blob: ef0f1ee6f3169f3f5ed44e4502bf4567690c988c [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Carlos Valdivia91979be2015-05-22 14:11:35 -070020import android.accounts.AbstractAccountAuthenticator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
25import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070026import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.accounts.GrantCredentialsPermissionActivity;
28import android.accounts.IAccountAuthenticator;
29import android.accounts.IAccountAuthenticatorResponse;
30import android.accounts.IAccountManager;
31import android.accounts.IAccountManagerResponse;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070032import android.annotation.NonNull;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080033import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070034import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070035import android.app.AppGlobals;
Svetoslavf3f02ac2015-09-08 14:36:35 -070036import android.app.AppOpsManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000040import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010041import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000042import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070043import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070044import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070045import android.content.ContentValues;
46import android.content.Context;
47import android.content.Intent;
48import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070049import android.content.ServiceConnection;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -080050import android.content.pm.ActivityInfo;
Doug Zongker885cfc232009-10-21 16:52:44 -070051import android.content.pm.ApplicationInfo;
52import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070053import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070054import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070055import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070056import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070057import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070058import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070059import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070060import android.database.Cursor;
61import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import android.database.sqlite.SQLiteDatabase;
63import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070064import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070065import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080067import android.os.Environment;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070068import android.os.FileUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.os.IBinder;
71import android.os.Looper;
72import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070073import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070074import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070075import android.os.RemoteException;
76import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070077import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070078import android.os.UserManager;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070079import android.os.storage.StorageManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070080import android.text.TextUtils;
81import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070082import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070083import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080084import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070085import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070086
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070087import com.android.internal.R;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070088import com.android.internal.annotations.VisibleForTesting;
Amith Yamasani67df64b2012-12-14 12:09:36 -080089import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080090import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -070091import com.android.internal.util.Preconditions;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070092import com.android.server.FgThread;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000093import com.android.server.LocalServices;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -060094import com.android.server.SystemService;
95
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070096import com.google.android.collect.Lists;
97import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070098
Oscar Montemayora8529f62009-11-18 10:14:20 -080099import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700100import java.io.FileDescriptor;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700101import java.io.IOException;
Fred Quintanaa698f422009-04-08 19:14:54 -0700102import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800103import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700104import java.security.MessageDigest;
105import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700106import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700107import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800108import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700109import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700110import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700111import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700112import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800113import java.util.LinkedHashMap;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700114import java.util.LinkedList;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700115import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800116import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800117import java.util.Map.Entry;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700118import java.util.Set;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700119import java.util.concurrent.atomic.AtomicInteger;
120import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700121
Fred Quintana60307342009-03-24 22:48:12 -0700122/**
123 * A system service that provides account, password, and authtoken management for all
124 * accounts on the device. Some of these calls are implemented with the help of the corresponding
125 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
126 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700127 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700128 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700129 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700130public class AccountManagerService
131 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800132 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700133 private static final String TAG = "AccountManagerService";
134
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600135 public static class Lifecycle extends SystemService {
136 private AccountManagerService mService;
137
138 public Lifecycle(Context context) {
139 super(context);
140 }
141
142 @Override
143 public void onStart() {
144 mService = new AccountManagerService(getContext());
145 publishBinderService(Context.ACCOUNT_SERVICE, mService);
146 }
147
148 @Override
149 public void onBootPhase(int phase) {
150 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
151 mService.systemReady();
152 }
153 }
154
155 @Override
156 public void onUnlockUser(int userHandle) {
157 mService.onUnlockUser(userHandle);
158 }
159 }
160
Fred Quintana60307342009-03-24 22:48:12 -0700161 private static final String DATABASE_NAME = "accounts.db";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700162 private static final int PRE_N_DATABASE_VERSION = 9;
163 private static final int CE_DATABASE_VERSION = 10;
164 private static final int DE_DATABASE_VERSION = 1;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700165
166 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700167
168 private final Context mContext;
169
Fred Quintana56285a62010-12-02 14:20:51 -0800170 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700171 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800173
Fred Quintana60307342009-03-24 22:48:12 -0700174 private final MessageHandler mMessageHandler;
175
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700176 /**
177 * Used to keep data read/write operations for logging purposes in a separate thread
178 * from main thread
179 */
180 private final LinkedList<Runnable> mLogRecordRunnables = new LinkedList<Runnable>();
181 private Thread mLogRecordThread;
182
Fred Quintana60307342009-03-24 22:48:12 -0700183 // Messages that can be sent on mHandler
184 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700185 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700186
Fred Quintana56285a62010-12-02 14:20:51 -0800187 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700188
189 private static final String TABLE_ACCOUNTS = "accounts";
190 private static final String ACCOUNTS_ID = "_id";
191 private static final String ACCOUNTS_NAME = "name";
192 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700193 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700194 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700195 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800196 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
197 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700198
199 private static final String TABLE_AUTHTOKENS = "authtokens";
200 private static final String AUTHTOKENS_ID = "_id";
201 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
202 private static final String AUTHTOKENS_TYPE = "type";
203 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
204
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700205 private static final String TABLE_GRANTS = "grants";
206 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
207 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
208 private static final String GRANTS_GRANTEE_UID = "uid";
209
Fred Quintana60307342009-03-24 22:48:12 -0700210 private static final String TABLE_EXTRAS = "extras";
211 private static final String EXTRAS_ID = "_id";
212 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
213 private static final String EXTRAS_KEY = "key";
214 private static final String EXTRAS_VALUE = "value";
215
216 private static final String TABLE_META = "meta";
217 private static final String META_KEY = "key";
218 private static final String META_VALUE = "value";
219
Amith Yamasani67df64b2012-12-14 12:09:36 -0800220 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700221 private static final String SHARED_ACCOUNTS_ID = "_id";
222
223 private static final String PRE_N_DATABASE_NAME = "accounts.db";
224 private static final String CE_DATABASE_NAME = "accounts_ce.db";
225 private static final String DE_DATABASE_NAME = "accounts_de.db";
226 private static final String CE_DB_PREFIX = "ceDb.";
227 private static final String CE_TABLE_ACCOUNTS = CE_DB_PREFIX + TABLE_ACCOUNTS;
228 private static final String CE_TABLE_AUTHTOKENS = CE_DB_PREFIX + TABLE_AUTHTOKENS;
229 private static final String CE_TABLE_EXTRAS = CE_DB_PREFIX + TABLE_EXTRAS;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800230
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700231 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
232 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700233 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800234
Carlos Valdivia91979be2015-05-22 14:11:35 -0700235 static {
236 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
237 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
238 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700239
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700240 private static final String COUNT_OF_MATCHING_GRANTS = ""
241 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
242 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
243 + " AND " + GRANTS_GRANTEE_UID + "=?"
244 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
245 + " AND " + ACCOUNTS_NAME + "=?"
246 + " AND " + ACCOUNTS_TYPE + "=?";
247
Fred Quintana56285a62010-12-02 14:20:51 -0800248 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
249 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700250
Fred Quintana56285a62010-12-02 14:20:51 -0800251 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
252 AUTHTOKENS_AUTHTOKEN};
253
254 private static final String SELECTION_USERDATA_BY_ACCOUNT =
255 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
256 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
257
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800258 private static final String META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX =
259 "auth_uid_for_type:";
260 private static final String META_KEY_DELIMITER = ":";
261 private static final String SELECTION_META_BY_AUTHENTICATOR_TYPE = META_KEY + " LIKE ?";
262
Fred Quintanaa698f422009-04-08 19:14:54 -0700263 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700264 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
265
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700266 private static final String NEW_ACCOUNT_VISIBLE = "android.accounts.NEW_ACCOUNT_VISIBLE";
267
Amith Yamasani04e0d262012-02-14 11:50:53 -0800268 static class UserAccounts {
269 private final int userId;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700270 private final DeDatabaseHelper openHelper;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800271 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
272 credentialsPermissionNotificationIds =
273 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
274 private final HashMap<Account, Integer> signinRequiredNotificationIds =
275 new HashMap<Account, Integer>();
276 private final Object cacheLock = new Object();
277 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700278 private final HashMap<String, Account[]> accountCache =
279 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800280 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700281 private final Map<Account, Map<String, String>> userDataCache = new HashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800282 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700283 private final Map<Account, Map<String, String>> authTokenCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700284
285 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700286 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700287
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700288 /** protected by the {@link #cacheLock} */
289 private final Map<String, ArrayList<Integer>> mApplicationAccountRequestMappings =
290 new HashMap<>();
291
292 /* Together the below two Sparse Arrays serve as visible list. One maps UID to account
293 number. Another maps Account number to Account.*/
294
295 /** protected by the {@link #cacheLock} */
296 private final SparseArray<ArrayList<Integer>> mVisibleListUidToMockAccountNumbers =
297 new SparseArray<>();
298
299 //TODO: Instead of using Mock Account IDs, use the actual account IDs.
300 /** protected by the {@link #cacheLock} */
301 private final SparseArray<Account> mMockAccountIdToAccount = new SparseArray<>();
302
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700303 /**
304 * protected by the {@link #cacheLock}
305 *
306 * Caches the previous names associated with an account. Previous names
307 * should be cached because we expect that when an Account is renamed,
308 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
309 * want to know if the accounts they care about have been renamed.
310 *
311 * The previous names are wrapped in an {@link AtomicReference} so that
312 * we can distinguish between those accounts with no previous names and
313 * those whose previous names haven't been cached (yet).
314 */
315 private final HashMap<Account, AtomicReference<String>> previousNameCache =
316 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800317
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700318 private int debugDbInsertionPoint = -1;
319 private SQLiteStatement statementForLogging;
320
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700321 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800322 this.userId = userId;
323 synchronized (cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700324 openHelper = DeDatabaseHelper.create(context, userId, preNDbFile, deDbFile);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800325 }
326 }
327 }
328
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700329 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600330 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800331
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700332 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700333 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700334
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700335 /**
336 * This should only be called by system code. One should only call this after the service
337 * has started.
338 * @return a reference to the AccountManagerService instance
339 * @hide
340 */
341 public static AccountManagerService getSingleton() {
342 return sThis.get();
343 }
Fred Quintana60307342009-03-24 22:48:12 -0700344
Fred Quintana56285a62010-12-02 14:20:51 -0800345 public AccountManagerService(Context context) {
346 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700347 }
348
Fred Quintana56285a62010-12-02 14:20:51 -0800349 public AccountManagerService(Context context, PackageManager packageManager,
350 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700351 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800352 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700353 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700354
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700355 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700356
Fred Quintana56285a62010-12-02 14:20:51 -0800357 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800358 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700359
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700360 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800361
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700362 addRequestsForPreInstalledApplications();
363
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800364 IntentFilter intentFilter = new IntentFilter();
365 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
366 intentFilter.addDataScheme("package");
367 mContext.registerReceiver(new BroadcastReceiver() {
368 @Override
369 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700370 // Don't delete accounts when updating a authenticator's
371 // package.
372 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700373 /* Purging data requires file io, don't block the main thread. This is probably
374 * less than ideal because we are introducing a race condition where old grants
375 * could be exercised until they are purged. But that race condition existed
376 * anyway with the broadcast receiver.
377 *
378 * Ideally, we would completely clear the cache, purge data from the database,
379 * and then rebuild the cache. All under the cache lock. But that change is too
380 * large at this point.
381 */
382 Runnable r = new Runnable() {
383 @Override
384 public void run() {
385 purgeOldGrantsAll();
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700386
387 /* clears application request's for account types supported */
388 int uidOfUninstalledApplication =
389 intent.getIntExtra(Intent.EXTRA_UID, -1);
390 if(uidOfUninstalledApplication != -1) {
391 clearRequestedAccountVisibility(uidOfUninstalledApplication,
392 getUserAccounts(UserHandle.getUserId(
393 uidOfUninstalledApplication)));
394 }
395
396 /* removes visibility of previous UID of this uninstalled application*/
397 removeAccountVisibilityAllAccounts(uidOfUninstalledApplication,
398 getUserAccounts(UserHandle.getUserId(
399 uidOfUninstalledApplication)));
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700400 }
401 };
402 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700403 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700404
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800405 }
406 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800407
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700408 IntentFilter packageAddedOrChangedFilter = new IntentFilter();
409 intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
410 packageAddedOrChangedFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
411 packageAddedOrChangedFilter.addDataScheme("package");
412 mContext.registerReceiverAsUser(new BroadcastReceiver() {
413 @Override
414 public void onReceive(Context context1, Intent intent) {
415 mMessageHandler.post(new Runnable() {
416 @Override
417 public void run() {
418 int uidOfInstalledApplication =
419 intent.getIntExtra(Intent.EXTRA_UID, -1);
420 if(uidOfInstalledApplication != -1) {
421 registerAccountTypesSupported(
422 uidOfInstalledApplication,
423 getUserAccounts(
424 UserHandle.getUserId(uidOfInstalledApplication)));
425 }
426 }
427 });
428 }
429 }, UserHandle.ALL, packageAddedOrChangedFilter, null, null);
430
Amith Yamasani13593602012-03-22 16:16:17 -0700431 IntentFilter userFilter = new IntentFilter();
432 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800433 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700434 @Override
435 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800436 String action = intent.getAction();
437 if (Intent.ACTION_USER_REMOVED.equals(action)) {
438 onUserRemoved(intent);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800439 }
Amith Yamasani13593602012-03-22 16:16:17 -0700440 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800441 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800442 }
443
Dianne Hackborn164371f2013-10-01 19:10:13 -0700444 @Override
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700445 public boolean addAccountExplicitlyWithUid(Account account, String password, Bundle extras,
446 int[] selectedUids) {
447 if(addAccountExplicitly(account,password,extras)) {
448 for(int thisUid : selectedUids) {
449 makeAccountVisible(account, thisUid);
450 }
451 return true;
452 }
453 return false;
454 }
455
456 @Override
457 public int[] getRequestingUidsForType(String accountType) {
458 int callingUid = Binder.getCallingUid();
459 if (!isAccountManagedByCaller(accountType, callingUid, UserHandle.getUserId(callingUid))) {
460 String msg = String.format(
461 "uid %s cannot get secrets for accounts of type: %s",
462 callingUid,
463 accountType);
464 throw new SecurityException(msg);
465 }
466 return getRequestingUidsForType(accountType, getUserAccounts(
467 UserHandle.getUserId(callingUid)));
468 }
469
470 /**
471 * Returns all UIDs for applications that requested the account type. This method
472 * is called indirectly by the Authenticator and AccountManager
473 *
474 * @param accountType authenticator would like to know the requesting apps of
475 * @param ua UserAccount that currently hosts the account and application
476 *
477 * @return ArrayList of all UIDs that support accounts of this
478 * account type that seek approval (to be used to know which accounts for
479 * the authenticator to include in addAccountExplicitly). Null if none.
480 */
481 private int[] getRequestingUidsForType(String accountType, UserAccounts ua) {
482 synchronized(ua.cacheLock) {
483 Map<String, ArrayList<Integer>> userApplicationAccountRequestMappings =
484 ua.mApplicationAccountRequestMappings;
485 ArrayList<Integer> allUidsForAccountType = userApplicationAccountRequestMappings.get(
486 accountType);
487 if(allUidsForAccountType == null) {
488 return null;
489 }
490 int[] toReturn = new int[allUidsForAccountType.size()];
491 for(int i = 0 ; i < toReturn.length ; i++) {
492 toReturn[i] = allUidsForAccountType.get(i);
493 }
494 return toReturn;
495 }
496 }
497
498 @Override
499 public boolean isAccountVisible(Account a, int uid) {
500 int callingUid = Binder.getCallingUid();
501 if (!isAccountManagedByCaller(a.type, callingUid, UserHandle.getUserId(callingUid))) {
502 String msg = String.format(
503 "uid %s cannot get secrets for accounts of type: %s",
504 callingUid,
505 a.type);
506 throw new SecurityException(msg);
507 }
508 return isAccountVisible(a, uid, getUserAccounts(UserHandle.getUserId(callingUid)));
509 }
510
511 /**
512 * Checks visibility of certain account of a process identified
513 * by a given UID. This is called by the Authenticator indirectly.
514 *
515 * @param a The account to check visibility of
516 * @param uid UID to check visibility of
517 * @param ua UserAccount that currently hosts the account and application
518 *
519 * @return True if application has access to the account
520 *
521 */
522 private boolean isAccountVisible(Account a, int uid, UserAccounts ua) {
Tejas Khorana69990d92016-08-03 11:19:40 -0700523 if(isAccountManagedByCaller(a.type, uid, UserHandle.getUserId(uid))) {
524 return true;
525 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700526 int accountMapping = getMockAccountNumber(a, ua);
527 if(accountMapping < 0) {
528 return true;
529 }
530 synchronized(ua.cacheLock) {
Tejas Khorana69990d92016-08-03 11:19:40 -0700531 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700532 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
533 ua.mVisibleListUidToMockAccountNumbers;
534 ArrayList<Integer> linkedAccountsToUid = userWlUidToMockAccountNums.get(uid);
Tejas Khorana69990d92016-08-03 11:19:40 -0700535 int indexOfAccountMapping = userAcctIdToAcctMap.indexOfValueByValue(a);
536 return indexOfAccountMapping == -1 || (linkedAccountsToUid != null
537 && linkedAccountsToUid.contains(accountMapping));
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700538 }
539 }
540
541 @Override
542 public boolean makeAccountVisible(Account a, int uid) {
543 int callingUid = Binder.getCallingUid();
544 if (!isAccountManagedByCaller(a.type, callingUid, UserHandle.getUserId(callingUid))) {
545 String msg = String.format(
546 "uid %s cannot get secrets for accounts of type: %s",
547 callingUid,
548 a.type);
549 throw new SecurityException(msg);
550 }
551 return makeAccountVisible(a, uid, getUserAccounts(UserHandle.getUserId(callingUid)));
552 }
553
554 /**
555 * Gives a certain UID, represented a application, access to an account. This method
556 * is called indirectly by the Authenticator.
557 *
558 * @param a Account to make visible
559 * @param uid to add visibility of the Account from
560 * @param ua UserAccount that currently hosts the account and application
561 *
562 * @return True if account made visible to application and was not previously visible.
563 */
564 private boolean makeAccountVisible(Account a, int uid, UserAccounts ua) {
565 int accountMapping = getMockAccountNumber(a, ua);
566 if(accountMapping < 0) {
567 accountMapping = makeAccountNumber(a, ua);
568 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700569 synchronized(ua.cacheLock) {
570 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
571 ua.mVisibleListUidToMockAccountNumbers;
572 ArrayList<Integer> linkedAccountsToUid = userWlUidToMockAccountNums.get(uid);
573 if(linkedAccountsToUid == null) {
574 linkedAccountsToUid = new ArrayList<>();
575 linkedAccountsToUid.add(accountMapping);
576 userWlUidToMockAccountNums.put(uid, linkedAccountsToUid);
577 } else if(!linkedAccountsToUid.contains(accountMapping)) {
578 linkedAccountsToUid.add(accountMapping);
579 } else {
580 return false;
581 }
582 }
583
584 String[] subPackages = mPackageManager.getPackagesForUid(uid);
585 if(subPackages != null) {
586 for(String subPackage : subPackages) {
587 sendNotification(subPackage, a);
588 }
589 }
590 return true;
591 }
592
593 @Override
594 public boolean removeAccountVisibility(Account a, int uid) {
595 int callingUid = Binder.getCallingUid();
596 if (!isAccountManagedByCaller(a.type, callingUid, UserHandle.getUserId(callingUid))) {
597 String msg = String.format(
598 "uid %s cannot get secrets for accounts of type: %s",
599 callingUid,
600 a.type);
601 throw new SecurityException(msg);
602 }
603 return removeAccountVisibility(a, uid, getUserAccounts(UserHandle.getUserId(callingUid)));
604 }
605
606 /**
607 * Removes visibility of certain account of a process identified
608 * by a given UID to an application. This is called directly by the
609 * AccountManager and indirectly by the Authenticator.
610 *
611 * @param a Account to remove visibility from
612 * @param uid UID to remove visibility of the Account from
613 * @param ua UserAccount that hosts the account and application
614 *
615 * @return True if application access to account removed and was previously visible.
616 */
617 private boolean removeAccountVisibility(Account a, int uid, UserAccounts ua) {
618 int accountMapping = getMockAccountNumber(a, ua);
619 if(accountMapping < 0) {
620 return false;
621 }
622 synchronized(ua.cacheLock) {
623 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
624 ua.mVisibleListUidToMockAccountNumbers;
625 ArrayList<Integer> linkedAccountsToUid = userWlUidToMockAccountNums.get(uid);
626 if(linkedAccountsToUid != null) {
627 boolean toReturn = linkedAccountsToUid.remove((Integer) accountMapping);
628 if(linkedAccountsToUid.size() == 0) {
629 userWlUidToMockAccountNums.remove(uid);
630 }
631 return toReturn;
632 }
633 }
634 return false;
635 }
636
637 /**
638 * Registers an application's preferences for supported account types for login. This is
639 * a helper method of requestAccountVisibility and indirectly called by AccountManager.
640 *
641 * @param accountTypes account types third party app is willing to support
642 * @param uid of application requesting account visibility
643 * @param ua UserAccount that hosts the account and application
644 */
645 private void addRequestedAccountsVisibility(String[] accountTypes, int uid, UserAccounts ua) {
646 synchronized(ua.cacheLock) {
647 Map<String, ArrayList<Integer>> userApplicationAccountRequestMappings =
648 ua.mApplicationAccountRequestMappings;
649 for(String accountType : accountTypes) {
650 ArrayList<Integer> accountUidAppList = userApplicationAccountRequestMappings
651 .get(accountType);
652 if(accountUidAppList == null) {
653 accountUidAppList = new ArrayList<>();
654 accountUidAppList.add(uid);
655 userApplicationAccountRequestMappings.put(accountType, accountUidAppList);
656 } else if (!accountUidAppList.contains(uid)) {
657 accountUidAppList.add(uid);
658 }
659 }
660 }
661 }
662
663 /**
664 * Registers the requested login account types requested by all the applications already
665 * installed on the device.
666 */
667 private void addRequestsForPreInstalledApplications() {
668 List<PackageInfo> allInstalledPackages = mContext.getPackageManager().
669 getInstalledPackages(0);
670 for(PackageInfo pi : allInstalledPackages) {
671 int currentUid = pi.applicationInfo.uid;
672 if(currentUid != -1) {
673 registerAccountTypesSupported(currentUid,
674 getUserAccounts(UserHandle.getUserId(currentUid)));
675 }
676 }
677 }
678
679 /**
680 * Clears all preferences an application had for login account types it offered
681 * support for. This method is used by AccountManager after application is
682 * uninstalled.
683 *
684 * @param uid Uid of the application to clear account type preferences
685 * @param ua UserAccount that hosted the account and application
686 *
687 * @return true if any previous settings were overridden.
688 */
689 private boolean clearRequestedAccountVisibility(int uid, UserAccounts ua) {
690 boolean accountsDeleted = false;
691 ArrayList<String> accountTypesToRemove = new ArrayList<>();
692 synchronized(ua.cacheLock) {
693 Map<String, ArrayList<Integer>> userApplicationAccountRequestMappings =
694 ua.mApplicationAccountRequestMappings;
695 Set<Entry<String, ArrayList<Integer>>> accountTypeAppListEntries =
696 userApplicationAccountRequestMappings.entrySet();
697
698 for(Entry<String, ArrayList<Integer>> entry : accountTypeAppListEntries) {
699 ArrayList<Integer> supportedApps = entry.getValue();
700 if(supportedApps.remove((Integer) uid)) {
701 accountsDeleted = true;
702 }
703
704 if(supportedApps.isEmpty()) {
705 accountTypesToRemove.add(entry.getKey());
706 }
707 }
708
709 for(String s : accountTypesToRemove) {
710 userApplicationAccountRequestMappings.remove(s);
711 }
712 }
713
714 return accountsDeleted;
715 }
716
717 /**
718 * Retrieves the mock account number associated with an Account in order to later retrieve
719 * the account from the Integer-Account Mapping. An account number is not the same as
720 * accountId in the database. This method can be indirectly called by AccountManager and
721 * indirectly by the Authenticator.
722 *
723 * @param a account to retrieve account number mapping
724 * @param ua UserAccount that currently hosts the account and application
725 *
726 * @return account number affiliated with the Account in question. Negative number if none.
727 */
728 private int getMockAccountNumber(Account a, UserAccounts ua) {
729 //TODO: Each account is linked to AccountId rather than generated mock account numbers
730 SparseArray<Account> userAcctIdToAcctMap =
731 ua.mMockAccountIdToAccount;
732 synchronized(ua.cacheLock) {
733 int indexOfAccount = userAcctIdToAcctMap.indexOfValueByValue(a);
734 if(indexOfAccount < 0) {
735 return -1;
736 }
737 return userAcctIdToAcctMap.keyAt(indexOfAccount);
738 }
739 }
740
741 /**
742 * Returns a full list of accounts that a certain UID is allowed access
743 * based on the visible list entries.
744 *
745 * @param uid of application to retrieve visible listed accounts for
746 * @param ua UserAccount that currently hosts the account and application
747 *
748 * @return array of Account values that are accessible by the given uids
749 */
750 private Account[] getVisibleListedAccounts(int uid, UserAccounts ua) {
751 ArrayList<Account> visibleListedAccounts = new ArrayList<>();
752 synchronized(ua.cacheLock) {
753 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
754 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
755 ua.mVisibleListUidToMockAccountNumbers;
756 ArrayList<Integer> visibleListedUidAccountNumbers =
757 userWlUidToMockAccountNums.get(uid);
758 if(visibleListedUidAccountNumbers != null) {
759 for(Integer accountNumber : visibleListedUidAccountNumbers) {
760 Account currentAccount = userAcctIdToAcctMap.get(accountNumber);
761 visibleListedAccounts.add(currentAccount);
762 }
763 }
764 }
765 Account[] arrVisibleListedAccounts = new Account[visibleListedAccounts.size()];
766 return visibleListedAccounts.toArray(arrVisibleListedAccounts);
767 }
768
769 /**
770 * Makes an account number for a given Account to be mapped to.
771 * This method is called by makeVisible if an Account does not have
772 * a mapping for the visible list. This method is thus indirectly
773 * called by the Authenticator.
774 *
775 * @param a account to make an account number mapping of
776 * @param ua UserAccount that currently hosts the account and application
777 *
778 * @return account number created to map to the given account
779 */
780 // TODO: Remove this method and use accountId from DB.
781 private int makeAccountNumber(Account a, UserAccounts ua) {
782 synchronized(ua.cacheLock) {
783 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
784 int newAccountMapping = 0;
785 while(userAcctIdToAcctMap.get(newAccountMapping) != null) {
786 newAccountMapping++;
787 }
788 userAcctIdToAcctMap.put(newAccountMapping, a);
789 return newAccountMapping;
790 }
791 }
792
793
794
795 /**
796 * Registers an application, represented by a UID, to support account types detailed in
797 * the applications manifest as well as allowing it to opt for notifications.
798 *
799 * @param uid UID of application
800 * @param ua UserAccount that currently hosts the account and application
801 */
802 private void registerAccountTypesSupported(int uid, UserAccounts ua) {
803 /* Account types supported are drawn from the Android Manifest of the Application */
804 String interestedPackages = null;
805 try {
806 String[] allPackages = mPackageManager.getPackagesForUid(uid);
807 for(String aPackage : allPackages) {
808 ApplicationInfo ai = mPackageManager.getApplicationInfo(aPackage,
809 PackageManager.GET_META_DATA);
810 Bundle b = ai.metaData;
811 if(b == null) {
812 return;
813 }
814 interestedPackages = b.getString("android.accounts.SupportedLoginTypes");
815 }
816 } catch (PackageManager.NameNotFoundException e) {
817 Log.d("NameNotFoundException", e.getMessage());
818 }
819 if(interestedPackages != null) {
820 /* request remote account types directly from here. Reads from Android Manifest */
821 requestAccountVisibility(interestedPackages.split(";"), uid, ua);
822 }
823 }
824
825 /**
826 * Allows AccountManager to register account types that an application has login
827 * support for. This method over-writes all of the application's previous settings
828 * for accounts it supported.
829 *
830 * @param accountTypes array of account types application wishes to support
831 * @param uid of application registering requested account types
832 * @param ua UserAccount that hosts the account and application
833 */
834 private void requestAccountVisibility(String[] accountTypes, int uid, UserAccounts ua) {
835 if(accountTypes.length > 0) {
836 clearRequestedAccountVisibility(uid, ua);
837 addRequestedAccountsVisibility(accountTypes, uid, ua);
838 }
839 }
840
841 /**
842 * Removes visibility of all Accounts to this particular UID. This is called when an
843 * application is uninstalled so another application that is installed with the same
844 * UID cannot access Accounts. This is called by AccountManager.
845 *
846 * @param uid of application to remove all Account visibility to
847 * @param ua UserAccount that hosts the current Account
848 */
849 private void removeAccountVisibilityAllAccounts(int uid, UserAccounts ua) {
850 synchronized(ua.cacheLock) {
851 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
852 ua.mVisibleListUidToMockAccountNumbers;
853 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
854 ArrayList<Integer> allAccountNumbersList = userWlUidToMockAccountNums.get(uid);
855 if(allAccountNumbersList != null) {
856 Integer[] allAccountNumbers = allAccountNumbersList.toArray(
857 new Integer[allAccountNumbersList.size()]);
858 for(int accountNum : allAccountNumbers) {
859 removeAccountVisibility(userAcctIdToAcctMap.get(accountNum), uid, ua);
860 }
861 }
862 }
863 }
864
865 /**
866 * Removes visible list functionality of a certain Account.
867 * This method is currently called by (1) addAccountExplicitly (as opposed to
868 * addAccountExplicitlyWithUid) and (2) removeAccountExplicitly.
869 *
870 * @param a the account to clear the visible list functionality for
871 * @param ua currently UserAccounts profile containing Account
872 *
873 * @return true if account previously had visible list functionality
874 */
875 private boolean removeVisibleListFunctionality(Account a, UserAccounts ua) {
876 int mockAccountNum = getMockAccountNumber(a, ua);
877 if(mockAccountNum < 0) {
878 return false;
879 }
880 synchronized(ua.cacheLock) {
881 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
882 ua.mVisibleListUidToMockAccountNumbers;
883 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
884
885 /* Removing mapping from account number to account removes visible list functionality*/
886 userAcctIdToAcctMap.remove(mockAccountNum);
887
888 for(int i = userWlUidToMockAccountNums.size() - 1 ; i >= 0 ; i--) {
889 int uidKey = userWlUidToMockAccountNums.keyAt(i);
890 ArrayList<Integer> allAccountNumbers = userWlUidToMockAccountNums.get(uidKey);
891 if(allAccountNumbers != null) {
892 allAccountNumbers.remove(mockAccountNum);
893 if(allAccountNumbers.isEmpty()) {
894 userWlUidToMockAccountNums.remove(uidKey);
895 }
896 }
897 }
898 }
899 return true;
900 }
901
902 /**
903 * Sends a direct intent to a package, notifying it of a visible account. This
904 * method is a helper method of makeAccountVisible.
905 *
906 * @param desiredPackage to send Account to
907 * @param visibleAccount to send to package
908 */
909 private void sendNotification(String desiredPackage, Account visibleAccount) {
910 Intent intent = new Intent();
911 intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
912 intent.setAction(NEW_ACCOUNT_VISIBLE);
913 intent.setPackage(desiredPackage);
914 intent.putExtra("android.accounts.KEY_ACCOUNT", (Account) visibleAccount);
915 mContext.sendBroadcast(intent);
916 }
917
918 @Override
Dianne Hackborn164371f2013-10-01 19:10:13 -0700919 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
920 throws RemoteException {
921 try {
922 return super.onTransact(code, data, reply, flags);
923 } catch (RuntimeException e) {
924 // The account manager only throws security exceptions, so let's
925 // log all others.
926 if (!(e instanceof SecurityException)) {
927 Slog.wtf(TAG, "Account Manager Crash", e);
928 }
929 throw e;
930 }
931 }
932
Kenny Root26ff6622012-07-30 12:58:03 -0700933 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700934 }
935
Amith Yamasani258848d2012-08-10 17:06:33 -0700936 private UserManager getUserManager() {
937 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700938 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700939 }
940 return mUserManager;
941 }
942
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700943 /**
944 * Validate internal set of accounts against installed authenticators for
945 * given user. Clears cached authenticators before validating.
946 */
947 public void validateAccounts(int userId) {
948 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700949 // Invalidate user-specific cache to make sure we catch any
950 // removed authenticators.
951 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
952 }
953
954 /**
955 * Validate internal set of accounts against installed authenticators for
956 * given user. Clear cached authenticators before validating when requested.
957 */
958 private void validateAccountsInternal(
959 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700960 if (Log.isLoggable(TAG, Log.DEBUG)) {
961 Log.d(TAG, "validateAccountsInternal " + accounts.userId
962 + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600963 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700964 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700965
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700966 if (invalidateAuthenticatorCache) {
967 mAuthenticatorCache.invalidateCache(accounts.userId);
968 }
969
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700970 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
971 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -0700972 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700973
Amith Yamasani04e0d262012-02-14 11:50:53 -0800974 synchronized (accounts.cacheLock) {
975 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800976 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800977
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700978 // Get a map of stored authenticator types to UID
979 Map<String, Integer> metaAuthUid = AccountsDbUtils.findMetaAuthUid(db);
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800980 // Create a list of authenticator type whose previous uid no longer exists
981 HashSet<String> obsoleteAuthType = Sets.newHashSet();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700982 SparseBooleanArray knownUids = null;
983 for (Entry<String, Integer> authToUidEntry : metaAuthUid.entrySet()) {
984 String type = authToUidEntry.getKey();
985 int uid = authToUidEntry.getValue();
986 Integer knownUid = knownAuth.get(type);
987 if (knownUid != null && uid == knownUid) {
988 // Remove it from the knownAuth list if it's unchanged.
989 knownAuth.remove(type);
990 } else {
991 /*
992 * The authenticator is presently not cached and should only be triggered
993 * when we think an authenticator has been removed (or is being updated).
994 * But we still want to check if any data with the associated uid is
995 * around. This is an (imperfect) signal that the package may be updating.
996 *
997 * A side effect of this is that an authenticator sharing a uid with
998 * multiple apps won't get its credentials wiped as long as some app with
999 * that uid is still on the device. But I suspect that this is a rare case.
1000 * And it isn't clear to me how an attacker could really exploit that
1001 * feature.
1002 *
1003 * The upshot is that we don't have to worry about accounts getting
1004 * uninstalled while the authenticator's package is being updated.
1005 *
1006 */
1007 if (knownUids == null) {
1008 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001009 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001010 if (!knownUids.get(uid)) {
1011 // The authenticator is not presently available to the cache. And the
1012 // package no longer has a data directory (so we surmise it isn't updating).
1013 // So purge its data from the account databases.
1014 obsoleteAuthType.add(type);
1015 // And delete it from the TABLE_META
1016 AccountsDbUtils.deleteMetaByAuthTypeAndUid(db, type, uid);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001017 }
1018 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001019 }
1020
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001021 // Add the newly registered authenticator to TABLE_META. If old authenticators have
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001022 // been re-enabled (after being updated for example), then we just overwrite the old
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001023 // values.
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001024 for (Entry<String, Integer> entry : knownAuth.entrySet()) {
1025 AccountsDbUtils.insertOrReplaceMetaAuthTypeAndUid(db, entry.getKey(),
1026 entry.getValue());
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001027 }
1028
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001029 final Map<Long, Account> accountsMap = AccountsDbUtils.findAllAccounts(db);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001030 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001031 accounts.accountCache.clear();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001032 final HashMap<String, ArrayList<String>> accountNamesByType = new LinkedHashMap<>();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001033 for (Entry<Long, Account> accountEntry : accountsMap.entrySet()) {
1034 final long accountId = accountEntry.getKey();
1035 final Account account = accountEntry.getValue();
1036 if (obsoleteAuthType.contains(account.type)) {
1037 Slog.w(TAG, "deleting account " + account.name + " because type "
1038 + account.type + "'s registered authenticator no longer exist.");
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001039 db.beginTransaction();
1040 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001041 AccountsDbUtils.deleteAccount(db, accountId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001042 // Also delete from CE table if user is unlocked; if user is currently
1043 // locked the account will be removed later by syncDeCeAccountsLocked
1044 if (userUnlocked) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001045 AccountsDbUtils.deleteCeAccount(db, accountId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001046 }
1047 db.setTransactionSuccessful();
1048 } finally {
1049 db.endTransaction();
1050 }
Fred Quintana56285a62010-12-02 14:20:51 -08001051 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001052
1053 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
1054 accountId, accounts);
1055
Amith Yamasani04e0d262012-02-14 11:50:53 -08001056 accounts.userDataCache.remove(account);
1057 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001058 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08001059 } else {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001060 ArrayList<String> accountNames = accountNamesByType.get(account.type);
Fred Quintana56285a62010-12-02 14:20:51 -08001061 if (accountNames == null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001062 accountNames = new ArrayList<>();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001063 accountNamesByType.put(account.type, accountNames);
Fred Quintana56285a62010-12-02 14:20:51 -08001064 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001065 accountNames.add(account.name);
Fred Quintana56285a62010-12-02 14:20:51 -08001066 }
1067 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001068 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -08001069 final String accountType = cur.getKey();
1070 final ArrayList<String> accountNames = cur.getValue();
1071 final Account[] accountsForType = new Account[accountNames.size()];
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001072 for (int i = 0; i < accountsForType.length; i++) {
1073 accountsForType[i] = new Account(accountNames.get(i), accountType);
Fred Quintana56285a62010-12-02 14:20:51 -08001074 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001075 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -08001076 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001077 } finally {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001078 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001079 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001080 }
Fred Quintanaafa92b82009-12-01 16:27:03 -08001081 }
1082 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001083 }
1084
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001085 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
1086 // Get the UIDs of all apps that might have data on the device. We want
1087 // to preserve user data if the app might otherwise be storing data.
1088 List<PackageInfo> pkgsWithData =
1089 mPackageManager.getInstalledPackagesAsUser(
1090 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1091 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
1092 for (PackageInfo pkgInfo : pkgsWithData) {
1093 if (pkgInfo.applicationInfo != null
1094 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
1095 knownUids.put(pkgInfo.applicationInfo.uid, true);
1096 }
1097 }
1098 return knownUids;
1099 }
1100
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001101 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1102 Context context,
1103 int userId) {
1104 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001105 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
1106 }
1107
1108 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1109 IAccountAuthenticatorCache authCache,
1110 int userId) {
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001111 HashMap<String, Integer> knownAuth = new HashMap<>();
1112 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
1113 .getAllServices(userId)) {
1114 knownAuth.put(service.type.type, service.uid);
1115 }
1116 return knownAuth;
1117 }
1118
Amith Yamasani04e0d262012-02-14 11:50:53 -08001119 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001120 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001121 }
1122
1123 protected UserAccounts getUserAccounts(int userId) {
1124 synchronized (mUsers) {
1125 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001126 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001127 if (accounts == null) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001128 File preNDbFile = new File(getPreNDatabaseName(userId));
1129 File deDbFile = new File(getDeDatabaseName(userId));
1130 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001131 initializeDebugDbSizeAndCompileSqlStatementForLogging(
1132 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001133 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001134 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001135 validateAccounts = true;
1136 }
1137 // open CE database if necessary
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001138 if (!accounts.openHelper.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001139 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
1140 synchronized (accounts.cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001141 File preNDatabaseFile = new File(getPreNDatabaseName(userId));
1142 File ceDatabaseFile = new File(getCeDatabaseName(userId));
1143 CeDatabaseHelper.create(mContext, userId, preNDatabaseFile, ceDatabaseFile);
1144 accounts.openHelper.attachCeDatabase(ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001145 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001146 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001147 }
1148 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001149 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001150 }
1151 return accounts;
1152 }
1153 }
1154
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001155 private void syncDeCeAccountsLocked(UserAccounts accounts) {
1156 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
1157 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001158 List<Account> accountsToRemove = AccountsDbUtils.findCeAccountsNotInDe(db);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001159 if (!accountsToRemove.isEmpty()) {
1160 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
1161 + accounts.userId + " was locked. Removing accounts from CE tables");
1162 logRecord(accounts, DebugDbHelper.ACTION_SYNC_DE_CE_ACCOUNTS, TABLE_ACCOUNTS);
1163
1164 for (Account account : accountsToRemove) {
1165 removeAccountInternal(accounts, account, Process.myUid());
1166 }
1167 }
1168 }
1169
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001170 private void purgeOldGrantsAll() {
1171 synchronized (mUsers) {
1172 for (int i = 0; i < mUsers.size(); i++) {
1173 purgeOldGrants(mUsers.valueAt(i));
1174 }
1175 }
1176 }
1177
1178 private void purgeOldGrants(UserAccounts accounts) {
1179 synchronized (accounts.cacheLock) {
1180 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001181 List<Integer> uids = AccountsDbUtils.findAllUidGrants(db);
1182 for (int uid : uids) {
1183 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
1184 if (packageExists) {
1185 continue;
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001186 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001187 Log.d(TAG, "deleting grants for UID " + uid
1188 + " because its package is no longer installed");
1189 AccountsDbUtils.deleteGrantsByUid(db, uid);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001190 }
1191 }
1192 }
1193
Amith Yamasani13593602012-03-22 16:16:17 -07001194 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001195 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -07001196 if (userId < 1) return;
1197
1198 UserAccounts accounts;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001199 boolean userUnlocked;
Amith Yamasani13593602012-03-22 16:16:17 -07001200 synchronized (mUsers) {
1201 accounts = mUsers.get(userId);
1202 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001203 userUnlocked = mLocalUnlockedUsers.get(userId);
1204 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001205 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001206 if (accounts != null) {
1207 synchronized (accounts.cacheLock) {
1208 accounts.openHelper.close();
1209 }
Amith Yamasani13593602012-03-22 16:16:17 -07001210 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001211 Log.i(TAG, "Removing database files for user " + userId);
1212 File dbFile = new File(getDeDatabaseName(userId));
Amith Yamasani13593602012-03-22 16:16:17 -07001213
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001214 deleteDbFileWarnIfFailed(dbFile);
1215 // Remove CE file if user is unlocked, or FBE is not enabled
1216 boolean fbeEnabled = StorageManager.isFileEncryptedNativeOrEmulated();
1217 if (!fbeEnabled || userUnlocked) {
1218 File ceDb = new File(getCeDatabaseName(userId));
1219 if (ceDb.exists()) {
1220 deleteDbFileWarnIfFailed(ceDb);
1221 }
1222 }
1223 }
1224
1225 private static void deleteDbFileWarnIfFailed(File dbFile) {
1226 if (!SQLiteDatabase.deleteDatabase(dbFile)) {
1227 Log.w(TAG, "Database at " + dbFile + " was not deleted successfully");
Amith Yamasani13593602012-03-22 16:16:17 -07001228 }
1229 }
1230
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001231 @VisibleForTesting
1232 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -06001233 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
1234 }
1235
1236 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001237 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1238 Log.v(TAG, "onUserUnlocked " + userId);
1239 }
1240 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001241 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001242 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001243 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001244 syncSharedAccounts(userId);
1245 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001246
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001247 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001248 // Check if there's a shared account that needs to be created as an account
1249 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
1250 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -07001251 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001252 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001253 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001254 : UserHandle.USER_SYSTEM;
1255 if (parentUserId < 0) {
1256 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
1257 return;
1258 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001259 for (Account sa : sharedAccounts) {
1260 if (ArrayUtils.contains(accounts, sa)) continue;
1261 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001262 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001263 }
1264 }
1265
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001266 @Override
1267 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001268 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -07001269 }
1270
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001271 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001272 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001273 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001274 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1275 Log.v(TAG, "getPassword: " + account
1276 + ", caller's uid " + Binder.getCallingUid()
1277 + ", pid " + Binder.getCallingPid());
1278 }
Fred Quintana382601f2010-03-25 12:25:10 -07001279 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001280 int userId = UserHandle.getCallingUserId();
1281 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001282 String msg = String.format(
1283 "uid %s cannot get secrets for accounts of type: %s",
1284 callingUid,
1285 account.type);
1286 throw new SecurityException(msg);
1287 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001288 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001289 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001290 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001291 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001292 } finally {
1293 restoreCallingIdentity(identityToken);
1294 }
1295 }
1296
Amith Yamasani04e0d262012-02-14 11:50:53 -08001297 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -07001298 if (account == null) {
1299 return null;
1300 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001301 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001302 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
1303 return null;
1304 }
Fred Quintana31957f12009-10-21 13:43:10 -07001305
Amith Yamasani04e0d262012-02-14 11:50:53 -08001306 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001307 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001308 return AccountsDbUtils.findAccountPasswordByNameAndType(db, account.name,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001309 account.type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001310 }
1311 }
1312
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001313 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001314 public String getPreviousName(Account account) {
1315 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1316 Log.v(TAG, "getPreviousName: " + account
1317 + ", caller's uid " + Binder.getCallingUid()
1318 + ", pid " + Binder.getCallingPid());
1319 }
1320 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001321 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001322 long identityToken = clearCallingIdentity();
1323 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001324 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001325 return readPreviousNameInternal(accounts, account);
1326 } finally {
1327 restoreCallingIdentity(identityToken);
1328 }
1329 }
1330
1331 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
1332 if (account == null) {
1333 return null;
1334 }
1335 synchronized (accounts.cacheLock) {
1336 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
1337 if (previousNameRef == null) {
1338 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001339 String previousName = AccountsDbUtils.findAccountPreviousName(db, account);
1340 previousNameRef = new AtomicReference<>(previousName);
1341 accounts.previousNameCache.put(account, previousNameRef);
1342 return previousName;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001343 } else {
1344 return previousNameRef.get();
1345 }
1346 }
1347 }
1348
1349 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001350 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001351 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001352 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001353 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1354 account, key, callingUid, Binder.getCallingPid());
1355 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001356 }
Fred Quintana382601f2010-03-25 12:25:10 -07001357 if (account == null) throw new IllegalArgumentException("account is null");
1358 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001359 int userId = UserHandle.getCallingUserId();
1360 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001361 String msg = String.format(
1362 "uid %s cannot get user data for accounts of type: %s",
1363 callingUid,
1364 account.type);
1365 throw new SecurityException(msg);
1366 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001367 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001368 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1369 return null;
1370 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001371 long identityToken = clearCallingIdentity();
1372 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001373 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00001374 synchronized (accounts.cacheLock) {
1375 if (!accountExistsCacheLocked(accounts, account)) {
1376 return null;
1377 }
1378 return readUserDataInternalLocked(accounts, account, key);
1379 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001380 } finally {
1381 restoreCallingIdentity(identityToken);
1382 }
1383 }
1384
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001385 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001386 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001387 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001388 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1389 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001390 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001391 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001392 + ", pid " + Binder.getCallingPid());
1393 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001394 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001395 if (isCrossUser(callingUid, userId)) {
1396 throw new SecurityException(
1397 String.format(
1398 "User %s tying to get authenticator types for %s" ,
1399 UserHandle.getCallingUserId(),
1400 userId));
1401 }
1402
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001403 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001404 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001405 return getAuthenticatorTypesInternal(userId);
1406
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001407 } finally {
1408 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001409 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001410 }
1411
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001412 /**
1413 * Should only be called inside of a clearCallingIdentity block.
1414 */
1415 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
1416 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1417 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1418 AuthenticatorDescription[] types =
1419 new AuthenticatorDescription[authenticatorCollection.size()];
1420 int i = 0;
1421 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1422 : authenticatorCollection) {
1423 types[i] = authenticator.type;
1424 i++;
1425 }
1426 return types;
1427 }
1428
1429
1430
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001431 private boolean isCrossUser(int callingUid, int userId) {
1432 return (userId != UserHandle.getCallingUserId()
1433 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001434 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001435 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1436 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001437 }
1438
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001439 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001440 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001441 Bundle.setDefusable(extras, true);
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001442 // clears the visible list functionality for this account because this method allows
1443 // default account access to all applications for account.
1444
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001445 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001446 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001447 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001448 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001449 + ", pid " + Binder.getCallingPid());
1450 }
Fred Quintana382601f2010-03-25 12:25:10 -07001451 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001452 int userId = UserHandle.getCallingUserId();
1453 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001454 String msg = String.format(
1455 "uid %s cannot explicitly add accounts of type: %s",
1456 callingUid,
1457 account.type);
1458 throw new SecurityException(msg);
1459 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001460 removeVisibleListFunctionality(account, getUserAccounts(UserHandle.getUserId(callingUid)));
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001461 /*
1462 * Child users are not allowed to add accounts. Only the accounts that are
1463 * shared by the parent profile can be added to child profile.
1464 *
1465 * TODO: Only allow accounts that were shared to be added by
1466 * a limited user.
1467 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001468
Fred Quintana60307342009-03-24 22:48:12 -07001469 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001470 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001471 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001472 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001473 return addAccountInternal(accounts, account, password, extras, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -07001474 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001475 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001476 }
1477 }
1478
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001479 @Override
1480 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001481 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001482 int callingUid = Binder.getCallingUid();
1483 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1484 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001485 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001486 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001487 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1488 final UserAccounts toAccounts = getUserAccounts(userTo);
1489 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001490 if (response != null) {
1491 Bundle result = new Bundle();
1492 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1493 try {
1494 response.onResult(result);
1495 } catch (RemoteException e) {
1496 Slog.w(TAG, "Failed to report error back to the client." + e);
1497 }
1498 }
1499 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001500 }
1501
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001502 Slog.d(TAG, "Copying account " + account.name
1503 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001504 long identityToken = clearCallingIdentity();
1505 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001506 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001507 false /* stripAuthTokenFromResult */, account.name,
1508 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001509 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001510 protected String toDebugString(long now) {
1511 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1512 + ", " + account.type;
1513 }
1514
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001515 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001516 public void run() throws RemoteException {
1517 mAuthenticator.getAccountCredentialsForCloning(this, account);
1518 }
1519
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001520 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001521 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001522 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001523 if (result != null
1524 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1525 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001526 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001527 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001528 super.onResult(result);
1529 }
1530 }
1531 }.bind();
1532 } finally {
1533 restoreCallingIdentity(identityToken);
1534 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001535 }
1536
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001537 @Override
1538 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001539 final int callingUid = Binder.getCallingUid();
1540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1541 String msg = String.format(
1542 "accountAuthenticated( account: %s, callerUid: %s)",
1543 account,
1544 callingUid);
1545 Log.v(TAG, msg);
1546 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001547 if (account == null) {
1548 throw new IllegalArgumentException("account is null");
1549 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001550 int userId = UserHandle.getCallingUserId();
1551 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001552 String msg = String.format(
1553 "uid %s cannot notify authentication for accounts of type: %s",
1554 callingUid,
1555 account.type);
1556 throw new SecurityException(msg);
1557 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001558
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001559 if (!canUserModifyAccounts(userId, callingUid) ||
1560 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001561 return false;
1562 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001563
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001564 long identityToken = clearCallingIdentity();
1565 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001566 UserAccounts accounts = getUserAccounts(userId);
1567 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001568 } finally {
1569 restoreCallingIdentity(identityToken);
1570 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001571 }
1572
1573 private boolean updateLastAuthenticatedTime(Account account) {
1574 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001575 synchronized (accounts.cacheLock) {
1576 final ContentValues values = new ContentValues();
1577 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
1578 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1579 int i = db.update(
1580 TABLE_ACCOUNTS,
1581 values,
1582 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1583 new String[] {
1584 account.name, account.type
1585 });
1586 if (i > 0) {
1587 return true;
1588 }
1589 }
1590 return false;
1591 }
1592
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001593 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001594 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1595 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001596 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001597 long id = clearCallingIdentity();
1598 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001599 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001600 false /* stripAuthTokenFromResult */, account.name,
1601 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001602 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001603 protected String toDebugString(long now) {
1604 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1605 + ", " + account.type;
1606 }
1607
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001608 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001609 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001610 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001611 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001612 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -07001613 for (Account acc : getAccounts(parentUserId,
1614 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001615 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001616 mAuthenticator.addAccountFromCredentials(
1617 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001618 break;
1619 }
1620 }
1621 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001622 }
1623
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001624 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001625 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001626 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001627 // TODO: Anything to do if if succedded?
1628 // TODO: If it failed: Show error notification? Should we remove the shadow
1629 // account to avoid retries?
1630 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001631 }
1632
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001633 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001634 public void onError(int errorCode, String errorMessage) {
1635 super.onError(errorCode, errorMessage);
1636 // TODO: Show error notification to user
1637 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1638 }
1639
1640 }.bind();
1641 } finally {
1642 restoreCallingIdentity(id);
1643 }
1644 }
1645
Amith Yamasani04e0d262012-02-14 11:50:53 -08001646 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001647 Bundle extras, int callingUid) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001648 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001649 if (account == null) {
1650 return false;
1651 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001652 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001653 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1654 + " is locked. callingUid=" + callingUid);
1655 return false;
1656 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001657 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001658 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001659 db.beginTransaction();
1660 try {
1661 long numMatches = DatabaseUtils.longForQuery(db,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001662 "select count(*) from " + CE_TABLE_ACCOUNTS
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001663 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1664 new String[]{account.name, account.type});
1665 if (numMatches > 0) {
1666 Log.w(TAG, "insertAccountIntoDatabase: " + account
1667 + ", skipping since the account already exists");
1668 return false;
1669 }
1670 ContentValues values = new ContentValues();
1671 values.put(ACCOUNTS_NAME, account.name);
1672 values.put(ACCOUNTS_TYPE, account.type);
1673 values.put(ACCOUNTS_PASSWORD, password);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001674 long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001675 if (accountId < 0) {
1676 Log.w(TAG, "insertAccountIntoDatabase: " + account
1677 + ", skipping the DB insert failed");
1678 return false;
1679 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001680 // Insert into DE table
1681 values = new ContentValues();
1682 values.put(ACCOUNTS_ID, accountId);
1683 values.put(ACCOUNTS_NAME, account.name);
1684 values.put(ACCOUNTS_TYPE, account.type);
1685 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1686 System.currentTimeMillis());
1687 if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1688 Log.w(TAG, "insertAccountIntoDatabase: " + account
1689 + ", skipping the DB insert failed");
1690 return false;
1691 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001692 if (extras != null) {
1693 for (String key : extras.keySet()) {
1694 final String value = extras.getString(key);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001695 if (AccountsDbUtils.insertExtra(db, accountId, key, value) < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001696 Log.w(TAG, "insertAccountIntoDatabase: " + account
1697 + ", skipping since insertExtra failed for key " + key);
1698 return false;
1699 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001700 }
1701 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001702 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001703
1704 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1705 accounts, callingUid);
1706
Amith Yamasani04e0d262012-02-14 11:50:53 -08001707 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001708 } finally {
1709 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001710 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001711 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001712 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1713 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001714 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001715
1716 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1717 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001718 return true;
1719 }
1720
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001721 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001722 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001723 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001724 }
1725 }
1726
Amith Yamasani5be347b2013-03-31 17:44:31 -07001727 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001728 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001729 * running, then clone the account too.
1730 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001731 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001732 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001733 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001734 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001735 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001736 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001737 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001738 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001739 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1740 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001741 }
1742 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001743 }
1744 }
1745
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001746 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001747 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001748 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001749 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001750 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1751 Log.v(TAG, "hasFeatures: " + account
1752 + ", response " + response
1753 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001754 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001755 + ", pid " + Binder.getCallingPid());
1756 }
Fred Quintana382601f2010-03-25 12:25:10 -07001757 if (response == null) throw new IllegalArgumentException("response is null");
1758 if (account == null) throw new IllegalArgumentException("account is null");
1759 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001760 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001761 checkReadAccountsPermitted(callingUid, account.type, userId,
1762 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001763
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001764 long identityToken = clearCallingIdentity();
1765 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001766 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001767 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001768 } finally {
1769 restoreCallingIdentity(identityToken);
1770 }
1771 }
1772
1773 private class TestFeaturesSession extends Session {
1774 private final String[] mFeatures;
1775 private final Account mAccount;
1776
Amith Yamasani04e0d262012-02-14 11:50:53 -08001777 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001778 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001779 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001780 true /* stripAuthTokenFromResult */, account.name,
1781 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001782 mFeatures = features;
1783 mAccount = account;
1784 }
1785
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001786 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001787 public void run() throws RemoteException {
1788 try {
1789 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1790 } catch (RemoteException e) {
1791 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1792 }
1793 }
1794
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001795 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001796 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001797 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001798 IAccountManagerResponse response = getResponseAndClose();
1799 if (response != null) {
1800 try {
1801 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001802 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001803 return;
1804 }
Fred Quintana56285a62010-12-02 14:20:51 -08001805 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1806 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1807 + response);
1808 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001809 final Bundle newResult = new Bundle();
1810 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1811 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1812 response.onResult(newResult);
1813 } catch (RemoteException e) {
1814 // if the caller is dead then there is no one to care about remote exceptions
1815 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1816 Log.v(TAG, "failure while notifying response", e);
1817 }
1818 }
1819 }
1820 }
1821
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001822 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001823 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001824 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001825 + ", " + mAccount
1826 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1827 }
1828 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001829
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001830 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001831 public void renameAccount(
1832 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001833 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001834 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1835 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001836 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001837 + ", pid " + Binder.getCallingPid());
1838 }
1839 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001840 int userId = UserHandle.getCallingUserId();
1841 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001842 String msg = String.format(
1843 "uid %s cannot rename accounts of type: %s",
1844 callingUid,
1845 accountToRename.type);
1846 throw new SecurityException(msg);
1847 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001848 long identityToken = clearCallingIdentity();
1849 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001850 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001851 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001852 Bundle result = new Bundle();
1853 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1854 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1855 try {
1856 response.onResult(result);
1857 } catch (RemoteException e) {
1858 Log.w(TAG, e.getMessage());
1859 }
1860 } finally {
1861 restoreCallingIdentity(identityToken);
1862 }
1863 }
1864
1865 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001866 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001867 Account resultAccount = null;
1868 /*
1869 * Cancel existing notifications. Let authenticators
1870 * re-post notifications as required. But we don't know if
1871 * the authenticators have bound their notifications to
1872 * now stale account name data.
1873 *
1874 * With a rename api, we might not need to do this anymore but it
1875 * shouldn't hurt.
1876 */
1877 cancelNotification(
1878 getSigninRequiredNotificationId(accounts, accountToRename),
1879 new UserHandle(accounts.userId));
1880 synchronized(accounts.credentialsPermissionNotificationIds) {
1881 for (Pair<Pair<Account, String>, Integer> pair:
1882 accounts.credentialsPermissionNotificationIds.keySet()) {
1883 if (accountToRename.equals(pair.first.first)) {
1884 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1885 cancelNotification(id, new UserHandle(accounts.userId));
1886 }
1887 }
1888 }
1889 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001890 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001891 db.beginTransaction();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001892 Account renamedAccount = new Account(newName, accountToRename.type);
1893 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001894 final long accountId = AccountsDbUtils.findAccountId(db, accountToRename);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001895 if (accountId >= 0) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001896 final ContentValues values = new ContentValues();
1897 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001898 final String[] argsAccountId = { String.valueOf(accountId) };
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001899 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1900 // Update NAME/PREVIOUS_NAME in DE accounts table
1901 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001902 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1903 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001904 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1905 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001906 }
1907 } finally {
1908 db.endTransaction();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001909 }
1910 /*
1911 * Database transaction was successful. Clean up cached
1912 * data associated with the account in the user profile.
1913 */
1914 insertAccountIntoCacheLocked(accounts, renamedAccount);
1915 /*
1916 * Extract the data and token caches before removing the
1917 * old account to preserve the user data associated with
1918 * the account.
1919 */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001920 Map<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1921 Map<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001922 removeAccountFromCacheLocked(accounts, accountToRename);
1923 /*
1924 * Update the cached data associated with the renamed
1925 * account.
1926 */
1927 accounts.userDataCache.put(renamedAccount, tmpData);
1928 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1929 accounts.previousNameCache.put(
1930 renamedAccount,
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001931 new AtomicReference<>(accountToRename.name));
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001932 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001933
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001934 int parentUserId = accounts.userId;
1935 if (canHaveProfile(parentUserId)) {
1936 /*
1937 * Owner or system user account was renamed, rename the account for
1938 * those users with which the account was shared.
1939 */
1940 List<UserInfo> users = getUserManager().getUsers(true);
1941 for (UserInfo user : users) {
1942 if (user.isRestricted()
1943 && (user.restrictedProfileParentId == parentUserId)) {
1944 renameSharedAccountAsUser(accountToRename, newName, user.id);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001945 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001946 }
1947 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001948 sendAccountsChangedBroadcast(accounts.userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001949 }
1950 return resultAccount;
1951 }
1952
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001953 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001954 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001955 return userInfo != null && userInfo.canHaveProfile();
1956 }
1957
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001958 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001959 public void removeAccount(IAccountManagerResponse response, Account account,
1960 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001961 removeAccountAsUser(
1962 response,
1963 account,
1964 expectActivityLaunch,
1965 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001966 }
1967
1968 @Override
1969 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001970 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001971 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001972 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1973 Log.v(TAG, "removeAccount: " + account
1974 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001975 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001976 + ", pid " + Binder.getCallingPid()
1977 + ", for user id " + userId);
1978 }
1979 if (response == null) throw new IllegalArgumentException("response is null");
1980 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001981 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001982 if (isCrossUser(callingUid, userId)) {
1983 throw new SecurityException(
1984 String.format(
1985 "User %s tying remove account for %s" ,
1986 UserHandle.getCallingUserId(),
1987 userId));
1988 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001989 /*
1990 * Only the system or authenticator should be allowed to remove accounts for that
1991 * authenticator. This will let users remove accounts (via Settings in the system) but not
1992 * arbitrary applications (like competing authenticators).
1993 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001994 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001995 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1996 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001997 String msg = String.format(
1998 "uid %s cannot remove accounts of type: %s",
1999 callingUid,
2000 account.type);
2001 throw new SecurityException(msg);
2002 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002003 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002004 try {
2005 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2006 "User cannot modify accounts");
2007 } catch (RemoteException re) {
2008 }
2009 return;
2010 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002011 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002012 try {
2013 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2014 "User cannot modify accounts of this type (policy).");
2015 } catch (RemoteException re) {
2016 }
2017 return;
2018 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002019 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002020 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002021 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002022 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002023 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08002024 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002025 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002026 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002027 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002028 }
2029 }
2030 }
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002031 SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002032 final long accountId = AccountsDbUtils.findAccountId(db, account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002033 logRecord(
2034 db,
2035 DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE,
2036 TABLE_ACCOUNTS,
2037 accountId,
2038 accounts,
2039 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002040 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002041 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
2042 } finally {
2043 restoreCallingIdentity(identityToken);
2044 }
2045 }
2046
2047 @Override
2048 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002049 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002050 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2051 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002052 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002053 + ", pid " + Binder.getCallingPid());
2054 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002055 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002056 if (account == null) {
2057 /*
2058 * Null accounts should result in returning false, as per
2059 * AccountManage.addAccountExplicitly(...) java doc.
2060 */
2061 Log.e(TAG, "account is null");
2062 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002063 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002064 String msg = String.format(
2065 "uid %s cannot explicitly add accounts of type: %s",
2066 callingUid,
2067 account.type);
2068 throw new SecurityException(msg);
2069 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07002070 removeVisibleListFunctionality(account, getUserAccounts(UserHandle.getUserId(callingUid)));
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002071 UserAccounts accounts = getUserAccountsForCaller();
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002072 SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002073 final long accountId = AccountsDbUtils.findAccountId(db, account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002074 logRecord(
2075 db,
2076 DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE,
2077 TABLE_ACCOUNTS,
2078 accountId,
2079 accounts,
2080 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002081 long identityToken = clearCallingIdentity();
2082 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002083 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002084 } finally {
2085 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07002086 }
Fred Quintana60307342009-03-24 22:48:12 -07002087 }
2088
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002089 private class RemoveAccountSession extends Session {
2090 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002091 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002092 Account account, boolean expectActivityLaunch) {
2093 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002094 true /* stripAuthTokenFromResult */, account.name,
2095 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002096 mAccount = account;
2097 }
2098
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002099 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002100 protected String toDebugString(long now) {
2101 return super.toDebugString(now) + ", removeAccount"
2102 + ", account " + mAccount;
2103 }
2104
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002105 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002106 public void run() throws RemoteException {
2107 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
2108 }
2109
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002110 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002111 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002112 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002113 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
2114 && !result.containsKey(AccountManager.KEY_INTENT)) {
2115 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002116 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002117 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002118 }
2119 IAccountManagerResponse response = getResponseAndClose();
2120 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002121 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2122 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2123 + response);
2124 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002125 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002126 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002127 try {
2128 response.onResult(result2);
2129 } catch (RemoteException e) {
2130 // ignore
2131 }
2132 }
2133 }
2134 super.onResult(result);
2135 }
2136 }
2137
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002138 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002139 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002140 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002141 }
2142
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002143 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002144 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002145 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002146 if (!userUnlocked) {
2147 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
2148 + " is still locked. CE data will be removed later");
2149 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002150 synchronized (accounts.cacheLock) {
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002151 final SQLiteDatabase db = userUnlocked
2152 ? accounts.openHelper.getWritableDatabaseUserIsUnlocked()
2153 : accounts.openHelper.getWritableDatabase();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002154 db.beginTransaction();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002155 // Set to a dummy value, this will only be used if the database
2156 // transaction succeeds.
2157 long accountId = -1;
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002158 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002159 accountId = AccountsDbUtils.findAccountId(db, account);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002160 if (accountId >= 0) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002161 AccountsDbUtils.deleteAccount(db, accountId);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002162 if (userUnlocked) {
2163 // Delete from CE table
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002164 AccountsDbUtils.deleteCeAccount(db, accountId);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002165 }
2166 db.setTransactionSuccessful();
2167 isChanged = true;
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002168 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002169 } finally {
2170 db.endTransaction();
2171 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002172 if (isChanged) {
2173 removeAccountFromCacheLocked(accounts, account);
2174 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occured.
2175 sendAccountsChangedBroadcast(accounts.userId);
2176 String action = userUnlocked ? DebugDbHelper.ACTION_ACCOUNT_REMOVE
2177 : DebugDbHelper.ACTION_ACCOUNT_REMOVE_DE;
2178 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts);
2179 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002180 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002181 long id = Binder.clearCallingIdentity();
2182 try {
2183 int parentUserId = accounts.userId;
2184 if (canHaveProfile(parentUserId)) {
2185 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002186 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002187 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002188 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002189 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002190 }
2191 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002192 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002193 } finally {
2194 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002195 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002196 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002197 }
2198
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002199 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002200 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002201 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002202 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2203 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002204 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002205 + ", pid " + Binder.getCallingPid());
2206 }
Fred Quintana382601f2010-03-25 12:25:10 -07002207 if (accountType == null) throw new IllegalArgumentException("accountType is null");
2208 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002209 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002210 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002211 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002212 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002213 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002214 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002215 db.beginTransaction();
2216 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002217 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002218 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002219 db.setTransactionSuccessful();
2220 } finally {
2221 db.endTransaction();
2222 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002223 }
Fred Quintana60307342009-03-24 22:48:12 -07002224 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002225 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002226 }
2227 }
2228
Carlos Valdivia91979be2015-05-22 14:11:35 -07002229 private void invalidateCustomTokenLocked(
2230 UserAccounts accounts,
2231 String accountType,
2232 String authToken) {
2233 if (authToken == null || accountType == null) {
2234 return;
2235 }
2236 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002237 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002238 }
2239
Amith Yamasani04e0d262012-02-14 11:50:53 -08002240 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
2241 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002242 if (authToken == null || accountType == null) {
2243 return;
2244 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002245 Cursor cursor = AccountsDbUtils.findAuthtokenForAllAccounts(db, accountType, authToken);
Fred Quintana33269202009-04-20 16:05:10 -07002246 try {
2247 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002248 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002249 String accountName = cursor.getString(1);
2250 String authTokenType = cursor.getString(2);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002251 AccountsDbUtils.deleteAuthToken(db, authTokenId);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002252 writeAuthTokenIntoCacheLocked(
2253 accounts,
2254 db,
2255 new Account(accountName, accountType),
2256 authTokenType,
2257 null);
Fred Quintana60307342009-03-24 22:48:12 -07002258 }
Fred Quintana33269202009-04-20 16:05:10 -07002259 } finally {
2260 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002261 }
2262 }
2263
Carlos Valdivia91979be2015-05-22 14:11:35 -07002264 private void saveCachedToken(
2265 UserAccounts accounts,
2266 Account account,
2267 String callerPkg,
2268 byte[] callerSigDigest,
2269 String tokenType,
2270 String token,
2271 long expiryMillis) {
2272
2273 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2274 return;
2275 }
2276 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002277 UserHandle.of(accounts.userId));
Carlos Valdivia91979be2015-05-22 14:11:35 -07002278 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002279 accounts.accountTokenCaches.put(
2280 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002281 }
2282 }
2283
Amith Yamasani04e0d262012-02-14 11:50:53 -08002284 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2285 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002286 if (account == null || type == null) {
2287 return false;
2288 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002289 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002290 UserHandle.of(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002291 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002292 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002293 db.beginTransaction();
2294 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002295 long accountId = AccountsDbUtils.findAccountId(db, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002296 if (accountId < 0) {
2297 return false;
2298 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002299 AccountsDbUtils.deleteAuthtokensByAccountIdAndType(db, accountId, type);
2300 if (AccountsDbUtils.insertAuthToken(db, accountId, type, authToken) >= 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002301 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002302 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002303 return true;
2304 }
Fred Quintana33269202009-04-20 16:05:10 -07002305 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002306 } finally {
2307 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07002308 }
Fred Quintana60307342009-03-24 22:48:12 -07002309 }
2310 }
2311
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002312 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002313 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002314 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002315 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2316 Log.v(TAG, "peekAuthToken: " + account
2317 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002318 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002319 + ", pid " + Binder.getCallingPid());
2320 }
Fred Quintana382601f2010-03-25 12:25:10 -07002321 if (account == null) throw new IllegalArgumentException("account is null");
2322 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002323 int userId = UserHandle.getCallingUserId();
2324 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002325 String msg = String.format(
2326 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2327 callingUid,
2328 account.type);
2329 throw new SecurityException(msg);
2330 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002331 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002332 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2333 + callingUid);
2334 return null;
2335 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002336 long identityToken = clearCallingIdentity();
2337 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002338 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002339 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002340 } finally {
2341 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002342 }
Fred Quintana60307342009-03-24 22:48:12 -07002343 }
2344
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002345 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002346 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002347 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002348 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2349 Log.v(TAG, "setAuthToken: " + account
2350 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002351 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002352 + ", pid " + Binder.getCallingPid());
2353 }
Fred Quintana382601f2010-03-25 12:25:10 -07002354 if (account == null) throw new IllegalArgumentException("account is null");
2355 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002356 int userId = UserHandle.getCallingUserId();
2357 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002358 String msg = String.format(
2359 "uid %s cannot set auth tokens associated with accounts of type: %s",
2360 callingUid,
2361 account.type);
2362 throw new SecurityException(msg);
2363 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002364 long identityToken = clearCallingIdentity();
2365 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002366 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002367 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002368 } finally {
2369 restoreCallingIdentity(identityToken);
2370 }
Fred Quintana60307342009-03-24 22:48:12 -07002371 }
2372
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002373 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002374 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002375 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002376 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2377 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002378 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002379 + ", pid " + Binder.getCallingPid());
2380 }
Fred Quintana382601f2010-03-25 12:25:10 -07002381 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002382 int userId = UserHandle.getCallingUserId();
2383 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002384 String msg = String.format(
2385 "uid %s cannot set secrets for accounts of type: %s",
2386 callingUid,
2387 account.type);
2388 throw new SecurityException(msg);
2389 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002390 long identityToken = clearCallingIdentity();
2391 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002392 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002393 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002394 } finally {
2395 restoreCallingIdentity(identityToken);
2396 }
Fred Quintana60307342009-03-24 22:48:12 -07002397 }
2398
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002399 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2400 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002401 if (account == null) {
2402 return;
2403 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002404 boolean isChanged = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002405 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002406 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002407 db.beginTransaction();
2408 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002409 final long accountId = AccountsDbUtils.findAccountId(db, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002410 if (accountId >= 0) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002411 AccountsDbUtils.updateAccountPassword(db, accountId, password);
2412 AccountsDbUtils.deleteAuthTokensByAccountId(db, accountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002413 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002414 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002415 db.setTransactionSuccessful();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002416 // If there is an account whose password will be updated and the database
2417 // transactions succeed, then we say that a change has occured. Even if the
2418 // new password is the same as the old and there were no authtokens to delete.
2419 isChanged = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002420 String action = (password == null || password.length() == 0) ?
2421 DebugDbHelper.ACTION_CLEAR_PASSWORD
2422 : DebugDbHelper.ACTION_SET_PASSWORD;
2423 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08002424 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002425 } finally {
2426 db.endTransaction();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002427 if (isChanged) {
2428 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2429 sendAccountsChangedBroadcast(accounts.userId);
2430 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002431 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002432 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002433 }
2434
Amith Yamasani04e0d262012-02-14 11:50:53 -08002435 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08002436 Log.i(TAG, "the accounts changed, sending broadcast of "
2437 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07002438 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07002439 }
2440
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002441 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002442 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002443 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002444 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2445 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002446 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002447 + ", pid " + Binder.getCallingPid());
2448 }
Fred Quintana382601f2010-03-25 12:25:10 -07002449 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002450 int userId = UserHandle.getCallingUserId();
2451 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002452 String msg = String.format(
2453 "uid %s cannot clear passwords for accounts of type: %s",
2454 callingUid,
2455 account.type);
2456 throw new SecurityException(msg);
2457 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002458 long identityToken = clearCallingIdentity();
2459 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002460 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002461 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002462 } finally {
2463 restoreCallingIdentity(identityToken);
2464 }
Fred Quintana60307342009-03-24 22:48:12 -07002465 }
2466
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002467 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002468 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002469 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002470 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2471 Log.v(TAG, "setUserData: " + account
2472 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002473 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002474 + ", pid " + Binder.getCallingPid());
2475 }
Fred Quintana382601f2010-03-25 12:25:10 -07002476 if (key == null) throw new IllegalArgumentException("key is null");
2477 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002478 int userId = UserHandle.getCallingUserId();
2479 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002480 String msg = String.format(
2481 "uid %s cannot set user data for accounts of type: %s",
2482 callingUid,
2483 account.type);
2484 throw new SecurityException(msg);
2485 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002486 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002487 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002488 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002489 synchronized (accounts.cacheLock) {
2490 if (!accountExistsCacheLocked(accounts, account)) {
2491 return;
2492 }
2493 setUserdataInternalLocked(accounts, account, key, value);
2494 }
Fred Quintana60307342009-03-24 22:48:12 -07002495 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002496 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002497 }
2498 }
2499
Simranjit Kohli858511c2016-03-10 18:36:11 +00002500 private boolean accountExistsCacheLocked(UserAccounts accounts, Account account) {
2501 if (accounts.accountCache.containsKey(account.type)) {
2502 for (Account acc : accounts.accountCache.get(account.type)) {
2503 if (acc.name.equals(account.name)) {
2504 return true;
2505 }
2506 }
2507 }
2508 return false;
2509 }
2510
2511 private void setUserdataInternalLocked(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002512 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07002513 if (account == null || key == null) {
2514 return;
2515 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002516 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2517 db.beginTransaction();
2518 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002519 long accountId = AccountsDbUtils.findAccountId(db, account);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002520 if (accountId < 0) {
2521 return;
2522 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002523 long extrasId = AccountsDbUtils.findExtrasIdByAccountId(db, accountId, key);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002524 if (extrasId < 0) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002525 extrasId = AccountsDbUtils.insertExtra(db, accountId, key, value);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002526 if (extrasId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002527 return;
2528 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002529 } else if (!AccountsDbUtils.updateExtra(db, extrasId, value)) {
2530 return;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002531 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002532 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
2533 db.setTransactionSuccessful();
2534 } finally {
2535 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002536 }
2537 }
2538
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002539 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002540 if (result == null) {
2541 Log.e(TAG, "the result is unexpectedly null", new Exception());
2542 }
2543 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2544 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2545 + response);
2546 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002547 try {
2548 response.onResult(result);
2549 } catch (RemoteException e) {
2550 // if the caller is dead then there is no one to care about remote
2551 // exceptions
2552 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2553 Log.v(TAG, "failure while notifying response", e);
2554 }
2555 }
2556 }
2557
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002558 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002559 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2560 final String authTokenType)
2561 throws RemoteException {
2562 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002563 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2564
Fred Quintanad9640ec2012-05-23 12:37:00 -07002565 final int callingUid = getCallingUid();
2566 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07002567 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002568 throw new SecurityException("can only call from system");
2569 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002570 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002571 long identityToken = clearCallingIdentity();
2572 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002573 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002574 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2575 false /* stripAuthTokenFromResult */, null /* accountName */,
2576 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002577 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002578 protected String toDebugString(long now) {
2579 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002580 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002581 + ", authTokenType " + authTokenType;
2582 }
2583
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002584 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002585 public void run() throws RemoteException {
2586 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2587 }
2588
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002589 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002590 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002591 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002592 if (result != null) {
2593 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2594 Bundle bundle = new Bundle();
2595 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2596 super.onResult(bundle);
2597 return;
2598 } else {
2599 super.onResult(result);
2600 }
2601 }
2602 }.bind();
2603 } finally {
2604 restoreCallingIdentity(identityToken);
2605 }
2606 }
2607
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002608 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002609 public void getAuthToken(
2610 IAccountManagerResponse response,
2611 final Account account,
2612 final String authTokenType,
2613 final boolean notifyOnAuthFailure,
2614 final boolean expectActivityLaunch,
2615 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002616 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002617 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2618 Log.v(TAG, "getAuthToken: " + account
2619 + ", response " + response
2620 + ", authTokenType " + authTokenType
2621 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2622 + ", expectActivityLaunch " + expectActivityLaunch
2623 + ", caller's uid " + Binder.getCallingUid()
2624 + ", pid " + Binder.getCallingPid());
2625 }
Fred Quintana382601f2010-03-25 12:25:10 -07002626 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002627 try {
2628 if (account == null) {
2629 Slog.w(TAG, "getAuthToken called with null account");
2630 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2631 return;
2632 }
2633 if (authTokenType == null) {
2634 Slog.w(TAG, "getAuthToken called with null authTokenType");
2635 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2636 return;
2637 }
2638 } catch (RemoteException e) {
2639 Slog.w(TAG, "Failed to report error back to the client." + e);
2640 return;
2641 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002642 int userId = UserHandle.getCallingUserId();
2643 long ident = Binder.clearCallingIdentity();
2644 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002645 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002646 try {
2647 accounts = getUserAccounts(userId);
2648 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2649 AuthenticatorDescription.newKey(account.type), accounts.userId);
2650 } finally {
2651 Binder.restoreCallingIdentity(ident);
2652 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002653
Costin Manolachea40c6302010-12-13 14:50:45 -08002654 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002655 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002656
2657 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002658 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002659 final boolean permissionGranted =
2660 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002661
Carlos Valdivia91979be2015-05-22 14:11:35 -07002662 // Get the calling package. We will use it for the purpose of caching.
2663 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002664 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002665 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002666 try {
2667 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2668 } finally {
2669 Binder.restoreCallingIdentity(ident);
2670 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002671 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2672 String msg = String.format(
2673 "Uid %s is attempting to illegally masquerade as package %s!",
2674 callerUid,
2675 callerPkg);
2676 throw new SecurityException(msg);
2677 }
2678
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002679 // let authenticator know the identity of the caller
2680 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2681 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002682
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002683 if (notifyOnAuthFailure) {
2684 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002685 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002686
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002687 long identityToken = clearCallingIdentity();
2688 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002689 // Distill the caller's package signatures into a single digest.
2690 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2691
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002692 // if the caller has permission, do the peek. otherwise go the more expensive
2693 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002694 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002695 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002696 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002697 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002698 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2699 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2700 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002701 onResult(response, result);
2702 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002703 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002704 }
2705
Carlos Valdivia91979be2015-05-22 14:11:35 -07002706 if (customTokens) {
2707 /*
2708 * Look up tokens in the new cache only if the loginOptions don't have parameters
2709 * outside of those expected to be injected by the AccountManager, e.g.
2710 * ANDORID_PACKAGE_NAME.
2711 */
2712 String token = readCachedTokenInternal(
2713 accounts,
2714 account,
2715 authTokenType,
2716 callerPkg,
2717 callerPkgSigDigest);
2718 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002719 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2720 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2721 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002722 Bundle result = new Bundle();
2723 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2724 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2725 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2726 onResult(response, result);
2727 return;
2728 }
2729 }
2730
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002731 new Session(
2732 accounts,
2733 response,
2734 account.type,
2735 expectActivityLaunch,
2736 false /* stripAuthTokenFromResult */,
2737 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002738 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002739 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002740 protected String toDebugString(long now) {
2741 if (loginOptions != null) loginOptions.keySet();
2742 return super.toDebugString(now) + ", getAuthToken"
2743 + ", " + account
2744 + ", authTokenType " + authTokenType
2745 + ", loginOptions " + loginOptions
2746 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2747 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002748
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002749 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002750 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002751 // If the caller doesn't have permission then create and return the
2752 // "grant permission" intent instead of the "getAuthToken" intent.
2753 if (!permissionGranted) {
2754 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2755 } else {
2756 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2757 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002758 }
2759
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002760 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002761 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002762 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002763 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002764 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002765 Intent intent = newGrantCredentialsPermissionIntent(
2766 account,
2767 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002768 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002769 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002770 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002771 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002772 onResult(bundle);
2773 return;
2774 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002775 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002776 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002777 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2778 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002779 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002780 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002781 "the type and name should not be empty");
2782 return;
2783 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002784 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002785 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002786 saveAuthTokenToDatabase(
2787 mAccounts,
2788 resultAccount,
2789 authTokenType,
2790 authToken);
2791 }
2792 long expiryMillis = result.getLong(
2793 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2794 if (customTokens
2795 && expiryMillis > System.currentTimeMillis()) {
2796 saveCachedToken(
2797 mAccounts,
2798 account,
2799 callerPkg,
2800 callerPkgSigDigest,
2801 authTokenType,
2802 authToken,
2803 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002804 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002805 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002806
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002807 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002808 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002809 /*
2810 * Make sure that the supplied intent is owned by the authenticator
2811 * giving it to the system. Otherwise a malicious authenticator could
2812 * have users launching arbitrary activities by tricking users to
2813 * interact with malicious notifications.
2814 */
2815 checkKeyIntent(
2816 Binder.getCallingUid(),
2817 intent);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002818 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002819 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002820 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002821 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002822 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002823 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002824 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002825 }.bind();
2826 } finally {
2827 restoreCallingIdentity(identityToken);
2828 }
Fred Quintana60307342009-03-24 22:48:12 -07002829 }
2830
Carlos Valdivia91979be2015-05-22 14:11:35 -07002831 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2832 MessageDigest digester;
2833 try {
2834 digester = MessageDigest.getInstance("SHA-256");
2835 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2836 callerPkg, PackageManager.GET_SIGNATURES);
2837 for (Signature sig : pkgInfo.signatures) {
2838 digester.update(sig.toByteArray());
2839 }
2840 } catch (NoSuchAlgorithmException x) {
2841 Log.wtf(TAG, "SHA-256 should be available", x);
2842 digester = null;
2843 } catch (NameNotFoundException e) {
2844 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2845 digester = null;
2846 }
2847 return (digester == null) ? null : digester.digest();
2848 }
2849
Dianne Hackborn41203752012-08-31 14:05:51 -07002850 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2851 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002852 int uid = intent.getIntExtra(
2853 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2854 String authTokenType = intent.getStringExtra(
2855 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002856 final String titleAndSubtitle =
2857 mContext.getString(R.string.permission_request_notification_with_subtitle,
2858 account.name);
2859 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002860 String title = titleAndSubtitle;
2861 String subtitle = "";
2862 if (index > 0) {
2863 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002864 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002865 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002866 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002867 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002868 Notification n = new Notification.Builder(contextForUser)
2869 .setSmallIcon(android.R.drawable.stat_sys_warning)
2870 .setWhen(0)
2871 .setColor(contextForUser.getColor(
2872 com.android.internal.R.color.system_notification_accent_color))
2873 .setContentTitle(title)
2874 .setContentText(subtitle)
2875 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2876 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2877 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002878 installNotification(getCredentialPermissionNotificationId(
2879 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002880 }
2881
Costin Manolache5f383ad92010-12-02 16:44:46 -08002882 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002883 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002884
2885 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002886 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002887 // Since it was set in Eclair+ we can't change it without breaking apps using
2888 // the intent from a non-Activity context.
2889 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002890 intent.addCategory(
2891 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002892
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002893 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002894 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2895 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002896 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002897
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002898 return intent;
2899 }
2900
2901 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2902 int uid) {
2903 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002904 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002905 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002906 final Pair<Pair<Account, String>, Integer> key =
2907 new Pair<Pair<Account, String>, Integer>(
2908 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002909 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002910 if (id == null) {
2911 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002912 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002913 }
2914 }
2915 return id;
2916 }
2917
Amith Yamasani04e0d262012-02-14 11:50:53 -08002918 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002919 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002920 synchronized (accounts.signinRequiredNotificationIds) {
2921 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002922 if (id == null) {
2923 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002924 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002925 }
2926 }
2927 return id;
2928 }
2929
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002930 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002931 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002932 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002933 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002934 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002935 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2936 Log.v(TAG, "addAccount: accountType " + accountType
2937 + ", response " + response
2938 + ", authTokenType " + authTokenType
2939 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2940 + ", expectActivityLaunch " + expectActivityLaunch
2941 + ", caller's uid " + Binder.getCallingUid()
2942 + ", pid " + Binder.getCallingPid());
2943 }
Fred Quintana382601f2010-03-25 12:25:10 -07002944 if (response == null) throw new IllegalArgumentException("response is null");
2945 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002946
Amith Yamasani71e6c692013-03-24 17:39:28 -07002947 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002948 final int uid = Binder.getCallingUid();
2949 final int userId = UserHandle.getUserId(uid);
2950 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002951 try {
2952 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2953 "User is not allowed to add an account!");
2954 } catch (RemoteException re) {
2955 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002956 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002957 return;
2958 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002959 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002960 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002961 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2962 "User cannot modify accounts of this type (policy).");
2963 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002964 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002965 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2966 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002967 return;
2968 }
2969
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002970 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002971 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2972 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2973 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2974
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002975 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002976 long identityToken = clearCallingIdentity();
2977 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002978 UserAccounts accounts = getUserAccounts(usrId);
2979 logRecordWithUid(
2980 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002981 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002982 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002983 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002984 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002985 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002986 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002987 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002988 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002989
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002990 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002991 protected String toDebugString(long now) {
2992 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002993 + ", accountType " + accountType
2994 + ", requiredFeatures "
2995 + (requiredFeatures != null
2996 ? TextUtils.join(",", requiredFeatures)
2997 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002998 }
2999 }.bind();
3000 } finally {
3001 restoreCallingIdentity(identityToken);
3002 }
Fred Quintana60307342009-03-24 22:48:12 -07003003 }
3004
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003005 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003006 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3007 final String authTokenType, final String[] requiredFeatures,
3008 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003009 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003010 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003011 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3012 Log.v(TAG, "addAccount: accountType " + accountType
3013 + ", response " + response
3014 + ", authTokenType " + authTokenType
3015 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
3016 + ", expectActivityLaunch " + expectActivityLaunch
3017 + ", caller's uid " + Binder.getCallingUid()
3018 + ", pid " + Binder.getCallingPid()
3019 + ", for user id " + userId);
3020 }
3021 if (response == null) throw new IllegalArgumentException("response is null");
3022 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003023 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003024 if (isCrossUser(callingUid, userId)) {
3025 throw new SecurityException(
3026 String.format(
3027 "User %s trying to add account for %s" ,
3028 UserHandle.getCallingUserId(),
3029 userId));
3030 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003031
3032 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003033 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003034 try {
3035 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3036 "User is not allowed to add an account!");
3037 } catch (RemoteException re) {
3038 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003039 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003040 return;
3041 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003042 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003043 try {
3044 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3045 "User cannot modify accounts of this type (policy).");
3046 } catch (RemoteException re) {
3047 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003048 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3049 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003050 return;
3051 }
3052
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003053 final int pid = Binder.getCallingPid();
3054 final int uid = Binder.getCallingUid();
3055 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3056 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3057 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3058
3059 long identityToken = clearCallingIdentity();
3060 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003061 UserAccounts accounts = getUserAccounts(userId);
3062 logRecordWithUid(
3063 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003064 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003065 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003066 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003067 @Override
3068 public void run() throws RemoteException {
3069 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3070 options);
3071 }
3072
3073 @Override
3074 protected String toDebugString(long now) {
3075 return super.toDebugString(now) + ", addAccount"
3076 + ", accountType " + accountType
3077 + ", requiredFeatures "
3078 + (requiredFeatures != null
3079 ? TextUtils.join(",", requiredFeatures)
3080 : null);
3081 }
3082 }.bind();
3083 } finally {
3084 restoreCallingIdentity(identityToken);
3085 }
3086 }
3087
Sandra Kwan78812282015-11-04 11:19:47 -08003088 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003089 public void startAddAccountSession(
3090 final IAccountManagerResponse response,
3091 final String accountType,
3092 final String authTokenType,
3093 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003094 final boolean expectActivityLaunch,
3095 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003096 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003097 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3098 Log.v(TAG,
3099 "startAddAccountSession: accountType " + accountType
3100 + ", response " + response
3101 + ", authTokenType " + authTokenType
3102 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
3103 + ", expectActivityLaunch " + expectActivityLaunch
3104 + ", caller's uid " + Binder.getCallingUid()
3105 + ", pid " + Binder.getCallingPid());
3106 }
3107 if (response == null) {
3108 throw new IllegalArgumentException("response is null");
3109 }
3110 if (accountType == null) {
3111 throw new IllegalArgumentException("accountType is null");
3112 }
3113
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003114 final int uid = Binder.getCallingUid();
3115 final int userId = UserHandle.getUserId(uid);
3116 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003117 try {
3118 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3119 "User is not allowed to add an account!");
3120 } catch (RemoteException re) {
3121 }
3122 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3123 return;
3124 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003125 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003126 try {
3127 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3128 "User cannot modify accounts of this type (policy).");
3129 } catch (RemoteException re) {
3130 }
3131 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3132 userId);
3133 return;
3134 }
Sandra Kwan78812282015-11-04 11:19:47 -08003135 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003136 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3137 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3138 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3139
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003140 // Check to see if the Password should be included to the caller.
3141 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3142 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003143 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003144
Sandra Kwan78812282015-11-04 11:19:47 -08003145 long identityToken = clearCallingIdentity();
3146 try {
Hongming Jin368aa192016-07-29 14:29:54 -07003147 UserAccounts accounts = getUserAccounts(userId);
Sandra Kwan78812282015-11-04 11:19:47 -08003148 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
3149 TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003150 new StartAccountSession(
3151 accounts,
3152 response,
3153 accountType,
3154 expectActivityLaunch,
3155 null /* accountName */,
3156 false /* authDetailsRequired */,
3157 true /* updateLastAuthenticationTime */,
3158 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003159 @Override
3160 public void run() throws RemoteException {
3161 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3162 requiredFeatures, options);
3163 }
3164
3165 @Override
3166 protected String toDebugString(long now) {
3167 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3168 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3169 + accountType + ", requiredFeatures "
3170 + (requiredFeatures != null ? requiredFeaturesStr : null);
3171 }
3172 }.bind();
3173 } finally {
3174 restoreCallingIdentity(identityToken);
3175 }
3176 }
3177
3178 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3179 private abstract class StartAccountSession extends Session {
3180
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003181 private final boolean mIsPasswordForwardingAllowed;
3182
3183 public StartAccountSession(
3184 UserAccounts accounts,
3185 IAccountManagerResponse response,
3186 String accountType,
3187 boolean expectActivityLaunch,
3188 String accountName,
3189 boolean authDetailsRequired,
3190 boolean updateLastAuthenticationTime,
3191 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003192 super(accounts, response, accountType, expectActivityLaunch,
3193 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3194 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003195 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003196 }
3197
3198 @Override
3199 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003200 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003201 mNumResults++;
3202 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003203 if (result != null
3204 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003205 checkKeyIntent(
3206 Binder.getCallingUid(),
3207 intent);
Sandra Kwan78812282015-11-04 11:19:47 -08003208 }
Sandra Kwan78812282015-11-04 11:19:47 -08003209 IAccountManagerResponse response;
3210 if (mExpectActivityLaunch && result != null
3211 && result.containsKey(AccountManager.KEY_INTENT)) {
3212 response = mResponse;
3213 } else {
3214 response = getResponseAndClose();
3215 }
3216 if (response == null) {
3217 return;
3218 }
3219 if (result == null) {
3220 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3221 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3222 + response);
3223 }
3224 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3225 "null bundle returned");
3226 return;
3227 }
3228
3229 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3230 // All AccountManager error codes are greater
3231 // than 0
3232 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3233 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3234 return;
3235 }
3236
Hongming Jin368aa192016-07-29 14:29:54 -07003237 // Omit passwords if the caller isn't permitted to see them.
3238 if (!mIsPasswordForwardingAllowed) {
3239 result.remove(AccountManager.KEY_PASSWORD);
3240 }
3241
Sandra Kwan78812282015-11-04 11:19:47 -08003242 // Strip auth token from result.
3243 result.remove(AccountManager.KEY_AUTHTOKEN);
3244
3245 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3246 Log.v(TAG,
3247 getClass().getSimpleName() + " calling onResult() on response " + response);
3248 }
3249
3250 // Get the session bundle created by authenticator. The
3251 // bundle contains data necessary for finishing the session
3252 // later. The session bundle will be encrypted here and
3253 // decrypted later when trying to finish the session.
3254 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3255 if (sessionBundle != null) {
3256 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3257 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003258 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003259 Log.w(TAG, "Account type in session bundle doesn't match request.");
3260 }
3261 // Add accountType info to session bundle. This will
3262 // override any value set by authenticator.
3263 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3264
3265 // Encrypt session bundle before returning to caller.
3266 try {
3267 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3268 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3269 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3270 } catch (GeneralSecurityException e) {
3271 if (Log.isLoggable(TAG, Log.DEBUG)) {
3272 Log.v(TAG, "Failed to encrypt session bundle!", e);
3273 }
3274 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3275 "failed to encrypt session bundle");
3276 return;
3277 }
3278 }
3279
3280 sendResponse(response, result);
3281 }
3282 }
3283
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003284 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003285 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003286 @NonNull Bundle sessionBundle,
3287 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003288 Bundle appInfo,
3289 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003290 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003291 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003292 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3293 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003294 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003295 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003296 + ", caller's uid " + callingUid
3297 + ", caller's user id " + UserHandle.getCallingUserId()
3298 + ", pid " + Binder.getCallingPid()
3299 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003300 }
3301 if (response == null) {
3302 throw new IllegalArgumentException("response is null");
3303 }
3304
3305 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3306 // Account type is added to it before encryption.
3307 if (sessionBundle == null || sessionBundle.size() == 0) {
3308 throw new IllegalArgumentException("sessionBundle is empty");
3309 }
3310
Sandra Kwan0b84b452016-01-20 15:25:42 -08003311 // Only allow the system process to finish session for other users
3312 if (isCrossUser(callingUid, userId)) {
3313 throw new SecurityException(
3314 String.format(
3315 "User %s trying to finish session for %s without cross user permission",
3316 UserHandle.getCallingUserId(),
3317 userId));
3318 }
3319
Sandra Kwan0b84b452016-01-20 15:25:42 -08003320 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003321 sendErrorResponse(response,
3322 AccountManager.ERROR_CODE_USER_RESTRICTED,
3323 "User is not allowed to add an account!");
3324 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3325 return;
3326 }
3327
3328 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003329 final Bundle decryptedBundle;
3330 final String accountType;
3331 // First decrypt session bundle to get account type for checking permission.
3332 try {
3333 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3334 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3335 if (decryptedBundle == null) {
3336 sendErrorResponse(
3337 response,
3338 AccountManager.ERROR_CODE_BAD_REQUEST,
3339 "failed to decrypt session bundle");
3340 return;
3341 }
3342 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3343 // Account type cannot be null. This should not happen if session bundle was created
3344 // properly by #StartAccountSession.
3345 if (TextUtils.isEmpty(accountType)) {
3346 sendErrorResponse(
3347 response,
3348 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3349 "accountType is empty");
3350 return;
3351 }
3352
3353 // If by any chances, decryptedBundle contains colliding keys with
3354 // system info
3355 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3356 // update credentials flow, we should replace with the new values of the current call.
3357 if (appInfo != null) {
3358 decryptedBundle.putAll(appInfo);
3359 }
3360
3361 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003362 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003363 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3364 } catch (GeneralSecurityException e) {
3365 if (Log.isLoggable(TAG, Log.DEBUG)) {
3366 Log.v(TAG, "Failed to decrypt session bundle!", e);
3367 }
3368 sendErrorResponse(
3369 response,
3370 AccountManager.ERROR_CODE_BAD_REQUEST,
3371 "failed to decrypt session bundle");
3372 return;
3373 }
3374
Sandra Kwan0b84b452016-01-20 15:25:42 -08003375 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003376 sendErrorResponse(
3377 response,
3378 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3379 "User cannot modify accounts of this type (policy).");
3380 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3381 userId);
3382 return;
3383 }
3384
3385 long identityToken = clearCallingIdentity();
3386 try {
3387 UserAccounts accounts = getUserAccounts(userId);
3388 logRecordWithUid(
3389 accounts,
3390 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3391 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003392 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003393 new Session(
3394 accounts,
3395 response,
3396 accountType,
3397 expectActivityLaunch,
3398 true /* stripAuthTokenFromResult */,
3399 null /* accountName */,
3400 false /* authDetailsRequired */,
3401 true /* updateLastAuthenticationTime */) {
3402 @Override
3403 public void run() throws RemoteException {
3404 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3405 }
3406
3407 @Override
3408 protected String toDebugString(long now) {
3409 return super.toDebugString(now)
3410 + ", finishSession"
3411 + ", accountType " + accountType;
3412 }
3413 }.bind();
3414 } finally {
3415 restoreCallingIdentity(identityToken);
3416 }
3417 }
3418
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003419 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003420 final DevicePolicyManagerInternal dpmi =
3421 LocalServices.getService(DevicePolicyManagerInternal.class);
3422 Intent intent = null;
Nicolas Prevot14fc1972016-08-24 14:21:38 +01003423 if (dpmi == null) {
3424 intent = getDefaultCantAddAccountIntent(errorCode);
3425 } else if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003426 intent = dpmi.createUserRestrictionSupportIntent(userId,
3427 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3428 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3429 intent = dpmi.createShowAdminSupportIntent(userId, false);
3430 }
3431 if (intent == null) {
3432 intent = getDefaultCantAddAccountIntent(errorCode);
3433 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003434 long identityToken = clearCallingIdentity();
3435 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003436 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003437 } finally {
3438 restoreCallingIdentity(identityToken);
3439 }
3440 }
3441
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003442 /**
3443 * Called when we don't know precisely who is preventing us from adding an account.
3444 */
3445 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3446 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3447 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3448 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3449 return cantAddAccount;
3450 }
3451
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003452 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003453 public void confirmCredentialsAsUser(
3454 IAccountManagerResponse response,
3455 final Account account,
3456 final Bundle options,
3457 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003458 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003459 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003460 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003461 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3462 Log.v(TAG, "confirmCredentials: " + account
3463 + ", response " + response
3464 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003465 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003466 + ", pid " + Binder.getCallingPid());
3467 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003468 // Only allow the system process to read accounts of other users
3469 if (isCrossUser(callingUid, userId)) {
3470 throw new SecurityException(
3471 String.format(
3472 "User %s trying to confirm account credentials for %s" ,
3473 UserHandle.getCallingUserId(),
3474 userId));
3475 }
Fred Quintana382601f2010-03-25 12:25:10 -07003476 if (response == null) throw new IllegalArgumentException("response is null");
3477 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003478 long identityToken = clearCallingIdentity();
3479 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003480 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003481 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003482 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003483 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003484 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003485 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003486 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003487 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003488 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003489 protected String toDebugString(long now) {
3490 return super.toDebugString(now) + ", confirmCredentials"
3491 + ", " + account;
3492 }
3493 }.bind();
3494 } finally {
3495 restoreCallingIdentity(identityToken);
3496 }
Fred Quintana60307342009-03-24 22:48:12 -07003497 }
3498
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003499 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003500 public void updateCredentials(IAccountManagerResponse response, final Account account,
3501 final String authTokenType, final boolean expectActivityLaunch,
3502 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003503 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003504 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3505 Log.v(TAG, "updateCredentials: " + account
3506 + ", response " + response
3507 + ", authTokenType " + authTokenType
3508 + ", expectActivityLaunch " + expectActivityLaunch
3509 + ", caller's uid " + Binder.getCallingUid()
3510 + ", pid " + Binder.getCallingPid());
3511 }
Fred Quintana382601f2010-03-25 12:25:10 -07003512 if (response == null) throw new IllegalArgumentException("response is null");
3513 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003514 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003515 long identityToken = clearCallingIdentity();
3516 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003517 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003518 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003519 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003520 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003521 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003522 public void run() throws RemoteException {
3523 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3524 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003525 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003526 protected String toDebugString(long now) {
3527 if (loginOptions != null) loginOptions.keySet();
3528 return super.toDebugString(now) + ", updateCredentials"
3529 + ", " + account
3530 + ", authTokenType " + authTokenType
3531 + ", loginOptions " + loginOptions;
3532 }
3533 }.bind();
3534 } finally {
3535 restoreCallingIdentity(identityToken);
3536 }
Fred Quintana60307342009-03-24 22:48:12 -07003537 }
3538
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003539 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003540 public void startUpdateCredentialsSession(
3541 IAccountManagerResponse response,
3542 final Account account,
3543 final String authTokenType,
3544 final boolean expectActivityLaunch,
3545 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003546 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003547 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3548 Log.v(TAG,
3549 "startUpdateCredentialsSession: " + account + ", response " + response
3550 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3551 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3552 + ", pid " + Binder.getCallingPid());
3553 }
3554 if (response == null) {
3555 throw new IllegalArgumentException("response is null");
3556 }
3557 if (account == null) {
3558 throw new IllegalArgumentException("account is null");
3559 }
Sandra Kwana578d112015-12-16 16:01:43 -08003560
3561 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003562 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003563
3564 // Check to see if the Password should be included to the caller.
3565 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3566 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003567 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003568
Sandra Kwane68c37e2015-11-12 17:11:49 -08003569 long identityToken = clearCallingIdentity();
3570 try {
3571 UserAccounts accounts = getUserAccounts(userId);
3572 new StartAccountSession(
3573 accounts,
3574 response,
3575 account.type,
3576 expectActivityLaunch,
3577 account.name,
3578 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003579 true /* updateLastCredentialTime */,
3580 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003581 @Override
3582 public void run() throws RemoteException {
3583 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3584 loginOptions);
3585 }
3586
3587 @Override
3588 protected String toDebugString(long now) {
3589 if (loginOptions != null)
3590 loginOptions.keySet();
3591 return super.toDebugString(now)
3592 + ", startUpdateCredentialsSession"
3593 + ", " + account
3594 + ", authTokenType " + authTokenType
3595 + ", loginOptions " + loginOptions;
3596 }
3597 }.bind();
3598 } finally {
3599 restoreCallingIdentity(identityToken);
3600 }
3601 }
3602
3603 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003604 public void isCredentialsUpdateSuggested(
3605 IAccountManagerResponse response,
3606 final Account account,
3607 final String statusToken) {
3608 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3609 Log.v(TAG,
3610 "isCredentialsUpdateSuggested: " + account + ", response " + response
3611 + ", caller's uid " + Binder.getCallingUid()
3612 + ", pid " + Binder.getCallingPid());
3613 }
3614 if (response == null) {
3615 throw new IllegalArgumentException("response is null");
3616 }
3617 if (account == null) {
3618 throw new IllegalArgumentException("account is null");
3619 }
3620 if (TextUtils.isEmpty(statusToken)) {
3621 throw new IllegalArgumentException("status token is empty");
3622 }
3623
Sandra Kwan390c9d22016-01-12 14:13:37 -08003624 int usrId = UserHandle.getCallingUserId();
3625 long identityToken = clearCallingIdentity();
3626 try {
3627 UserAccounts accounts = getUserAccounts(usrId);
3628 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3629 false /* stripAuthTokenFromResult */, account.name,
3630 false /* authDetailsRequired */) {
3631 @Override
3632 protected String toDebugString(long now) {
3633 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3634 + ", " + account;
3635 }
3636
3637 @Override
3638 public void run() throws RemoteException {
3639 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3640 }
3641
3642 @Override
3643 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003644 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003645 IAccountManagerResponse response = getResponseAndClose();
3646 if (response == null) {
3647 return;
3648 }
3649
3650 if (result == null) {
3651 sendErrorResponse(
3652 response,
3653 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3654 "null bundle");
3655 return;
3656 }
3657
3658 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3659 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3660 + response);
3661 }
3662 // Check to see if an error occurred. We know if an error occurred because all
3663 // error codes are greater than 0.
3664 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3665 sendErrorResponse(response,
3666 result.getInt(AccountManager.KEY_ERROR_CODE),
3667 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3668 return;
3669 }
3670 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3671 sendErrorResponse(
3672 response,
3673 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3674 "no result in response");
3675 return;
3676 }
3677 final Bundle newResult = new Bundle();
3678 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3679 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3680 sendResponse(response, newResult);
3681 }
3682 }.bind();
3683 } finally {
3684 restoreCallingIdentity(identityToken);
3685 }
3686 }
3687
3688 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003689 public void editProperties(IAccountManagerResponse response, final String accountType,
3690 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003691 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003692 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3693 Log.v(TAG, "editProperties: accountType " + accountType
3694 + ", response " + response
3695 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003696 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003697 + ", pid " + Binder.getCallingPid());
3698 }
Fred Quintana382601f2010-03-25 12:25:10 -07003699 if (response == null) throw new IllegalArgumentException("response is null");
3700 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003701 int userId = UserHandle.getCallingUserId();
3702 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003703 String msg = String.format(
3704 "uid %s cannot edit authenticator properites for account type: %s",
3705 callingUid,
3706 accountType);
3707 throw new SecurityException(msg);
3708 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003709 long identityToken = clearCallingIdentity();
3710 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003711 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003712 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003713 true /* stripAuthTokenFromResult */, null /* accountName */,
3714 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003715 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003716 public void run() throws RemoteException {
3717 mAuthenticator.editProperties(this, mAccountType);
3718 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003719 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003720 protected String toDebugString(long now) {
3721 return super.toDebugString(now) + ", editProperties"
3722 + ", accountType " + accountType;
3723 }
3724 }.bind();
3725 } finally {
3726 restoreCallingIdentity(identityToken);
3727 }
Fred Quintana60307342009-03-24 22:48:12 -07003728 }
3729
Amith Yamasani12747872015-12-07 14:19:49 -08003730 @Override
3731 public boolean someUserHasAccount(@NonNull final Account account) {
3732 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3733 throw new SecurityException("Only system can check for accounts across users");
3734 }
3735 final long token = Binder.clearCallingIdentity();
3736 try {
3737 AccountAndUser[] allAccounts = getAllAccounts();
3738 for (int i = allAccounts.length - 1; i >= 0; i--) {
3739 if (allAccounts[i].account.equals(account)) {
3740 return true;
3741 }
3742 }
3743 return false;
3744 } finally {
3745 Binder.restoreCallingIdentity(token);
3746 }
3747 }
3748
Fred Quintana33269202009-04-20 16:05:10 -07003749 private class GetAccountsByTypeAndFeatureSession extends Session {
3750 private final String[] mFeatures;
3751 private volatile Account[] mAccountsOfType = null;
3752 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3753 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003754 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003755
Amith Yamasani04e0d262012-02-14 11:50:53 -08003756 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003757 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003758 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003759 true /* stripAuthTokenFromResult */, null /* accountName */,
3760 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003761 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003762 mFeatures = features;
3763 }
3764
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003765 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003766 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003767 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003768 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3769 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003770 }
Fred Quintana33269202009-04-20 16:05:10 -07003771 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07003772 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07003773 mCurrentAccount = 0;
3774
3775 checkAccount();
3776 }
3777
3778 public void checkAccount() {
3779 if (mCurrentAccount >= mAccountsOfType.length) {
3780 sendResult();
3781 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003782 }
Fred Quintana33269202009-04-20 16:05:10 -07003783
Fred Quintana29e94b82010-03-10 12:11:51 -08003784 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3785 if (accountAuthenticator == null) {
3786 // It is possible that the authenticator has died, which is indicated by
3787 // mAuthenticator being set to null. If this happens then just abort.
3788 // There is no need to send back a result or error in this case since
3789 // that already happened when mAuthenticator was cleared.
3790 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3791 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3792 + " connected to the authenticator, " + toDebugString());
3793 }
3794 return;
3795 }
Fred Quintana33269202009-04-20 16:05:10 -07003796 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003797 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003798 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003799 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003800 }
3801 }
3802
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003803 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003804 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003805 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003806 mNumResults++;
3807 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003808 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003809 return;
3810 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003811 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003812 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3813 }
3814 mCurrentAccount++;
3815 checkAccount();
3816 }
3817
3818 public void sendResult() {
3819 IAccountManagerResponse response = getResponseAndClose();
3820 if (response != null) {
3821 try {
3822 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3823 for (int i = 0; i < accounts.length; i++) {
3824 accounts[i] = mAccountsWithFeatures.get(i);
3825 }
Fred Quintana56285a62010-12-02 14:20:51 -08003826 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3827 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3828 + response);
3829 }
Fred Quintana33269202009-04-20 16:05:10 -07003830 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003831 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003832 response.onResult(result);
3833 } catch (RemoteException e) {
3834 // if the caller is dead then there is no one to care about remote exceptions
3835 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3836 Log.v(TAG, "failure while notifying response", e);
3837 }
3838 }
3839 }
3840 }
3841
3842
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003843 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003844 protected String toDebugString(long now) {
3845 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3846 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3847 }
3848 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003849
Amith Yamasani04e0d262012-02-14 11:50:53 -08003850 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003851 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003852 * @hide
3853 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003854 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003855 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003856 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003857 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3858 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003859 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003860 return new Account[0];
3861 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003862 long identityToken = clearCallingIdentity();
3863 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003864 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003865 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003866 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003867 callingUid,
3868 null, // packageName
3869 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003870 } finally {
3871 restoreCallingIdentity(identityToken);
3872 }
3873 }
3874
Amith Yamasanif29f2362012-04-05 18:29:52 -07003875 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003876 * Returns accounts for all running users.
3877 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003878 * @hide
3879 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003880 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003881 public AccountAndUser[] getRunningAccounts() {
3882 final int[] runningUserIds;
3883 try {
3884 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3885 } catch (RemoteException e) {
3886 // Running in system_server; should never happen
3887 throw new RuntimeException(e);
3888 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003889 return getAccounts(runningUserIds);
3890 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003891
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003892 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003893 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003894 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003895 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003896 final int[] userIds = new int[users.size()];
3897 for (int i = 0; i < userIds.length; i++) {
3898 userIds[i] = users.get(i).id;
3899 }
3900 return getAccounts(userIds);
3901 }
3902
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003903 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003904 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003905 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003906 for (int userId : userIds) {
3907 UserAccounts userAccounts = getUserAccounts(userId);
3908 if (userAccounts == null) continue;
3909 synchronized (userAccounts.cacheLock) {
3910 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3911 Binder.getCallingUid(), null);
3912 for (int a = 0; a < accounts.length; a++) {
3913 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003914 }
3915 }
3916 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003917
3918 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3919 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003920 }
3921
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003922 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003923 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003924 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3925 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003926 }
3927
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003928 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003929 private Account[] getAccountsAsUser(
3930 String type,
3931 int userId,
3932 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003933 int packageUid,
3934 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003935 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003936 // Only allow the system process to read accounts of other users
3937 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003938 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003939 && mContext.checkCallingOrSelfPermission(
3940 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3941 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003942 throw new SecurityException("User " + UserHandle.getCallingUserId()
3943 + " trying to get account for " + userId);
3944 }
3945
Fred Quintana56285a62010-12-02 14:20:51 -08003946 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3947 Log.v(TAG, "getAccounts: accountType " + type
3948 + ", caller's uid " + Binder.getCallingUid()
3949 + ", pid " + Binder.getCallingPid());
3950 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003951 // If the original calling app was using the framework account chooser activity, we'll
3952 // be passed in the original caller's uid here, which is what should be used for filtering.
3953 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3954 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003955 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003956 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003957 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3958 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003959 if (visibleAccountTypes.isEmpty()
3960 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003961 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003962 } else if (visibleAccountTypes.contains(type)) {
3963 // Prune the list down to just the requested type.
3964 visibleAccountTypes = new ArrayList<>();
3965 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003966 } // else aggregate all the visible accounts (it won't matter if the
3967 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003968
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003969 long identityToken = clearCallingIdentity();
3970 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003971 UserAccounts accounts = getUserAccounts(userId);
Tejas Khorana69990d92016-08-03 11:19:40 -07003972 Account[] accountsToReturn = getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003973 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003974 callingUid,
3975 callingPackage,
3976 visibleAccountTypes);
Tejas Khorana69990d92016-08-03 11:19:40 -07003977 ArrayList<Account> accountsToReturnList = new
3978 ArrayList<Account>(Arrays.asList(accountsToReturn));
3979 for(int i = accountsToReturnList.size() - 1; i >= 0 ; i--) {
3980 // if account not visible to caller or managed by caller, remove from
3981 // accounts to return. Note that all accounts visible by default unless
3982 // visible list functionality implemented
3983 if(!(isAccountVisible(accountsToReturnList.get(i), callingUid,
3984 getUserAccounts(userId)))) {
3985 accountsToReturnList.remove(i);
3986 }
3987 }
3988 return accountsToReturnList.toArray(new Account[accountsToReturnList.size()]);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003989 } finally {
3990 restoreCallingIdentity(identityToken);
3991 }
3992 }
3993
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003994 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003995 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003996 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003997 int callingUid,
3998 String callingPackage,
3999 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004000 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004001 ArrayList<Account> visibleAccounts = new ArrayList<>();
4002 for (String visibleType : visibleAccountTypes) {
4003 Account[] accountsForType = getAccountsFromCacheLocked(
4004 userAccounts, visibleType, callingUid, callingPackage);
4005 if (accountsForType != null) {
4006 visibleAccounts.addAll(Arrays.asList(accountsForType));
4007 }
4008 }
4009 Account[] result = new Account[visibleAccounts.size()];
4010 for (int i = 0; i < visibleAccounts.size(); i++) {
4011 result[i] = visibleAccounts.get(i);
4012 }
4013 return result;
4014 }
4015 }
4016
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004017 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004018 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004019 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004020 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
4021 for (Account account : accounts) {
4022 addSharedAccountAsUser(account, userId);
4023 }
4024 }
4025
4026 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004027 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004028 UserAccounts accounts = getUserAccounts(userId);
4029 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004030 AccountsDbUtils.deleteSharedAccount(db, account);
4031 long accountId = AccountsDbUtils.insertSharedAccount(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004032 if (accountId < 0) {
4033 Log.w(TAG, "insertAccountIntoDatabase: " + account
4034 + ", skipping the DB insert failed");
4035 return false;
4036 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004037 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004038 return true;
4039 }
4040
4041 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004042 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4043 userId = handleIncomingUser(userId);
4044 UserAccounts accounts = getUserAccounts(userId);
4045 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004046 long sharedTableAccountId = AccountsDbUtils.findSharedAccountId(db, account);
4047 int r = AccountsDbUtils.renameSharedAccount(db, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004048 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004049 int callingUid = getCallingUid();
4050 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
4051 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004052 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004053 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004054 }
4055 return r > 0;
4056 }
4057
4058 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08004059 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004060 return removeSharedAccountAsUser(account, userId, getCallingUid());
4061 }
4062
4063 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004064 userId = handleIncomingUser(userId);
4065 UserAccounts accounts = getUserAccounts(userId);
4066 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004067 long sharedTableAccountId = AccountsDbUtils.findSharedAccountId(db, account);
4068 boolean deleted = AccountsDbUtils.deleteSharedAccount(db, account);
4069 if (deleted) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004070 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
4071 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004072 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004073 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004074 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004075 }
4076
4077 @Override
4078 public Account[] getSharedAccountsAsUser(int userId) {
4079 userId = handleIncomingUser(userId);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004080 SQLiteDatabase db = getUserAccounts(userId).openHelper.getReadableDatabase();
4081 List<Account> accountList = AccountsDbUtils.getSharedAccounts(db);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004082 Account[] accountArray = new Account[accountList.size()];
4083 accountList.toArray(accountArray);
4084 return accountArray;
4085 }
4086
4087 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004088 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004089 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004090 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004091 }
4092
Amith Yamasani27db4682013-03-30 17:07:47 -07004093 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004094 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004095 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004096 int callingUid = Binder.getCallingUid();
4097 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
4098 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4099 + callingUid + " with uid=" + uid);
4100 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004101 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
4102 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07004103 }
4104
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004105 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004106 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004107 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4108 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004109 int packageUid = -1;
4110 try {
4111 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07004112 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
4113 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004114 } catch (RemoteException re) {
4115 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
4116 return new Account[0];
4117 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004118 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
4119 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004120 }
4121
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004122 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004123 public void getAccountsByFeatures(
4124 IAccountManagerResponse response,
4125 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004126 String[] features,
4127 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004128 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08004129 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4130 Log.v(TAG, "getAccounts: accountType " + type
4131 + ", response " + response
4132 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004133 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004134 + ", pid " + Binder.getCallingPid());
4135 }
Fred Quintana382601f2010-03-25 12:25:10 -07004136 if (response == null) throw new IllegalArgumentException("response is null");
4137 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004138 int userId = UserHandle.getCallingUserId();
4139
Svetoslavf3f02ac2015-09-08 14:36:35 -07004140 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4141 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004142 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004143 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004144 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004145 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
4146 try {
4147 response.onResult(result);
4148 } catch (RemoteException e) {
4149 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4150 }
4151 return;
4152 }
Fred Quintana33269202009-04-20 16:05:10 -07004153 long identityToken = clearCallingIdentity();
4154 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004155 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004156 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004157 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004158 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004159 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004160 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004161 Bundle result = new Bundle();
4162 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4163 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004164 return;
4165 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004166 new GetAccountsByTypeAndFeatureSession(
4167 userAccounts,
4168 response,
4169 type,
4170 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004171 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004172 } finally {
4173 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004174 }
4175 }
4176
Fred Quintanaa698f422009-04-08 19:14:54 -07004177 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004178 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004179 IAccountManagerResponse mResponse;
4180 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004181 final boolean mExpectActivityLaunch;
4182 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004183 final String mAccountName;
4184 // Indicates if we need to add auth details(like last credential time)
4185 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004186 // If set, we need to update the last authenticated time. This is
4187 // currently
4188 // used on
4189 // successful confirming credentials.
4190 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004191
Fred Quintana33269202009-04-20 16:05:10 -07004192 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004193 private int mNumRequestContinued = 0;
4194 private int mNumErrors = 0;
4195
Fred Quintana60307342009-03-24 22:48:12 -07004196 IAccountAuthenticator mAuthenticator = null;
4197
Fred Quintana8570f742010-02-18 10:32:54 -08004198 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004199 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004200
Amith Yamasani04e0d262012-02-14 11:50:53 -08004201 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004202 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4203 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004204 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4205 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4206 }
4207
4208 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4209 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4210 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004211 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004212 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004213 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004214 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004215 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004216 mResponse = response;
4217 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004218 mExpectActivityLaunch = expectActivityLaunch;
4219 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004220 mAccountName = accountName;
4221 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004222 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004223
Fred Quintanaa698f422009-04-08 19:14:54 -07004224 synchronized (mSessions) {
4225 mSessions.put(toString(), this);
4226 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004227 if (response != null) {
4228 try {
4229 response.asBinder().linkToDeath(this, 0 /* flags */);
4230 } catch (RemoteException e) {
4231 mResponse = null;
4232 binderDied();
4233 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004234 }
Fred Quintana60307342009-03-24 22:48:12 -07004235 }
4236
Fred Quintanaa698f422009-04-08 19:14:54 -07004237 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004238 if (mResponse == null) {
4239 // this session has already been closed
4240 return null;
4241 }
Fred Quintana60307342009-03-24 22:48:12 -07004242 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004243 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004244 return response;
4245 }
4246
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004247 /**
4248 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4249 * security policy.
4250 *
4251 * In particular we want to make sure that the Authenticator doesn't try to trick users
4252 * into launching aribtrary intents on the device via by tricking to click authenticator
4253 * supplied entries in the system Settings app.
4254 */
4255 protected void checkKeyIntent(
4256 int authUid,
4257 Intent intent) throws SecurityException {
4258 long bid = Binder.clearCallingIdentity();
4259 try {
4260 PackageManager pm = mContext.getPackageManager();
4261 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
4262 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4263 int targetUid = targetActivityInfo.applicationInfo.uid;
Sandra Kwan0e961a12016-06-30 14:34:01 -07004264 if (!GrantCredentialsPermissionActivity.class.getName().equals(
4265 targetActivityInfo.getClass().getName())
4266 && !CantAddAccountActivity.class
4267 .equals(targetActivityInfo.getClass().getName())
4268 && PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid,
4269 targetUid)) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004270 String pkgName = targetActivityInfo.packageName;
4271 String activityName = targetActivityInfo.name;
4272 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4273 + "does not share a signature with the supplying authenticator (%s).";
4274 throw new SecurityException(
4275 String.format(tmpl, activityName, pkgName, mAccountType));
4276 }
4277 } finally {
4278 Binder.restoreCallingIdentity(bid);
4279 }
4280 }
4281
Fred Quintanaa698f422009-04-08 19:14:54 -07004282 private void close() {
4283 synchronized (mSessions) {
4284 if (mSessions.remove(toString()) == null) {
4285 // the session was already closed, so bail out now
4286 return;
4287 }
4288 }
4289 if (mResponse != null) {
4290 // stop listening for response deaths
4291 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4292
4293 // clear this so that we don't accidentally send any further results
4294 mResponse = null;
4295 }
4296 cancelTimeout();
4297 unbind();
4298 }
4299
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004300 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004301 public void binderDied() {
4302 mResponse = null;
4303 close();
4304 }
4305
4306 protected String toDebugString() {
4307 return toDebugString(SystemClock.elapsedRealtime());
4308 }
4309
4310 protected String toDebugString(long now) {
4311 return "Session: expectLaunch " + mExpectActivityLaunch
4312 + ", connected " + (mAuthenticator != null)
4313 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4314 + "/" + mNumErrors + ")"
4315 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4316 }
4317
Fred Quintana60307342009-03-24 22:48:12 -07004318 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004319 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4320 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4321 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004322 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004323 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004324 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004325 }
4326 }
4327
4328 private void unbind() {
4329 if (mAuthenticator != null) {
4330 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004331 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004332 }
4333 }
4334
Fred Quintana60307342009-03-24 22:48:12 -07004335 public void cancelTimeout() {
4336 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
4337 }
4338
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004339 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004340 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004341 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004342 try {
4343 run();
4344 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004345 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004346 "remote exception");
4347 }
Fred Quintana60307342009-03-24 22:48:12 -07004348 }
4349
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004350 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004351 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004352 mAuthenticator = null;
4353 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004354 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004355 try {
4356 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4357 "disconnected");
4358 } catch (RemoteException e) {
4359 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4360 Log.v(TAG, "Session.onServiceDisconnected: "
4361 + "caught RemoteException while responding", e);
4362 }
4363 }
Fred Quintana60307342009-03-24 22:48:12 -07004364 }
4365 }
4366
Fred Quintanab839afc2009-10-14 15:57:28 -07004367 public abstract void run() throws RemoteException;
4368
Fred Quintana60307342009-03-24 22:48:12 -07004369 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004370 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004371 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004372 try {
4373 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4374 "timeout");
4375 } catch (RemoteException e) {
4376 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4377 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4378 e);
4379 }
4380 }
Fred Quintana60307342009-03-24 22:48:12 -07004381 }
4382 }
4383
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004384 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004385 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004386 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004387 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004388 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004389 if (result != null) {
4390 boolean isSuccessfulConfirmCreds = result.getBoolean(
4391 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004392 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004393 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4394 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004395 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004396 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4397 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004398 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004399 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004400 if (needUpdate || mAuthDetailsRequired) {
4401 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4402 if (needUpdate && accountPresent) {
4403 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4404 }
4405 if (mAuthDetailsRequired) {
4406 long lastAuthenticatedTime = -1;
4407 if (accountPresent) {
4408 lastAuthenticatedTime = DatabaseUtils.longForQuery(
4409 mAccounts.openHelper.getReadableDatabase(),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004410 "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4411 + " FROM " +
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004412 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
4413 + ACCOUNTS_TYPE + "=?",
4414 new String[] {
4415 mAccountName, mAccountType
4416 });
4417 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004418 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004419 lastAuthenticatedTime);
4420 }
4421 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004422 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004423 if (result != null
4424 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004425 checkKeyIntent(
4426 Binder.getCallingUid(),
4427 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004428 }
4429 if (result != null
4430 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004431 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4432 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004433 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4434 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004435 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4436 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004437 }
Fred Quintana60307342009-03-24 22:48:12 -07004438 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004439 IAccountManagerResponse response;
4440 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004441 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004442 response = mResponse;
4443 } else {
4444 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004445 }
Fred Quintana60307342009-03-24 22:48:12 -07004446 if (response != null) {
4447 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004448 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004449 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4450 Log.v(TAG, getClass().getSimpleName()
4451 + " calling onError() on response " + response);
4452 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004453 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004454 "null bundle returned");
4455 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004456 if (mStripAuthTokenFromResult) {
4457 result.remove(AccountManager.KEY_AUTHTOKEN);
4458 }
Fred Quintana56285a62010-12-02 14:20:51 -08004459 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4460 Log.v(TAG, getClass().getSimpleName()
4461 + " calling onResult() on response " + response);
4462 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004463 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4464 (intent == null)) {
4465 // All AccountManager error codes are greater than 0
4466 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4467 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4468 } else {
4469 response.onResult(result);
4470 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004471 }
Fred Quintana60307342009-03-24 22:48:12 -07004472 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004473 // if the caller is dead then there is no one to care about remote exceptions
4474 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4475 Log.v(TAG, "failure while notifying response", e);
4476 }
Fred Quintana60307342009-03-24 22:48:12 -07004477 }
4478 }
4479 }
Fred Quintana60307342009-03-24 22:48:12 -07004480
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004481 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004482 public void onRequestContinued() {
4483 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004484 }
4485
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004486 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004487 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004488 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004489 IAccountManagerResponse response = getResponseAndClose();
4490 if (response != null) {
4491 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004492 Log.v(TAG, getClass().getSimpleName()
4493 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004494 }
4495 try {
4496 response.onError(errorCode, errorMessage);
4497 } catch (RemoteException e) {
4498 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4499 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4500 }
4501 }
4502 } else {
4503 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4504 Log.v(TAG, "Session.onError: already closed");
4505 }
Fred Quintana60307342009-03-24 22:48:12 -07004506 }
4507 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004508
4509 /**
4510 * find the component name for the authenticator and initiate a bind
4511 * if no authenticator or the bind fails then return false, otherwise return true
4512 */
4513 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004514 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4515 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4516 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004517 if (authenticatorInfo == null) {
4518 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4519 Log.v(TAG, "there is no authenticator for " + authenticatorType
4520 + ", bailing out");
4521 }
4522 return false;
4523 }
4524
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004525 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004526 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004527 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4528 + " which isn't encryption aware");
4529 return false;
4530 }
4531
Fred Quintanab839afc2009-10-14 15:57:28 -07004532 Intent intent = new Intent();
4533 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4534 intent.setComponent(authenticatorInfo.componentName);
4535 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4536 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4537 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004538 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004539 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4541 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4542 }
4543 return false;
4544 }
4545
Fred Quintanab839afc2009-10-14 15:57:28 -07004546 return true;
4547 }
Fred Quintana60307342009-03-24 22:48:12 -07004548 }
4549
4550 private class MessageHandler extends Handler {
4551 MessageHandler(Looper looper) {
4552 super(looper);
4553 }
Costin Manolache3348f142009-09-29 18:58:36 -07004554
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004555 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004556 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004557 switch (msg.what) {
4558 case MESSAGE_TIMED_OUT:
4559 Session session = (Session)msg.obj;
4560 session.onTimedOut();
4561 break;
4562
Amith Yamasani5be347b2013-03-31 17:44:31 -07004563 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004564 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004565 break;
4566
Fred Quintana60307342009-03-24 22:48:12 -07004567 default:
4568 throw new IllegalStateException("unhandled message: " + msg.what);
4569 }
4570 }
4571 }
4572
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004573 @VisibleForTesting
4574 String getPreNDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07004575 File systemDir = Environment.getDataSystemDirectory();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004576 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
4577 PRE_N_DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004578 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07004579 // Migrate old file, if it exists, to the new location.
4580 // Make sure the new file doesn't already exist. A dummy file could have been
4581 // accidentally created in the old location, causing the new one to become corrupted
4582 // as well.
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004583 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07004584 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07004585 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07004586 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07004587 if (!userDir.exists()) {
4588 if (!userDir.mkdirs()) {
4589 throw new IllegalStateException("User dir cannot be created: " + userDir);
4590 }
4591 }
4592 if (!oldFile.renameTo(databaseFile)) {
4593 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
4594 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004595 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004596 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004597 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08004598 }
4599
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004600 @VisibleForTesting
4601 String getDeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004602 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
4603 DE_DATABASE_NAME);
4604 return databaseFile.getPath();
4605 }
4606
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004607 @VisibleForTesting
4608 String getCeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004609 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4610 CE_DATABASE_NAME);
4611 return databaseFile.getPath();
4612 }
4613
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004614 private static class DebugDbHelper{
4615 private DebugDbHelper() {
4616 }
4617
4618 private static String TABLE_DEBUG = "debug_table";
4619
4620 // Columns for the table
4621 private static String ACTION_TYPE = "action_type";
4622 private static String TIMESTAMP = "time";
4623 private static String CALLER_UID = "caller_uid";
4624 private static String TABLE_NAME = "table_name";
4625 private static String KEY = "primary_key";
4626
4627 // These actions correspond to the occurrence of real actions. Since
4628 // these are called by the authenticators, the uid associated will be
4629 // of the authenticator.
4630 private static String ACTION_SET_PASSWORD = "action_set_password";
4631 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4632 private static String ACTION_ACCOUNT_ADD = "action_account_add";
4633 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004634 private static String ACTION_ACCOUNT_REMOVE_DE = "action_account_remove_de";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004635 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4636 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4637
4638 // These actions don't necessarily correspond to any action on
4639 // accountDb taking place. As an example, there might be a request for
4640 // addingAccount, which might not lead to addition of account on grounds
4641 // of bad authentication. We will still be logging it to keep track of
4642 // who called.
4643 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4644 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004645 private static String ACTION_SYNC_DE_CE_ACCOUNTS = "action_sync_de_ce_accounts";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004646
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004647 //This action doesn't add account to accountdb. Account is only
4648 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08004649 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004650 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4651 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08004652
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004653 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4654
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004655 private static void createDebugTable(SQLiteDatabase db) {
4656 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4657 + ACCOUNTS_ID + " INTEGER,"
4658 + ACTION_TYPE + " TEXT NOT NULL, "
4659 + TIMESTAMP + " DATETIME,"
4660 + CALLER_UID + " INTEGER NOT NULL,"
4661 + TABLE_NAME + " TEXT NOT NULL,"
4662 + KEY + " INTEGER PRIMARY KEY)");
4663 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4664 }
4665 }
4666
4667 private void logRecord(UserAccounts accounts, String action, String tableName) {
4668 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4669 logRecord(db, action, tableName, -1, accounts);
4670 }
4671
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004672 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4673 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4674 logRecord(db, action, tableName, -1, accounts, uid);
4675 }
4676
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004677 /*
4678 * This function receives an opened writable database.
4679 */
4680 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4681 UserAccounts userAccount) {
4682 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4683 }
4684
4685 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004686 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004687 */
4688 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4689 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004690
4691 class LogRecordTask implements Runnable {
4692 private final String action;
4693 private final String tableName;
4694 private final long accountId;
4695 private final UserAccounts userAccount;
4696 private final int callingUid;
4697 private final long userDebugDbInsertionPoint;
4698
4699 LogRecordTask(final String action,
4700 final String tableName,
4701 final long accountId,
4702 final UserAccounts userAccount,
4703 final int callingUid,
4704 final long userDebugDbInsertionPoint) {
4705 this.action = action;
4706 this.tableName = tableName;
4707 this.accountId = accountId;
4708 this.userAccount = userAccount;
4709 this.callingUid = callingUid;
4710 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
4711 }
4712
4713 public void run() {
4714 SQLiteStatement logStatement = userAccount.statementForLogging;
4715 logStatement.bindLong(1, accountId);
4716 logStatement.bindString(2, action);
4717 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4718 logStatement.bindLong(4, callingUid);
4719 logStatement.bindString(5, tableName);
4720 logStatement.bindLong(6, userDebugDbInsertionPoint);
4721 logStatement.execute();
4722 logStatement.clearBindings();
4723 }
4724 }
4725
4726 mLogRecordRunnables.add(new LogRecordTask(action, tableName, accountId, userAccount,
4727 callingUid, userAccount.debugDbInsertionPoint));
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004728 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4729 % MAX_DEBUG_DB_SIZE;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004730
4731
4732 if(mLogRecordThread == null || !mLogRecordThread.isAlive()) {
4733 mLogRecordThread = new Thread(new Runnable() {
4734 public void run() {
4735 while(mLogRecordRunnables.size() > 0) {
4736 mLogRecordRunnables.pollFirst().run();
4737 }
4738 }
4739 });
4740 mLogRecordThread.start();
4741 }
4742
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004743 }
4744
4745 /*
4746 * This should only be called once to compile the sql statement for logging
4747 * and to find the insertion point.
4748 */
4749 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4750 UserAccounts userAccount) {
4751 // Initialize the count if not done earlier.
4752 int size = (int) getDebugTableRowCount(db);
4753 if (size >= MAX_DEBUG_DB_SIZE) {
4754 // Table is full, and we need to find the point where to insert.
4755 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4756 } else {
4757 userAccount.debugDbInsertionPoint = size;
4758 }
4759 compileSqlStatementForLogging(db, userAccount);
4760 }
4761
4762 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4763 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4764 + " VALUES (?,?,?,?,?,?)";
4765 userAccount.statementForLogging = db.compileStatement(sql);
4766 }
4767
4768 private long getDebugTableRowCount(SQLiteDatabase db) {
4769 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4770 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4771 }
4772
4773 /*
4774 * Finds the row key where the next insertion should take place. This should
4775 * be invoked only if the table has reached its full capacity.
4776 */
4777 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4778 // This query finds the smallest timestamp value (and if 2 records have
4779 // same timestamp, the choose the lower id).
4780 String queryCountDebugDbRows = new StringBuilder()
4781 .append("SELECT ").append(DebugDbHelper.KEY)
4782 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4783 .append(" ORDER BY ")
4784 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4785 .append(" LIMIT 1")
4786 .toString();
4787 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4788 }
4789
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004790 static class PreNDatabaseHelper extends SQLiteOpenHelper {
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004791 private final Context mContext;
4792 private final int mUserId;
4793
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004794 public PreNDatabaseHelper(Context context, int userId, String preNDatabaseName) {
4795 super(context, preNDatabaseName, null, PRE_N_DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004796 mContext = context;
4797 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004798 }
4799
4800 @Override
4801 public void onCreate(SQLiteDatabase db) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004802 // We use PreNDatabaseHelper only if pre-N db exists
4803 throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004804 }
4805
Amith Yamasani67df64b2012-12-14 12:09:36 -08004806 private void createSharedAccountsTable(SQLiteDatabase db) {
4807 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4808 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4809 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4810 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4811 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4812 }
4813
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004814 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4815 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4816 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4817 }
4818
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004819 private void addOldAccountNameColumn(SQLiteDatabase db) {
4820 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4821 }
4822
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004823 private void addDebugTable(SQLiteDatabase db) {
4824 DebugDbHelper.createDebugTable(db);
4825 }
4826
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004827 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004828 db.execSQL(""
4829 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4830 + " BEGIN"
4831 + " DELETE FROM " + TABLE_AUTHTOKENS
4832 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4833 + " DELETE FROM " + TABLE_EXTRAS
4834 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004835 + " DELETE FROM " + TABLE_GRANTS
4836 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004837 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004838 }
4839
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004840 private void createGrantsTable(SQLiteDatabase db) {
4841 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4842 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4843 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4844 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4845 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4846 + "," + GRANTS_GRANTEE_UID + "))");
4847 }
4848
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004849 private void populateMetaTableWithAuthTypeAndUID(SQLiteDatabase db,
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004850 Map<String, Integer> authTypeAndUIDMap) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004851 for (Entry<String, Integer> entry : authTypeAndUIDMap.entrySet()) {
4852 AccountsDbUtils.insertMetaAuthTypeAndUid(db, entry.getKey(), entry.getValue());
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004853 }
4854 }
4855
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004856 /**
4857 * Pre-N database may need an upgrade before splitting
4858 */
Fred Quintana60307342009-03-24 22:48:12 -07004859 @Override
4860 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004861 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004862
Fred Quintanaa698f422009-04-08 19:14:54 -07004863 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004864 // no longer need to do anything since the work is done
4865 // when upgrading from version 2
4866 oldVersion++;
4867 }
4868
4869 if (oldVersion == 2) {
4870 createGrantsTable(db);
4871 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4872 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004873 oldVersion++;
4874 }
Costin Manolache3348f142009-09-29 18:58:36 -07004875
4876 if (oldVersion == 3) {
4877 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4878 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4879 oldVersion++;
4880 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004881
4882 if (oldVersion == 4) {
4883 createSharedAccountsTable(db);
4884 oldVersion++;
4885 }
4886
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004887 if (oldVersion == 5) {
4888 addOldAccountNameColumn(db);
4889 oldVersion++;
4890 }
4891
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004892 if (oldVersion == 6) {
4893 addLastSuccessfullAuthenticatedTimeColumn(db);
4894 oldVersion++;
4895 }
4896
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004897 if (oldVersion == 7) {
4898 addDebugTable(db);
4899 oldVersion++;
4900 }
4901
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004902 if (oldVersion == 8) {
4903 populateMetaTableWithAuthTypeAndUID(
4904 db,
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004905 getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004906 oldVersion++;
4907 }
4908
Amith Yamasani67df64b2012-12-14 12:09:36 -08004909 if (oldVersion != newVersion) {
4910 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4911 }
Fred Quintana60307342009-03-24 22:48:12 -07004912 }
4913
4914 @Override
4915 public void onOpen(SQLiteDatabase db) {
4916 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4917 }
4918 }
4919
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004920 static class DeDatabaseHelper extends SQLiteOpenHelper {
4921
4922 private final int mUserId;
4923 private volatile boolean mCeAttached;
4924
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004925 private DeDatabaseHelper(Context context, int userId, String deDatabaseName) {
4926 super(context, deDatabaseName, null, DE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004927 mUserId = userId;
4928 }
4929
4930 /**
4931 * This call needs to be made while the mCacheLock is held. The way to
4932 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4933 * @param db The database.
4934 */
4935 @Override
4936 public void onCreate(SQLiteDatabase db) {
4937 Log.i(TAG, "Creating DE database for user " + mUserId);
4938 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4939 + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4940 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4941 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4942 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4943 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4944 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4945
4946 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4947 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4948 + META_VALUE + " TEXT)");
4949
4950 createGrantsTable(db);
4951 createSharedAccountsTable(db);
4952 createAccountsDeletionTrigger(db);
4953 DebugDbHelper.createDebugTable(db);
4954 }
4955
4956 private void createSharedAccountsTable(SQLiteDatabase db) {
4957 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4958 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4959 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4960 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4961 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4962 }
4963
4964 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4965 db.execSQL(""
4966 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4967 + " BEGIN"
4968 + " DELETE FROM " + TABLE_GRANTS
4969 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4970 + " END");
4971 }
4972
4973 private void createGrantsTable(SQLiteDatabase db) {
4974 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4975 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4976 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4977 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4978 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4979 + "," + GRANTS_GRANTEE_UID + "))");
4980 }
4981
4982 @Override
4983 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4984 Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4985
4986 if (oldVersion != newVersion) {
4987 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4988 }
4989 }
4990
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004991 public void attachCeDatabase(File ceDbFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004992 SQLiteDatabase db = getWritableDatabase();
4993 db.execSQL("ATTACH DATABASE '" + ceDbFile.getPath()+ "' AS ceDb");
4994 mCeAttached = true;
4995 }
4996
4997 public boolean isCeDatabaseAttached() {
4998 return mCeAttached;
4999 }
5000
5001
5002 public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
5003 if(!mCeAttached) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005004 Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user " + mUserId
5005 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005006 }
5007 return super.getReadableDatabase();
5008 }
5009
5010 public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
5011 if(!mCeAttached) {
5012 Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005013 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005014 }
5015 return super.getWritableDatabase();
5016 }
5017
5018 @Override
5019 public void onOpen(SQLiteDatabase db) {
5020 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
5021 }
5022
5023 private void migratePreNDbToDe(File preNDbFile) {
5024 Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
5025 SQLiteDatabase db = getWritableDatabase();
5026 db.execSQL("ATTACH DATABASE '" + preNDbFile.getPath() + "' AS preNDb");
5027 db.beginTransaction();
5028 // Copy accounts fields
5029 db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
5030 + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
5031 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
5032 + ") "
5033 + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
5034 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
5035 + " FROM preNDb." + TABLE_ACCOUNTS);
5036 // Copy SHARED_ACCOUNTS
5037 db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
5038 + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
5039 "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
5040 + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
5041 // Copy DEBUG_TABLE
5042 db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
5043 + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
5044 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
5045 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
5046 "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
5047 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
5048 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
5049 + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
5050 // Copy GRANTS
5051 db.execSQL("INSERT INTO " + TABLE_GRANTS
5052 + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
5053 + GRANTS_GRANTEE_UID + ") " +
5054 "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
5055 + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
5056 // Copy META
5057 db.execSQL("INSERT INTO " + TABLE_META
5058 + "(" + META_KEY + "," + META_VALUE + ") "
5059 + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
5060 db.setTransactionSuccessful();
5061 db.endTransaction();
5062
5063 db.execSQL("DETACH DATABASE preNDb");
5064 }
5065
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005066 static DeDatabaseHelper create(
5067 Context context,
5068 int userId,
5069 File preNDatabaseFile,
5070 File deDatabaseFile) {
5071 boolean newDbExists = deDatabaseFile.exists();
5072 DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId,
5073 deDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005074 // If the db just created, and there is a legacy db, migrate it
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005075 if (!newDbExists && preNDatabaseFile.exists()) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005076 // Migrate legacy db to the latest version - PRE_N_DATABASE_VERSION
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005077 PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId,
5078 preNDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005079 // Open the database to force upgrade if required
5080 preNDatabaseHelper.getWritableDatabase();
5081 preNDatabaseHelper.close();
5082 // Move data without SPII to DE
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005083 deDatabaseHelper.migratePreNDbToDe(preNDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005084 }
5085 return deDatabaseHelper;
5086 }
5087 }
5088
5089 static class CeDatabaseHelper extends SQLiteOpenHelper {
5090
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005091 public CeDatabaseHelper(Context context, String ceDatabaseName) {
5092 super(context, ceDatabaseName, null, CE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005093 }
5094
5095 /**
5096 * This call needs to be made while the mCacheLock is held.
5097 * @param db The database.
5098 */
5099 @Override
5100 public void onCreate(SQLiteDatabase db) {
5101 Log.i(TAG, "Creating CE database " + getDatabaseName());
5102 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
5103 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
5104 + ACCOUNTS_NAME + " TEXT NOT NULL, "
5105 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
5106 + ACCOUNTS_PASSWORD + " TEXT, "
5107 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
5108
5109 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
5110 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
5111 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
5112 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
5113 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
5114 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
5115
5116 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
5117 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
5118 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
5119 + EXTRAS_KEY + " TEXT NOT NULL, "
5120 + EXTRAS_VALUE + " TEXT, "
5121 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
5122
5123 createAccountsDeletionTrigger(db);
5124 }
5125
5126 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
5127 db.execSQL(""
5128 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
5129 + " BEGIN"
5130 + " DELETE FROM " + TABLE_AUTHTOKENS
5131 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
5132 + " DELETE FROM " + TABLE_EXTRAS
5133 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
5134 + " END");
5135 }
5136
5137 @Override
5138 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
5139 Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
5140
5141 if (oldVersion == 9) {
5142 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5143 Log.v(TAG, "onUpgrade upgrading to v10");
5144 }
5145 db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
5146 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
5147 // Recreate the trigger, since the old one references the table to be removed
5148 db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
5149 createAccountsDeletionTrigger(db);
5150 db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
5151 db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
5152 oldVersion ++;
5153 }
5154
5155 if (oldVersion != newVersion) {
5156 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
5157 }
5158 }
5159
5160 @Override
5161 public void onOpen(SQLiteDatabase db) {
5162 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
5163 }
5164
Fyodor Kupolov35f68082016-04-06 12:14:17 -07005165
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005166 /**
5167 * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
5168 * it also performs migration to the new CE database.
5169 * @param context
5170 * @param userId id of the user where the database is located
5171 */
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005172 static CeDatabaseHelper create(
5173 Context context,
5174 int userId,
5175 File preNDatabaseFile,
5176 File ceDatabaseFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005177 boolean newDbExists = ceDatabaseFile.exists();
5178 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5179 Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005180 + preNDatabaseFile.exists() + " newDbExists=" + newDbExists);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005181 }
5182 boolean removeOldDb = false;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005183 if (!newDbExists && preNDatabaseFile.exists()) {
5184 removeOldDb = migratePreNDbToCe(preNDatabaseFile, ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005185 }
5186 // Try to open and upgrade if necessary
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005187 CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, ceDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005188 ceHelper.getWritableDatabase();
5189 ceHelper.close();
5190 if (removeOldDb) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07005191 Slog.i(TAG, "Migration complete - removing pre-N db " + preNDatabaseFile);
5192 if (!SQLiteDatabase.deleteDatabase(preNDatabaseFile)) {
5193 Slog.e(TAG, "Cannot remove pre-N db " + preNDatabaseFile);
5194 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005195 }
5196 return ceHelper;
5197 }
5198
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005199 private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07005200 Slog.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005201 try {
5202 FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
5203 } catch (IOException e) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07005204 Slog.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005205 // Try to remove potentially damaged file if I/O error occurred
5206 deleteDbFileWarnIfFailed(ceDbFile);
5207 return false;
5208 }
5209 return true;
5210 }
5211 }
5212
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005213 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07005214 return asBinder();
5215 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005216
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005217 /**
5218 * Searches array of arguments for the specified string
5219 * @param args array of argument strings
5220 * @param value value to search for
5221 * @return true if the value is contained in the array
5222 */
5223 private static boolean scanArgs(String[] args, String value) {
5224 if (args != null) {
5225 for (String arg : args) {
5226 if (value.equals(arg)) {
5227 return true;
5228 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005229 }
5230 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005231 return false;
5232 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005233
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005234 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005235 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07005236 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5237 != PackageManager.PERMISSION_GRANTED) {
5238 fout.println("Permission Denial: can't dump AccountsManager from from pid="
5239 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
5240 + " without permission " + android.Manifest.permission.DUMP);
5241 return;
5242 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005243 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005244 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07005245
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005246 final List<UserInfo> users = getUserManager().getUsers();
5247 for (UserInfo user : users) {
5248 ipw.println("User " + user + ":");
5249 ipw.increaseIndent();
5250 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
5251 ipw.println();
5252 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005253 }
5254 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005255
Amith Yamasani04e0d262012-02-14 11:50:53 -08005256 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5257 String[] args, boolean isCheckinRequest) {
5258 synchronized (userAccounts.cacheLock) {
5259 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005260
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005261 if (isCheckinRequest) {
5262 // This is a checkin request. *Only* upload the account types and the count of each.
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005263 AccountsDbUtils.dumpAccountsTable(db, fout);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005264 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005265 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07005266 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005267 fout.println("Accounts: " + accounts.length);
5268 for (Account account : accounts) {
5269 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005270 }
Fred Quintana307da1a2010-01-21 14:24:20 -08005271
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005272 // Add debug information.
5273 fout.println();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005274 AccountsDbUtils.dumpDebugTable(db, fout);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005275 fout.println();
5276 synchronized (mSessions) {
5277 final long now = SystemClock.elapsedRealtime();
5278 fout.println("Active Sessions: " + mSessions.size());
5279 for (Session session : mSessions.values()) {
5280 fout.println(" " + session.toDebugString(now));
5281 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005282 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005283
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005284 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005285 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005286 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005287 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005288 }
5289
Amith Yamasani04e0d262012-02-14 11:50:53 -08005290 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07005291 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005292 long identityToken = clearCallingIdentity();
5293 try {
5294 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5295 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5296 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005297
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005298 if (intent.getComponent() != null &&
5299 GrantCredentialsPermissionActivity.class.getName().equals(
5300 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07005301 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005302 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005303 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07005304 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005305 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005306 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07005307 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005308 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005309 Notification n = new Notification.Builder(contextForUser)
5310 .setWhen(0)
5311 .setSmallIcon(android.R.drawable.stat_sys_warning)
5312 .setColor(contextForUser.getColor(
5313 com.android.internal.R.color.system_notification_accent_color))
5314 .setContentTitle(String.format(notificationTitleFormat, account.name))
5315 .setContentText(message)
5316 .setContentIntent(PendingIntent.getActivityAsUser(
5317 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
5318 null, user))
5319 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005320 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005321 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005322 } finally {
5323 restoreCallingIdentity(identityToken);
5324 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005325 }
5326
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005327 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005328 protected void installNotification(final int notificationId, final Notification n,
5329 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08005330 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005331 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08005332 }
5333
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005334 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005335 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005336 long identityToken = clearCallingIdentity();
5337 try {
5338 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005339 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005340 } finally {
5341 restoreCallingIdentity(identityToken);
5342 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005343 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005344
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005345 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5346 for (String perm : permissions) {
5347 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5348 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5349 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5350 }
5351 final int opCode = AppOpsManager.permissionToOpCode(perm);
5352 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5353 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5354 return true;
5355 }
5356 }
5357 }
5358 return false;
5359 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005360
Amith Yamasani67df64b2012-12-14 12:09:36 -08005361 private int handleIncomingUser(int userId) {
5362 try {
5363 return ActivityManagerNative.getDefault().handleIncomingUser(
5364 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5365 } catch (RemoteException re) {
5366 // Shouldn't happen, local.
5367 }
5368 return userId;
5369 }
5370
Christopher Tateccbf84f2013-05-08 15:25:41 -07005371 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005372 final int callingUserId = UserHandle.getUserId(callingUid);
5373
5374 final PackageManager userPackageManager;
5375 try {
5376 userPackageManager = mContext.createPackageContextAsUser(
5377 "android", 0, new UserHandle(callingUserId)).getPackageManager();
5378 } catch (NameNotFoundException e) {
5379 return false;
5380 }
5381
5382 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005383 for (String name : packages) {
5384 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005385 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08005386 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08005387 && (packageInfo.applicationInfo.privateFlags
5388 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07005389 return true;
5390 }
5391 } catch (PackageManager.NameNotFoundException e) {
5392 return false;
5393 }
5394 }
5395 return false;
5396 }
5397
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005398 private boolean permissionIsGranted(
5399 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07005400 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07005401 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005402 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07005403 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08005404 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005405 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5406 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08005407 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005408 + ": is authenticator? " + fromAuthenticator
5409 + ", has explicit permission? " + hasExplicitGrants);
5410 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07005411 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005412 }
5413
Svetoslavf3f02ac2015-09-08 14:36:35 -07005414 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5415 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005416 if (accountType == null) {
5417 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005418 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005419 return getTypesVisibleToCaller(callingUid, userId,
5420 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005421 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005422 }
5423
5424 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5425 if (accountType == null) {
5426 return false;
5427 } else {
5428 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5429 }
5430 }
5431
Svetoslavf3f02ac2015-09-08 14:36:35 -07005432 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5433 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005434 boolean isPermitted =
5435 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
5436 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005437 return getTypesForCaller(callingUid, userId, isPermitted);
5438 }
5439
5440 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
5441 return getTypesForCaller(callingUid, userId, false);
5442 }
5443
5444 private List<String> getTypesForCaller(
5445 int callingUid, int userId, boolean isOtherwisePermitted) {
5446 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005447 long identityToken = Binder.clearCallingIdentity();
5448 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5449 try {
5450 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5451 } finally {
5452 Binder.restoreCallingIdentity(identityToken);
5453 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005454 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005455 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005456 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5457 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
5458 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005459 }
5460 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005461 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005462 }
5463
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005464 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5465 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5466 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5467 if (account.name.equals(accountName)) {
5468 return true;
5469 }
5470 }
5471 }
5472 return false;
5473 }
5474
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005475 private static void checkManageUsersPermission(String message) {
5476 if (ActivityManager.checkComponentPermission(
5477 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5478 != PackageManager.PERMISSION_GRANTED) {
5479 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5480 }
5481 }
5482
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005483 private static void checkManageOrCreateUsersPermission(String message) {
5484 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5485 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5486 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5487 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5488 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5489 + message);
5490 }
5491 }
5492
Amith Yamasani04e0d262012-02-14 11:50:53 -08005493 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5494 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07005495 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005496 return true;
5497 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005498 UserAccounts accounts = getUserAccountsForCaller();
5499 synchronized (accounts.cacheLock) {
5500 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005501 final boolean permissionGranted = AccountsDbUtils.findMatchingGrantsCount(db, callerUid,
5502 authTokenType, account) != 0;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005503 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5504 // TODO: Skip this check when running automated tests. Replace this
5505 // with a more general solution.
5506 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08005507 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005508 + " but ignoring since device is in test harness.");
5509 return true;
5510 }
5511 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005512 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005513 }
5514
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005515 private boolean isSystemUid(int callingUid) {
5516 String[] packages = null;
5517 long ident = Binder.clearCallingIdentity();
5518 try {
5519 packages = mPackageManager.getPackagesForUid(callingUid);
5520 } finally {
5521 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005522 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005523 if (packages != null) {
5524 for (String name : packages) {
5525 try {
5526 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5527 if (packageInfo != null
5528 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5529 != 0) {
5530 return true;
5531 }
5532 } catch (PackageManager.NameNotFoundException e) {
5533 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5534 }
5535 }
5536 } else {
5537 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005538 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005539 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005540 }
5541
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005542 /** Succeeds if any of the specified permissions are granted. */
5543 private void checkReadAccountsPermitted(
5544 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005545 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005546 int userId,
5547 String opPackageName) {
5548 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005549 String msg = String.format(
5550 "caller uid %s cannot access %s accounts",
5551 callingUid,
5552 accountType);
5553 Log.w(TAG, " " + msg);
5554 throw new SecurityException(msg);
5555 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005556 }
5557
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005558 private boolean canUserModifyAccounts(int userId, int callingUid) {
5559 // the managing app can always modify accounts
5560 if (isProfileOwner(callingUid)) {
5561 return true;
5562 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005563 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5564 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5565 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005566 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005567 return true;
5568 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005569
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005570 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5571 // the managing app can always modify accounts
5572 if (isProfileOwner(callingUid)) {
5573 return true;
5574 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005575 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5576 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005577 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005578 if (typesArray == null) {
5579 return true;
5580 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005581 for (String forbiddenType : typesArray) {
5582 if (forbiddenType.equals(accountType)) {
5583 return false;
5584 }
5585 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005586 return true;
5587 }
5588
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005589 private boolean isProfileOwner(int uid) {
5590 final DevicePolicyManagerInternal dpmi =
5591 LocalServices.getService(DevicePolicyManagerInternal.class);
5592 return (dpmi != null)
5593 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5594 }
5595
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005596 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005597 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5598 throws RemoteException {
5599 final int callingUid = getCallingUid();
5600
Amith Yamasani27db4682013-03-30 17:07:47 -07005601 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005602 throw new SecurityException();
5603 }
5604
5605 if (value) {
5606 grantAppPermission(account, authTokenType, uid);
5607 } else {
5608 revokeAppPermission(account, authTokenType, uid);
5609 }
5610 }
5611
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005612 /**
5613 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5614 * <p>
5615 * Although this is public it can only be accessed via the AccountManagerService object
5616 * which is in the system. This means we don't need to protect it with permissions.
5617 * @hide
5618 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005619 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005620 if (account == null || authTokenType == null) {
5621 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005622 return;
5623 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005624 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005625 synchronized (accounts.cacheLock) {
5626 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005627 long accountId = AccountsDbUtils.findAccountId(db, account);
5628 if (accountId >= 0) {
5629 AccountsDbUtils.insertGrant(db, accountId, authTokenType, uid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005630 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005631 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005632 UserHandle.of(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005633 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005634 }
5635
5636 /**
5637 * Don't allow callers with the given uid permission to get credentials for
5638 * account/authTokenType.
5639 * <p>
5640 * Although this is public it can only be accessed via the AccountManagerService object
5641 * which is in the system. This means we don't need to protect it with permissions.
5642 * @hide
5643 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005644 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005645 if (account == null || authTokenType == null) {
5646 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005647 return;
5648 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005649 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005650 synchronized (accounts.cacheLock) {
5651 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005652 db.beginTransaction();
5653 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005654 long accountId = AccountsDbUtils.findAccountId(db, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005655 if (accountId >= 0) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005656 AccountsDbUtils.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5657 db, accountId, authTokenType, uid);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005658 db.setTransactionSuccessful();
5659 }
5660 } finally {
5661 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005662 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005663 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5664 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005665 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005666 }
Fred Quintana56285a62010-12-02 14:20:51 -08005667
5668 static final private String stringArrayToString(String[] value) {
5669 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5670 }
5671
Amith Yamasani04e0d262012-02-14 11:50:53 -08005672 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5673 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005674 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005675 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005676 for (Account curAccount : oldAccountsForType) {
5677 if (!curAccount.equals(account)) {
5678 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005679 }
5680 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005681 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005682 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005683 } else {
5684 Account[] newAccountsForType = new Account[newAccountsList.size()];
5685 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005686 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005687 }
Fred Quintana56285a62010-12-02 14:20:51 -08005688 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005689 accounts.userDataCache.remove(account);
5690 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005691 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005692 }
5693
5694 /**
5695 * This assumes that the caller has already checked that the account is not already present.
5696 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08005697 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5698 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005699 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5700 Account[] newAccountsForType = new Account[oldLength + 1];
5701 if (accountsForType != null) {
5702 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005703 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005704 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005705 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08005706 }
5707
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005708 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07005709 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005710 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07005711 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005712 return unfiltered;
5713 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005714 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005715 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005716 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005717 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005718 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005719 // This might be a temporary way to specify a visible list
5720 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005721 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5722 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005723 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005724 return unfiltered;
5725 }
5726 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005727 ArrayList<Account> allowed = new ArrayList<>();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005728 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5729 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005730 String requiredAccountType = "";
5731 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005732 // If there's an explicit callingPackage specified, check if that package
5733 // opted in to see restricted accounts.
5734 if (callingPackage != null) {
5735 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005736 if (pi != null && pi.restrictedAccountType != null) {
5737 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005738 }
5739 } else {
5740 // Otherwise check if the callingUid has a package that has opted in
5741 for (String packageName : packages) {
5742 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5743 if (pi != null && pi.restrictedAccountType != null) {
5744 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005745 break;
5746 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005747 }
5748 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005749 } catch (NameNotFoundException nnfe) {
5750 }
5751 for (Account account : unfiltered) {
5752 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005753 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005754 } else {
5755 boolean found = false;
5756 for (Account shared : sharedAccounts) {
5757 if (shared.equals(account)) {
5758 found = true;
5759 break;
5760 }
5761 }
5762 if (!found) {
5763 allowed.add(account);
5764 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005765 }
5766 }
5767 Account[] filtered = new Account[allowed.size()];
5768 allowed.toArray(filtered);
5769 return filtered;
5770 } else {
5771 return unfiltered;
5772 }
5773 }
5774
Amith Yamasani27db4682013-03-30 17:07:47 -07005775 /*
5776 * packageName can be null. If not null, it should be used to filter out restricted accounts
5777 * that the package is not allowed to access.
5778 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005779 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07005780 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005781 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005782 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005783 if (accounts == null) {
5784 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005785 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005786 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07005787 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005788 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005789 } else {
5790 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005791 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005792 totalLength += accounts.length;
5793 }
5794 if (totalLength == 0) {
5795 return EMPTY_ACCOUNT_ARRAY;
5796 }
5797 Account[] accounts = new Account[totalLength];
5798 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005799 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005800 System.arraycopy(accountsOfType, 0, accounts, totalLength,
5801 accountsOfType.length);
5802 totalLength += accountsOfType.length;
5803 }
Amith Yamasani27db4682013-03-30 17:07:47 -07005804 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005805 }
5806 }
5807
Amith Yamasani04e0d262012-02-14 11:50:53 -08005808 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5809 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005810 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005811 if (userDataForAccount == null) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005812 userDataForAccount = AccountsDbUtils.findUserExtrasForAccount(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005813 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005814 }
5815 if (value == null) {
5816 userDataForAccount.remove(key);
5817 } else {
5818 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005819 }
5820 }
5821
Carlos Valdivia91979be2015-05-22 14:11:35 -07005822 protected String readCachedTokenInternal(
5823 UserAccounts accounts,
5824 Account account,
5825 String tokenType,
5826 String callingPackage,
5827 byte[] pkgSigDigest) {
5828 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005829 return accounts.accountTokenCaches.get(
5830 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005831 }
5832 }
5833
Amith Yamasani04e0d262012-02-14 11:50:53 -08005834 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5835 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005836 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005837 if (authTokensForAccount == null) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005838 authTokensForAccount = AccountsDbUtils.findAuthTokensByAccount(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005839 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005840 }
5841 if (value == null) {
5842 authTokensForAccount.remove(key);
5843 } else {
5844 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005845 }
5846 }
5847
Amith Yamasani04e0d262012-02-14 11:50:53 -08005848 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5849 String authTokenType) {
5850 synchronized (accounts.cacheLock) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005851 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005852 if (authTokensForAccount == null) {
5853 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005854 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005855 authTokensForAccount = AccountsDbUtils
5856 .findAuthTokensByAccount(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005857 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005858 }
5859 return authTokensForAccount.get(authTokenType);
5860 }
5861 }
5862
Simranjit Kohli858511c2016-03-10 18:36:11 +00005863 protected String readUserDataInternalLocked(
5864 UserAccounts accounts, Account account, String key) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005865 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Simranjit Kohli858511c2016-03-10 18:36:11 +00005866 if (userDataForAccount == null) {
5867 // need to populate the cache for this account
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005868 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005869 userDataForAccount = AccountsDbUtils.findUserExtrasForAccount(db, account);
Simranjit Kohli858511c2016-03-10 18:36:11 +00005870 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005871 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005872 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005873 }
5874
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005875 private Context getContextForUser(UserHandle user) {
5876 try {
5877 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5878 } catch (NameNotFoundException e) {
5879 // Default to mContext, not finding the package system is running as is unlikely.
5880 return mContext;
5881 }
5882 }
Sandra Kwan78812282015-11-04 11:19:47 -08005883
5884 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5885 try {
5886 response.onResult(result);
5887 } catch (RemoteException e) {
5888 // if the caller is dead then there is no one to care about remote
5889 // exceptions
5890 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5891 Log.v(TAG, "failure while notifying response", e);
5892 }
5893 }
5894 }
5895
5896 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5897 String errorMessage) {
5898 try {
5899 response.onError(errorCode, errorMessage);
5900 } catch (RemoteException e) {
5901 // if the caller is dead then there is no one to care about remote
5902 // exceptions
5903 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5904 Log.v(TAG, "failure while notifying response", e);
5905 }
5906 }
5907 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005908
5909 static class AccountsDbUtils {
5910
5911 static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
5912 String type) {
5913 Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
5914 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
5915 new String[]{name, type}, null, null, null);
5916 try {
5917 if (cursor.moveToNext()) {
5918 return cursor.getString(0);
5919 }
5920 return null;
5921 } finally {
5922 cursor.close();
5923 }
5924 }
5925
5926 static Map<Long, Account> findAllAccounts(SQLiteDatabase db) {
5927 LinkedHashMap<Long, Account> map = new LinkedHashMap<>();
5928 Cursor cursor = db.query(TABLE_ACCOUNTS,
5929 new String[] {ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
5930 null, null, null, null, ACCOUNTS_ID);
5931 try {
5932 while (cursor.moveToNext()) {
5933 final long accountId = cursor.getLong(0);
5934 final String accountType = cursor.getString(1);
5935 final String accountName = cursor.getString(2);
5936
5937 final Account account = new Account(accountName, accountType);
5938 map.put(accountId, account);
5939 }
5940 } finally {
5941 cursor.close();
5942 }
5943 return map;
5944 }
5945
5946 static String findAccountPreviousName(SQLiteDatabase db, Account account) {
5947 Cursor cursor = db.query(
5948 TABLE_ACCOUNTS,
5949 new String[]{ ACCOUNTS_PREVIOUS_NAME },
5950 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
5951 new String[] { account.name, account.type },
5952 null,
5953 null,
5954 null);
5955 try {
5956 if (cursor.moveToNext()) {
5957 return cursor.getString(0);
5958 }
5959 } finally {
5960 cursor.close();
5961 }
5962 return null;
5963 }
5964
5965 static List<Account> findCeAccountsNotInDe(SQLiteDatabase db) {
5966 // Select accounts from CE that do not exist in DE
5967 Cursor cursor = db.rawQuery(
5968 "SELECT " + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
5969 + " FROM " + CE_TABLE_ACCOUNTS
5970 + " WHERE NOT EXISTS "
5971 + " (SELECT " + ACCOUNTS_ID + " FROM " + TABLE_ACCOUNTS
5972 + " WHERE " + ACCOUNTS_ID + "=" + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
5973 + " )", null);
5974 try {
5975 List<Account> accounts = new ArrayList<>(cursor.getCount());
5976 while (cursor.moveToNext()) {
5977 String accountName = cursor.getString(0);
5978 String accountType = cursor.getString(1);
5979 accounts.add(new Account(accountName, accountType));
5980 }
5981 return accounts;
5982 } finally {
5983 cursor.close();
5984 }
5985 }
5986
5987 static boolean deleteAccount(SQLiteDatabase db, long accountId) {
5988 return db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null) > 0;
5989 }
5990
5991 static boolean deleteCeAccount(SQLiteDatabase db, long accountId) {
5992 return db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null) > 0;
5993 }
5994
5995 /**
5996 * Returns information about auth tokens and their account for the specified query parameters.
5997 * Output is in the format:
5998 * <pre><code> | AUTHTOKEN_ID | ACCOUNT_NAME | AUTH_TOKEN_TYPE |</code></pre>
5999 */
6000 static Cursor findAuthtokenForAllAccounts(SQLiteDatabase db, String accountType,
6001 String authToken) {
6002 return db.rawQuery(
6003 "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
6004 + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
6005 + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
6006 + " FROM " + CE_TABLE_ACCOUNTS
6007 + " JOIN " + CE_TABLE_AUTHTOKENS
6008 + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
6009 + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
6010 + " WHERE " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_AUTHTOKEN
6011 + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
6012 new String[]{authToken, accountType});
6013 }
6014
6015 static boolean deleteAuthtokensByAccountIdAndType(SQLiteDatabase db, long accountId,
6016 String authtokenType) {
6017 return db.delete(CE_TABLE_AUTHTOKENS,
6018 AUTHTOKENS_ACCOUNTS_ID + "=?" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
6019 new String[] {String.valueOf(accountId), authtokenType}) > 0;
6020 }
6021
6022 static boolean deleteAuthToken(SQLiteDatabase db, String authTokenId) {
6023 return db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "= ?",
6024 new String[] {authTokenId}) > 0;
6025 }
6026
6027 static long insertAuthToken(SQLiteDatabase db, long accountId, String authTokenType,
6028 String authToken) {
6029 ContentValues values = new ContentValues();
6030 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
6031 values.put(AUTHTOKENS_TYPE, authTokenType);
6032 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
6033 return db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values);
6034 }
6035
6036 static Map<String, String> findAuthTokensByAccount(final SQLiteDatabase db, Account account) {
6037 HashMap<String, String> authTokensForAccount = new HashMap<>();
6038 Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
6039 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
6040 SELECTION_AUTHTOKENS_BY_ACCOUNT,
6041 new String[]{account.name, account.type},
6042 null, null, null);
6043 try {
6044 while (cursor.moveToNext()) {
6045 final String type = cursor.getString(0);
6046 final String authToken = cursor.getString(1);
6047 authTokensForAccount.put(type, authToken);
6048 }
6049 } finally {
6050 cursor.close();
6051 }
6052 return authTokensForAccount;
6053 }
6054
6055 static int updateAccountPassword(SQLiteDatabase db, long accountId, String password) {
6056 final ContentValues values = new ContentValues();
6057 values.put(ACCOUNTS_PASSWORD, password);
6058 return db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?",
6059 new String[] {String.valueOf(accountId)});
6060 }
6061
6062 static boolean deleteAuthTokensByAccountId(SQLiteDatabase db, long accountId) {
6063 return db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?",
6064 new String[] {String.valueOf(accountId)}) > 0;
6065 }
6066
6067 static long insertSharedAccount(SQLiteDatabase db, Account account) {
6068 ContentValues values = new ContentValues();
6069 values.put(ACCOUNTS_NAME, account.name);
6070 values.put(ACCOUNTS_TYPE, account.type);
6071 return db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
6072 }
6073
6074 static boolean deleteSharedAccount(SQLiteDatabase db, Account account) {
6075 return db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
6076 new String[] {account.name, account.type}) > 0;
6077 }
6078
6079 static int renameSharedAccount(SQLiteDatabase db, Account account, String newName) {
6080 final ContentValues values = new ContentValues();
6081 values.put(ACCOUNTS_NAME, newName);
6082 return db.update(TABLE_SHARED_ACCOUNTS,
6083 values,
6084 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
6085 new String[] { account.name, account.type });
6086 }
6087
6088 static List<Account> getSharedAccounts(SQLiteDatabase db) {
6089 ArrayList<Account> accountList = new ArrayList<>();
6090 Cursor cursor = null;
6091 try {
6092 cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[] {ACCOUNTS_NAME, ACCOUNTS_TYPE},
6093 null, null, null, null, null);
6094 if (cursor != null && cursor.moveToFirst()) {
6095 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
6096 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
6097 do {
6098 accountList.add(new Account(cursor.getString(nameIndex),
6099 cursor.getString(typeIndex)));
6100 } while (cursor.moveToNext());
6101 }
6102 } finally {
6103 if (cursor != null) {
6104 cursor.close();
6105 }
6106 }
6107 return accountList;
6108 }
6109
6110 static long findSharedAccountId(SQLiteDatabase db, Account account) {
6111 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
6112 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
6113 try {
6114 if (cursor.moveToNext()) {
6115 return cursor.getLong(0);
6116 }
6117 return -1;
6118 } finally {
6119 cursor.close();
6120 }
6121 }
6122
6123 static long findAccountId(SQLiteDatabase db, Account account) {
6124 Cursor cursor = db.query(
6125 TABLE_ACCOUNTS, new String[] {ACCOUNTS_ID},
6126 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
6127 try {
6128 if (cursor.moveToNext()) {
6129 return cursor.getLong(0);
6130 }
6131 return -1;
6132 } finally {
6133 cursor.close();
6134 }
6135 }
6136
6137 static long findExtrasIdByAccountId(SQLiteDatabase db, long accountId, String key) {
6138 Cursor cursor = db.query(
6139 CE_TABLE_EXTRAS, new String[] {EXTRAS_ID},
6140 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
6141 new String[]{key}, null, null, null);
6142 try {
6143 if (cursor.moveToNext()) {
6144 return cursor.getLong(0);
6145 }
6146 return -1;
6147 } finally {
6148 cursor.close();
6149 }
6150 }
6151
6152 static boolean updateExtra(SQLiteDatabase db, long extrasId, String value) {
6153 ContentValues values = new ContentValues();
6154 values.put(EXTRAS_VALUE, value);
6155 int rows = db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=?",
6156 new String[]{String.valueOf(extrasId)});
6157 return rows == 1;
6158 }
6159
6160 static long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
6161 ContentValues values = new ContentValues();
6162 values.put(EXTRAS_KEY, key);
6163 values.put(EXTRAS_ACCOUNTS_ID, accountId);
6164 values.put(EXTRAS_VALUE, value);
6165 return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
6166 }
6167
6168 static Map<String, String> findUserExtrasForAccount(SQLiteDatabase db, Account account) {
6169 Map<String, String> userExtrasForAccount = new HashMap<>();
6170 Cursor cursor = db.query(CE_TABLE_EXTRAS,
6171 COLUMNS_EXTRAS_KEY_AND_VALUE,
6172 SELECTION_USERDATA_BY_ACCOUNT,
6173 new String[] {account.name, account.type},
6174 null, null, null);
6175 try {
6176 while (cursor.moveToNext()) {
6177 final String tmpkey = cursor.getString(0);
6178 final String value = cursor.getString(1);
6179 userExtrasForAccount.put(tmpkey, value);
6180 }
6181 } finally {
6182 cursor.close();
6183 }
6184 return userExtrasForAccount;
6185 }
6186
6187 static long insertGrant(SQLiteDatabase db, long accountId, String authTokenType, int uid) {
6188 ContentValues values = new ContentValues();
6189 values.put(GRANTS_ACCOUNTS_ID, accountId);
6190 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
6191 values.put(GRANTS_GRANTEE_UID, uid);
6192 return db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
6193 }
6194
6195 static boolean deleteGrantsByUid(SQLiteDatabase db, int uid) {
6196 return db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
6197 new String[] {Integer.toString(uid)}) > 0;
6198 }
6199
6200 static boolean deleteGrantsByAccountIdAuthTokenTypeAndUid(SQLiteDatabase db, long accountId, String authTokenType, long uid) {
6201 return db.delete(TABLE_GRANTS,
6202 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
6203 + GRANTS_GRANTEE_UID + "=?",
6204 new String[] {String.valueOf(accountId), authTokenType, String.valueOf(uid)}) > 0;
6205 }
6206
6207 static List<Integer> findAllUidGrants(SQLiteDatabase db) {
6208 List<Integer> result = new ArrayList<>();
6209 final Cursor cursor = db.query(TABLE_GRANTS,
6210 new String[] {GRANTS_GRANTEE_UID},
6211 null, null, GRANTS_GRANTEE_UID, null, null);
6212 try {
6213 while (cursor.moveToNext()) {
6214 final int uid = cursor.getInt(0);
6215 result.add(uid);
6216 }
6217 } finally {
6218 cursor.close();
6219 }
6220 return result;
6221 }
6222
6223 static long findMatchingGrantsCount(SQLiteDatabase db,
6224 int uid, String authTokenType, Account account) {
6225 String[] args = { String.valueOf(uid), authTokenType,
6226 account.name, account.type};
6227 return DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args);
6228 }
6229
6230 static long insertMetaAuthTypeAndUid(SQLiteDatabase db, String authenticatorType, int uid) {
6231 ContentValues values = new ContentValues();
6232 values.put(META_KEY,
6233 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + authenticatorType);
6234 values.put(META_VALUE, uid);
6235 return db.insert(TABLE_META, null, values);
6236 }
6237
6238 static long insertOrReplaceMetaAuthTypeAndUid(SQLiteDatabase db, String authenticatorType,
6239 int uid) {
6240 ContentValues values = new ContentValues();
6241 values.put(META_KEY,
6242 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + authenticatorType);
6243 values.put(META_VALUE, uid);
6244 return db.insertWithOnConflict(TABLE_META, null, values,
6245 SQLiteDatabase.CONFLICT_REPLACE);
6246 }
6247
6248
6249 static Map<String, Integer> findMetaAuthUid(SQLiteDatabase db) {
6250 Cursor metaCursor = db.query(
6251 TABLE_META,
6252 new String[] {META_KEY, META_VALUE},
6253 SELECTION_META_BY_AUTHENTICATOR_TYPE,
6254 new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
6255 null /* groupBy */,
6256 null /* having */,
6257 META_KEY);
6258 Map<String, Integer> map = new LinkedHashMap<>();
6259 try {
6260 while (metaCursor.moveToNext()) {
6261 String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
6262 String uidStr = metaCursor.getString(1);
6263 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uidStr)) {
6264 // Should never happen.
6265 Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
6266 + ", uid empty: " + TextUtils.isEmpty(uidStr));
6267 continue;
6268 }
6269 int uid = Integer.parseInt(metaCursor.getString(1));
6270 map.put(type, uid);
6271 }
6272 } finally {
6273 metaCursor.close();
6274 }
6275 return map;
6276 }
6277
6278 static boolean deleteMetaByAuthTypeAndUid(SQLiteDatabase db, String type, int uid) {
6279 return db.delete(
6280 TABLE_META,
6281 META_KEY + "=? AND " + META_VALUE + "=?",
6282 new String[] {
6283 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
6284 String.valueOf(uid)}
6285 ) > 0;
6286 }
6287
6288 static void dumpAccountsTable(SQLiteDatabase db, PrintWriter pw) {
6289 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
6290 null, null, ACCOUNTS_TYPE, null, null);
6291 try {
6292 while (cursor.moveToNext()) {
6293 // print type,count
6294 pw.println(cursor.getString(0) + "," + cursor.getString(1));
6295 }
6296 } finally {
6297 if (cursor != null) {
6298 cursor.close();
6299 }
6300 }
6301 }
6302
6303 static void dumpDebugTable(SQLiteDatabase db, PrintWriter pw) {
6304 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
6305 null, null, null, null, DebugDbHelper.TIMESTAMP);
6306 pw.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
6307 pw.println("Accounts History");
6308 try {
6309 while (cursor.moveToNext()) {
6310 // print type,count
6311 pw.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
6312 cursor.getString(2) + "," + cursor.getString(3) + ","
6313 + cursor.getString(4) + "," + cursor.getString(5));
6314 }
6315 } finally {
6316 cursor.close();
6317 }
6318 }
6319
6320 }
Fred Quintana60307342009-03-24 22:48:12 -07006321}