blob: 384e6c9f6024ede60d5f9f02d3d770ae6b6d2a3d [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;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080032import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070033import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070034import android.app.AppGlobals;
Svetoslavce852dd2015-09-08 14:36:35 -070035import android.app.AppOpsManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010039import android.app.admin.DevicePolicyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070040import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070041import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070042import android.content.ContentValues;
43import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070046import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070047import android.content.pm.ApplicationInfo;
48import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070049import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070050import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070051import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070052import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070053import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070054import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070055import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070056import android.database.Cursor;
57import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070058import android.database.sqlite.SQLiteDatabase;
59import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070060import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070061import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080063import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070064import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import android.os.IBinder;
66import android.os.Looper;
67import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070068import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070069import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.os.RemoteException;
71import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070072import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070073import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070074import android.text.TextUtils;
75import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070076import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070077import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080078import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070079
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070080import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080081import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080082import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070083import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070084import com.google.android.collect.Lists;
85import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070086
Oscar Montemayora8529f62009-11-18 10:14:20 -080087import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070088import java.io.FileDescriptor;
89import java.io.PrintWriter;
Carlos Valdivia91979be2015-05-22 14:11:35 -070090import java.security.MessageDigest;
91import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070092import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -070093import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080094import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070095import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070096import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070097import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070098import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080099import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700100import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800101import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700102import java.util.concurrent.atomic.AtomicInteger;
103import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700104
Fred Quintana60307342009-03-24 22:48:12 -0700105/**
106 * A system service that provides account, password, and authtoken management for all
107 * accounts on the device. Some of these calls are implemented with the help of the corresponding
108 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
109 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700110 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700111 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700112 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700113public class AccountManagerService
114 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800115 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700116 private static final String TAG = "AccountManagerService";
117
Fred Quintana60307342009-03-24 22:48:12 -0700118 private static final String DATABASE_NAME = "accounts.db";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700119 private static final int DATABASE_VERSION = 8;
120
121 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700122
123 private final Context mContext;
124
Fred Quintana56285a62010-12-02 14:20:51 -0800125 private final PackageManager mPackageManager;
Svetoslavce852dd2015-09-08 14:36:35 -0700126 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700127 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800128
Fred Quintana60307342009-03-24 22:48:12 -0700129 private final MessageHandler mMessageHandler;
130
131 // Messages that can be sent on mHandler
132 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700133 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700134
Fred Quintana56285a62010-12-02 14:20:51 -0800135 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700136
137 private static final String TABLE_ACCOUNTS = "accounts";
138 private static final String ACCOUNTS_ID = "_id";
139 private static final String ACCOUNTS_NAME = "name";
140 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700141 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700142 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700143 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800144 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
145 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700146
147 private static final String TABLE_AUTHTOKENS = "authtokens";
148 private static final String AUTHTOKENS_ID = "_id";
149 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
150 private static final String AUTHTOKENS_TYPE = "type";
151 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
152
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700153 private static final String TABLE_GRANTS = "grants";
154 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
155 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
156 private static final String GRANTS_GRANTEE_UID = "uid";
157
Fred Quintana60307342009-03-24 22:48:12 -0700158 private static final String TABLE_EXTRAS = "extras";
159 private static final String EXTRAS_ID = "_id";
160 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
161 private static final String EXTRAS_KEY = "key";
162 private static final String EXTRAS_VALUE = "value";
163
164 private static final String TABLE_META = "meta";
165 private static final String META_KEY = "key";
166 private static final String META_VALUE = "value";
167
Amith Yamasani67df64b2012-12-14 12:09:36 -0800168 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
169
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700170 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
171 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700172 private static final Intent ACCOUNTS_CHANGED_INTENT;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700173 static {
174 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
175 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
176 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700177
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700178 private static final String COUNT_OF_MATCHING_GRANTS = ""
179 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
180 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
181 + " AND " + GRANTS_GRANTEE_UID + "=?"
182 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
183 + " AND " + ACCOUNTS_NAME + "=?"
184 + " AND " + ACCOUNTS_TYPE + "=?";
185
Fred Quintana56285a62010-12-02 14:20:51 -0800186 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
187 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700188
Fred Quintana56285a62010-12-02 14:20:51 -0800189 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
190 AUTHTOKENS_AUTHTOKEN};
191
192 private static final String SELECTION_USERDATA_BY_ACCOUNT =
193 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
194 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
195
Fred Quintanaa698f422009-04-08 19:14:54 -0700196 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700197 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
198
Amith Yamasani04e0d262012-02-14 11:50:53 -0800199 static class UserAccounts {
200 private final int userId;
201 private final DatabaseHelper openHelper;
202 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
203 credentialsPermissionNotificationIds =
204 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
205 private final HashMap<Account, Integer> signinRequiredNotificationIds =
206 new HashMap<Account, Integer>();
207 private final Object cacheLock = new Object();
208 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700209 private final HashMap<String, Account[]> accountCache =
210 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800211 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800212 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800213 new HashMap<Account, HashMap<String, String>>();
214 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800215 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800216 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700217
218 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700219 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700220
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700221 /**
222 * protected by the {@link #cacheLock}
223 *
224 * Caches the previous names associated with an account. Previous names
225 * should be cached because we expect that when an Account is renamed,
226 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
227 * want to know if the accounts they care about have been renamed.
228 *
229 * The previous names are wrapped in an {@link AtomicReference} so that
230 * we can distinguish between those accounts with no previous names and
231 * those whose previous names haven't been cached (yet).
232 */
233 private final HashMap<Account, AtomicReference<String>> previousNameCache =
234 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800235
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700236 private int debugDbInsertionPoint = -1;
237 private SQLiteStatement statementForLogging;
238
Amith Yamasani04e0d262012-02-14 11:50:53 -0800239 UserAccounts(Context context, int userId) {
240 this.userId = userId;
241 synchronized (cacheLock) {
242 openHelper = new DatabaseHelper(context, userId);
243 }
244 }
245 }
246
247 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
248
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700249 private static AtomicReference<AccountManagerService> sThis =
250 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700251 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700252
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700253 /**
254 * This should only be called by system code. One should only call this after the service
255 * has started.
256 * @return a reference to the AccountManagerService instance
257 * @hide
258 */
259 public static AccountManagerService getSingleton() {
260 return sThis.get();
261 }
Fred Quintana60307342009-03-24 22:48:12 -0700262
Fred Quintana56285a62010-12-02 14:20:51 -0800263 public AccountManagerService(Context context) {
264 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700265 }
266
Fred Quintana56285a62010-12-02 14:20:51 -0800267 public AccountManagerService(Context context, PackageManager packageManager,
268 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700269 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800270 mPackageManager = packageManager;
Svetoslavce852dd2015-09-08 14:36:35 -0700271 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700272
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700273 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700274
Fred Quintana56285a62010-12-02 14:20:51 -0800275 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800276 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700277
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700278 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800279
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800280 IntentFilter intentFilter = new IntentFilter();
281 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
282 intentFilter.addDataScheme("package");
283 mContext.registerReceiver(new BroadcastReceiver() {
284 @Override
285 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700286 // Don't delete accounts when updating a authenticator's
287 // package.
288 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700289 /* Purging data requires file io, don't block the main thread. This is probably
290 * less than ideal because we are introducing a race condition where old grants
291 * could be exercised until they are purged. But that race condition existed
292 * anyway with the broadcast receiver.
293 *
294 * Ideally, we would completely clear the cache, purge data from the database,
295 * and then rebuild the cache. All under the cache lock. But that change is too
296 * large at this point.
297 */
298 Runnable r = new Runnable() {
299 @Override
300 public void run() {
301 purgeOldGrantsAll();
302 }
303 };
304 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700305 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800306 }
307 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800308
Amith Yamasani13593602012-03-22 16:16:17 -0700309 IntentFilter userFilter = new IntentFilter();
310 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800311 userFilter.addAction(Intent.ACTION_USER_STARTED);
312 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700313 @Override
314 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800315 String action = intent.getAction();
316 if (Intent.ACTION_USER_REMOVED.equals(action)) {
317 onUserRemoved(intent);
318 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
319 onUserStarted(intent);
320 }
Amith Yamasani13593602012-03-22 16:16:17 -0700321 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800322 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800323 }
324
Dianne Hackborn164371f2013-10-01 19:10:13 -0700325 @Override
326 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
327 throws RemoteException {
328 try {
329 return super.onTransact(code, data, reply, flags);
330 } catch (RuntimeException e) {
331 // The account manager only throws security exceptions, so let's
332 // log all others.
333 if (!(e instanceof SecurityException)) {
334 Slog.wtf(TAG, "Account Manager Crash", e);
335 }
336 throw e;
337 }
338 }
339
Kenny Root26ff6622012-07-30 12:58:03 -0700340 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700341 }
342
Amith Yamasani258848d2012-08-10 17:06:33 -0700343 private UserManager getUserManager() {
344 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700345 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700346 }
347 return mUserManager;
348 }
349
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700350 /**
351 * Validate internal set of accounts against installed authenticators for
352 * given user. Clears cached authenticators before validating.
353 */
354 public void validateAccounts(int userId) {
355 final UserAccounts accounts = getUserAccounts(userId);
356
357 // Invalidate user-specific cache to make sure we catch any
358 // removed authenticators.
359 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
360 }
361
362 /**
363 * Validate internal set of accounts against installed authenticators for
364 * given user. Clear cached authenticators before validating when requested.
365 */
366 private void validateAccountsInternal(
367 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
368 if (invalidateAuthenticatorCache) {
369 mAuthenticatorCache.invalidateCache(accounts.userId);
370 }
371
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700372 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
373 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
374 mAuthenticatorCache.getAllServices(accounts.userId)) {
375 knownAuth.add(service.type);
376 }
377
Amith Yamasani04e0d262012-02-14 11:50:53 -0800378 synchronized (accounts.cacheLock) {
379 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800380 boolean accountDeleted = false;
381 Cursor cursor = db.query(TABLE_ACCOUNTS,
382 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800383 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800384 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800385 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800386 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700387 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800388 while (cursor.moveToNext()) {
389 final long accountId = cursor.getLong(0);
390 final String accountType = cursor.getString(1);
391 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700392
393 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700394 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800395 + accountType + " no longer has a registered authenticator");
396 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
397 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700398
399 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
400 accountId, accounts);
401
Fred Quintana56285a62010-12-02 14:20:51 -0800402 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800403 accounts.userDataCache.remove(account);
404 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700405 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800406 } else {
407 ArrayList<String> accountNames = accountNamesByType.get(accountType);
408 if (accountNames == null) {
409 accountNames = new ArrayList<String>();
410 accountNamesByType.put(accountType, accountNames);
411 }
412 accountNames.add(accountName);
413 }
414 }
Andy McFadden2f362292012-01-20 14:43:38 -0800415 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800416 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800417 final String accountType = cur.getKey();
418 final ArrayList<String> accountNames = cur.getValue();
419 final Account[] accountsForType = new Account[accountNames.size()];
420 int i = 0;
421 for (String accountName : accountNames) {
422 accountsForType[i] = new Account(accountName, accountType);
423 ++i;
424 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800425 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800426 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800427 } finally {
428 cursor.close();
429 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800430 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800431 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800432 }
433 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700434 }
435
Amith Yamasani04e0d262012-02-14 11:50:53 -0800436 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700437 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800438 }
439
440 protected UserAccounts getUserAccounts(int userId) {
441 synchronized (mUsers) {
442 UserAccounts accounts = mUsers.get(userId);
443 if (accounts == null) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700444 accounts = new UserAccounts(mContext, userId);
445 initializeDebugDbSizeAndCompileSqlStatementForLogging(
446 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800447 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700448 purgeOldGrants(accounts);
449 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800450 }
451 return accounts;
452 }
453 }
454
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700455 private void purgeOldGrantsAll() {
456 synchronized (mUsers) {
457 for (int i = 0; i < mUsers.size(); i++) {
458 purgeOldGrants(mUsers.valueAt(i));
459 }
460 }
461 }
462
463 private void purgeOldGrants(UserAccounts accounts) {
464 synchronized (accounts.cacheLock) {
465 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
466 final Cursor cursor = db.query(TABLE_GRANTS,
467 new String[]{GRANTS_GRANTEE_UID},
468 null, null, GRANTS_GRANTEE_UID, null, null);
469 try {
470 while (cursor.moveToNext()) {
471 final int uid = cursor.getInt(0);
472 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
473 if (packageExists) {
474 continue;
475 }
476 Log.d(TAG, "deleting grants for UID " + uid
477 + " because its package is no longer installed");
478 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
479 new String[]{Integer.toString(uid)});
480 }
481 } finally {
482 cursor.close();
483 }
484 }
485 }
486
Amith Yamasani13593602012-03-22 16:16:17 -0700487 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700488 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700489 if (userId < 1) return;
490
491 UserAccounts accounts;
492 synchronized (mUsers) {
493 accounts = mUsers.get(userId);
494 mUsers.remove(userId);
495 }
496 if (accounts == null) {
497 File dbFile = new File(getDatabaseName(userId));
498 dbFile.delete();
499 return;
500 }
501
502 synchronized (accounts.cacheLock) {
503 accounts.openHelper.close();
504 File dbFile = new File(getDatabaseName(userId));
505 dbFile.delete();
506 }
507 }
508
Amith Yamasani67df64b2012-12-14 12:09:36 -0800509 private void onUserStarted(Intent intent) {
510 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
511 if (userId < 1) return;
512
513 // Check if there's a shared account that needs to be created as an account
514 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
515 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavce852dd2015-09-08 14:36:35 -0700516 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Amith Yamasani67df64b2012-12-14 12:09:36 -0800517 for (Account sa : sharedAccounts) {
518 if (ArrayUtils.contains(accounts, sa)) continue;
519 // Account doesn't exist. Copy it now.
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000520 copyAccountToUser(null /*no response*/, sa, UserHandle.USER_OWNER, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800521 }
522 }
523
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700524 @Override
525 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700526 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700527 }
528
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800529 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700530 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700531 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800532 if (Log.isLoggable(TAG, Log.VERBOSE)) {
533 Log.v(TAG, "getPassword: " + account
534 + ", caller's uid " + Binder.getCallingUid()
535 + ", pid " + Binder.getCallingPid());
536 }
Fred Quintana382601f2010-03-25 12:25:10 -0700537 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000538 int userId = UserHandle.getCallingUserId();
539 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700540 String msg = String.format(
541 "uid %s cannot get secrets for accounts of type: %s",
542 callingUid,
543 account.type);
544 throw new SecurityException(msg);
545 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700546 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700547 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700548 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800549 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700550 } finally {
551 restoreCallingIdentity(identityToken);
552 }
553 }
554
Amith Yamasani04e0d262012-02-14 11:50:53 -0800555 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700556 if (account == null) {
557 return null;
558 }
559
Amith Yamasani04e0d262012-02-14 11:50:53 -0800560 synchronized (accounts.cacheLock) {
561 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800562 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
563 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
564 new String[]{account.name, account.type}, null, null, null);
565 try {
566 if (cursor.moveToNext()) {
567 return cursor.getString(0);
568 }
569 return null;
570 } finally {
571 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700572 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700573 }
574 }
575
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800576 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700577 public String getPreviousName(Account account) {
578 if (Log.isLoggable(TAG, Log.VERBOSE)) {
579 Log.v(TAG, "getPreviousName: " + account
580 + ", caller's uid " + Binder.getCallingUid()
581 + ", pid " + Binder.getCallingPid());
582 }
583 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700584 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700585 long identityToken = clearCallingIdentity();
586 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700587 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700588 return readPreviousNameInternal(accounts, account);
589 } finally {
590 restoreCallingIdentity(identityToken);
591 }
592 }
593
594 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
595 if (account == null) {
596 return null;
597 }
598 synchronized (accounts.cacheLock) {
599 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
600 if (previousNameRef == null) {
601 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
602 Cursor cursor = db.query(
603 TABLE_ACCOUNTS,
604 new String[]{ ACCOUNTS_PREVIOUS_NAME },
605 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
606 new String[] { account.name, account.type },
607 null,
608 null,
609 null);
610 try {
611 if (cursor.moveToNext()) {
612 String previousName = cursor.getString(0);
613 previousNameRef = new AtomicReference<String>(previousName);
614 accounts.previousNameCache.put(account, previousNameRef);
615 return previousName;
616 } else {
617 return null;
618 }
619 } finally {
620 cursor.close();
621 }
622 } else {
623 return previousNameRef.get();
624 }
625 }
626 }
627
628 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700629 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700630 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800631 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700632 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
633 account, key, callingUid, Binder.getCallingPid());
634 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800635 }
Fred Quintana382601f2010-03-25 12:25:10 -0700636 if (account == null) throw new IllegalArgumentException("account is null");
637 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000638 int userId = UserHandle.getCallingUserId();
639 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700640 String msg = String.format(
641 "uid %s cannot get user data for accounts of type: %s",
642 callingUid,
643 account.type);
644 throw new SecurityException(msg);
645 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700646 long identityToken = clearCallingIdentity();
647 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700648 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800649 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700650 } finally {
651 restoreCallingIdentity(identityToken);
652 }
653 }
654
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800655 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100656 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700657 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800658 if (Log.isLoggable(TAG, Log.VERBOSE)) {
659 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100660 + "for user id " + userId
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700661 + "caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800662 + ", pid " + Binder.getCallingPid());
663 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100664 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700665 if (isCrossUser(callingUid, userId)) {
666 throw new SecurityException(
667 String.format(
668 "User %s tying to get authenticator types for %s" ,
669 UserHandle.getCallingUserId(),
670 userId));
671 }
672
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700673 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700674 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000675 return getAuthenticatorTypesInternal(userId);
676
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700677 } finally {
678 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700679 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700680 }
681
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000682 /**
683 * Should only be called inside of a clearCallingIdentity block.
684 */
685 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
686 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
687 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
688 AuthenticatorDescription[] types =
689 new AuthenticatorDescription[authenticatorCollection.size()];
690 int i = 0;
691 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
692 : authenticatorCollection) {
693 types[i] = authenticator.type;
694 i++;
695 }
696 return types;
697 }
698
699
700
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700701 private boolean isCrossUser(int callingUid, int userId) {
702 return (userId != UserHandle.getCallingUserId()
703 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100704 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700705 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
706 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100707 }
708
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700709 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700710 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700711 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800712 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700713 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700714 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800715 + ", pid " + Binder.getCallingPid());
716 }
Fred Quintana382601f2010-03-25 12:25:10 -0700717 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000718 int userId = UserHandle.getCallingUserId();
719 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700720 String msg = String.format(
721 "uid %s cannot explicitly add accounts of type: %s",
722 callingUid,
723 account.type);
724 throw new SecurityException(msg);
725 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700726 /*
727 * Child users are not allowed to add accounts. Only the accounts that are
728 * shared by the parent profile can be added to child profile.
729 *
730 * TODO: Only allow accounts that were shared to be added by
731 * a limited user.
732 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700733
Fred Quintana60307342009-03-24 22:48:12 -0700734 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700735 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700736 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700737 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000738 return addAccountInternal(accounts, account, password, extras, false, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700739 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700740 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700741 }
742 }
743
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000744 @Override
745 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
746 int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700747 int callingUid = Binder.getCallingUid();
748 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
749 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000750 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700751 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800752 final UserAccounts fromAccounts = getUserAccounts(userFrom);
753 final UserAccounts toAccounts = getUserAccounts(userTo);
754 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000755 if (response != null) {
756 Bundle result = new Bundle();
757 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
758 try {
759 response.onResult(result);
760 } catch (RemoteException e) {
761 Slog.w(TAG, "Failed to report error back to the client." + e);
762 }
763 }
764 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800765 }
766
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000767 Slog.d(TAG, "Copying account " + account.name
768 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800769 long identityToken = clearCallingIdentity();
770 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000771 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800772 false /* stripAuthTokenFromResult */, account.name,
773 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700774 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800775 protected String toDebugString(long now) {
776 return super.toDebugString(now) + ", getAccountCredentialsForClone"
777 + ", " + account.type;
778 }
779
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700780 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800781 public void run() throws RemoteException {
782 mAuthenticator.getAccountCredentialsForCloning(this, account);
783 }
784
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700785 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800786 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000787 if (result != null
788 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
789 // Create a Session for the target user and pass in the bundle
790 completeCloningAccount(response, result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800791 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800792 super.onResult(result);
793 }
794 }
795 }.bind();
796 } finally {
797 restoreCallingIdentity(identityToken);
798 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800799 }
800
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800801 @Override
802 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700803 final int callingUid = Binder.getCallingUid();
804 if (Log.isLoggable(TAG, Log.VERBOSE)) {
805 String msg = String.format(
806 "accountAuthenticated( account: %s, callerUid: %s)",
807 account,
808 callingUid);
809 Log.v(TAG, msg);
810 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800811 if (account == null) {
812 throw new IllegalArgumentException("account is null");
813 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000814 int userId = UserHandle.getCallingUserId();
815 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700816 String msg = String.format(
817 "uid %s cannot notify authentication for accounts of type: %s",
818 callingUid,
819 account.type);
820 throw new SecurityException(msg);
821 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000822
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800823 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
824 return false;
825 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000826
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700827 long identityToken = clearCallingIdentity();
828 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000829 UserAccounts accounts = getUserAccounts(userId);
830 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700831 } finally {
832 restoreCallingIdentity(identityToken);
833 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -0700834 }
835
836 private boolean updateLastAuthenticatedTime(Account account) {
837 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800838 synchronized (accounts.cacheLock) {
839 final ContentValues values = new ContentValues();
840 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
841 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
842 int i = db.update(
843 TABLE_ACCOUNTS,
844 values,
845 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
846 new String[] {
847 account.name, account.type
848 });
849 if (i > 0) {
850 return true;
851 }
852 }
853 return false;
854 }
855
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000856 private void completeCloningAccount(IAccountManagerResponse response,
857 final Bundle accountCredentials, final Account account, final UserAccounts targetUser) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800858 long id = clearCallingIdentity();
859 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000860 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800861 false /* stripAuthTokenFromResult */, account.name,
862 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700863 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800864 protected String toDebugString(long now) {
865 return super.toDebugString(now) + ", getAccountCredentialsForClone"
866 + ", " + account.type;
867 }
868
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700869 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800870 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700871 // Confirm that the owner's account still exists before this step.
872 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
873 synchronized (owner.cacheLock) {
Svetoslavce852dd2015-09-08 14:36:35 -0700874 for (Account acc : getAccounts(UserHandle.USER_OWNER,
875 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700876 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000877 mAuthenticator.addAccountFromCredentials(
878 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700879 break;
880 }
881 }
882 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800883 }
884
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700885 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800886 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000887 // TODO: Anything to do if if succedded?
888 // TODO: If it failed: Show error notification? Should we remove the shadow
889 // account to avoid retries?
890 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800891 }
892
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700893 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800894 public void onError(int errorCode, String errorMessage) {
895 super.onError(errorCode, errorMessage);
896 // TODO: Show error notification to user
897 // TODO: Should we remove the shadow account so that it doesn't keep trying?
898 }
899
900 }.bind();
901 } finally {
902 restoreCallingIdentity(id);
903 }
904 }
905
Amith Yamasani04e0d262012-02-14 11:50:53 -0800906 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700907 Bundle extras, boolean restricted, int callingUid) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700908 if (account == null) {
909 return false;
910 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800911 synchronized (accounts.cacheLock) {
912 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800913 db.beginTransaction();
914 try {
915 long numMatches = DatabaseUtils.longForQuery(db,
916 "select count(*) from " + TABLE_ACCOUNTS
917 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
918 new String[]{account.name, account.type});
919 if (numMatches > 0) {
920 Log.w(TAG, "insertAccountIntoDatabase: " + account
921 + ", skipping since the account already exists");
922 return false;
923 }
924 ContentValues values = new ContentValues();
925 values.put(ACCOUNTS_NAME, account.name);
926 values.put(ACCOUNTS_TYPE, account.type);
927 values.put(ACCOUNTS_PASSWORD, password);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800928 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800929 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
930 if (accountId < 0) {
931 Log.w(TAG, "insertAccountIntoDatabase: " + account
932 + ", skipping the DB insert failed");
933 return false;
934 }
935 if (extras != null) {
936 for (String key : extras.keySet()) {
937 final String value = extras.getString(key);
938 if (insertExtraLocked(db, accountId, key, value) < 0) {
939 Log.w(TAG, "insertAccountIntoDatabase: " + account
940 + ", skipping since insertExtra failed for key " + key);
941 return false;
942 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700943 }
944 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800945 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700946
947 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
948 accounts, callingUid);
949
Amith Yamasani04e0d262012-02-14 11:50:53 -0800950 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800951 } finally {
952 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700953 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800954 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700955 }
956 if (accounts.userId == UserHandle.USER_OWNER) {
957 addAccountToLimitedUsers(account);
958 }
959 return true;
960 }
961
962 /**
963 * Adds the account to all limited users as shared accounts. If the user is currently
964 * running, then clone the account too.
965 * @param account the account to share with limited users
966 */
967 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700968 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700969 for (UserInfo user : users) {
970 if (user.isRestricted()) {
971 addSharedAccountAsUser(account, user.id);
972 try {
973 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
974 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
975 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
976 account));
977 }
978 } catch (RemoteException re) {
979 // Shouldn't happen
980 }
981 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700982 }
983 }
984
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800985 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700986 ContentValues values = new ContentValues();
987 values.put(EXTRAS_KEY, key);
988 values.put(EXTRAS_ACCOUNTS_ID, accountId);
989 values.put(EXTRAS_VALUE, value);
990 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
991 }
992
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800993 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -0800994 public void hasFeatures(IAccountManagerResponse response,
Svetoslavce852dd2015-09-08 14:36:35 -0700995 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700996 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800997 if (Log.isLoggable(TAG, Log.VERBOSE)) {
998 Log.v(TAG, "hasFeatures: " + account
999 + ", response " + response
1000 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001001 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001002 + ", pid " + Binder.getCallingPid());
1003 }
Fred Quintana382601f2010-03-25 12:25:10 -07001004 if (response == null) throw new IllegalArgumentException("response is null");
1005 if (account == null) throw new IllegalArgumentException("account is null");
1006 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001007 int userId = UserHandle.getCallingUserId();
Svetoslavce852dd2015-09-08 14:36:35 -07001008 checkReadAccountsPermitted(callingUid, account.type, userId,
1009 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001010
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001011 long identityToken = clearCallingIdentity();
1012 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001013 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001014 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001015 } finally {
1016 restoreCallingIdentity(identityToken);
1017 }
1018 }
1019
1020 private class TestFeaturesSession extends Session {
1021 private final String[] mFeatures;
1022 private final Account mAccount;
1023
Amith Yamasani04e0d262012-02-14 11:50:53 -08001024 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001025 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001026 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001027 true /* stripAuthTokenFromResult */, account.name,
1028 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001029 mFeatures = features;
1030 mAccount = account;
1031 }
1032
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001033 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001034 public void run() throws RemoteException {
1035 try {
1036 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1037 } catch (RemoteException e) {
1038 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1039 }
1040 }
1041
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001042 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001043 public void onResult(Bundle result) {
1044 IAccountManagerResponse response = getResponseAndClose();
1045 if (response != null) {
1046 try {
1047 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001048 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001049 return;
1050 }
Fred Quintana56285a62010-12-02 14:20:51 -08001051 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1052 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1053 + response);
1054 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001055 final Bundle newResult = new Bundle();
1056 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1057 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1058 response.onResult(newResult);
1059 } catch (RemoteException e) {
1060 // if the caller is dead then there is no one to care about remote exceptions
1061 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1062 Log.v(TAG, "failure while notifying response", e);
1063 }
1064 }
1065 }
1066 }
1067
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001068 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001069 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001070 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001071 + ", " + mAccount
1072 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1073 }
1074 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001075
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001076 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001077 public void renameAccount(
1078 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001079 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001080 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1081 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001082 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001083 + ", pid " + Binder.getCallingPid());
1084 }
1085 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001086 int userId = UserHandle.getCallingUserId();
1087 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001088 String msg = String.format(
1089 "uid %s cannot rename accounts of type: %s",
1090 callingUid,
1091 accountToRename.type);
1092 throw new SecurityException(msg);
1093 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001094 long identityToken = clearCallingIdentity();
1095 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001096 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001097 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001098 Bundle result = new Bundle();
1099 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1100 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1101 try {
1102 response.onResult(result);
1103 } catch (RemoteException e) {
1104 Log.w(TAG, e.getMessage());
1105 }
1106 } finally {
1107 restoreCallingIdentity(identityToken);
1108 }
1109 }
1110
1111 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001112 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001113 Account resultAccount = null;
1114 /*
1115 * Cancel existing notifications. Let authenticators
1116 * re-post notifications as required. But we don't know if
1117 * the authenticators have bound their notifications to
1118 * now stale account name data.
1119 *
1120 * With a rename api, we might not need to do this anymore but it
1121 * shouldn't hurt.
1122 */
1123 cancelNotification(
1124 getSigninRequiredNotificationId(accounts, accountToRename),
1125 new UserHandle(accounts.userId));
1126 synchronized(accounts.credentialsPermissionNotificationIds) {
1127 for (Pair<Pair<Account, String>, Integer> pair:
1128 accounts.credentialsPermissionNotificationIds.keySet()) {
1129 if (accountToRename.equals(pair.first.first)) {
1130 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1131 cancelNotification(id, new UserHandle(accounts.userId));
1132 }
1133 }
1134 }
1135 synchronized (accounts.cacheLock) {
1136 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1137 db.beginTransaction();
1138 boolean isSuccessful = false;
1139 Account renamedAccount = new Account(newName, accountToRename.type);
1140 try {
1141 final ContentValues values = new ContentValues();
1142 values.put(ACCOUNTS_NAME, newName);
1143 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
1144 final long accountId = getAccountIdLocked(db, accountToRename);
1145 if (accountId >= 0) {
1146 final String[] argsAccountId = { String.valueOf(accountId) };
1147 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1148 db.setTransactionSuccessful();
1149 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001150 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1151 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001152 }
1153 } finally {
1154 db.endTransaction();
1155 if (isSuccessful) {
1156 /*
1157 * Database transaction was successful. Clean up cached
1158 * data associated with the account in the user profile.
1159 */
1160 insertAccountIntoCacheLocked(accounts, renamedAccount);
1161 /*
1162 * Extract the data and token caches before removing the
1163 * old account to preserve the user data associated with
1164 * the account.
1165 */
1166 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1167 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1168 removeAccountFromCacheLocked(accounts, accountToRename);
1169 /*
1170 * Update the cached data associated with the renamed
1171 * account.
1172 */
1173 accounts.userDataCache.put(renamedAccount, tmpData);
1174 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1175 accounts.previousNameCache.put(
1176 renamedAccount,
1177 new AtomicReference<String>(accountToRename.name));
1178 resultAccount = renamedAccount;
1179
1180 if (accounts.userId == UserHandle.USER_OWNER) {
1181 /*
1182 * Owner's account was renamed, rename the account for
1183 * those users with which the account was shared.
1184 */
1185 List<UserInfo> users = mUserManager.getUsers(true);
1186 for (UserInfo user : users) {
1187 if (!user.isPrimary() && user.isRestricted()) {
1188 renameSharedAccountAsUser(accountToRename, newName, user.id);
1189 }
1190 }
1191 }
1192 sendAccountsChangedBroadcast(accounts.userId);
1193 }
1194 }
1195 }
1196 return resultAccount;
1197 }
1198
1199 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001200 public void removeAccount(IAccountManagerResponse response, Account account,
1201 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001202 removeAccountAsUser(
1203 response,
1204 account,
1205 expectActivityLaunch,
1206 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001207 }
1208
1209 @Override
1210 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001211 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001212 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001213 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1214 Log.v(TAG, "removeAccount: " + account
1215 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001216 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001217 + ", pid " + Binder.getCallingPid()
1218 + ", for user id " + userId);
1219 }
1220 if (response == null) throw new IllegalArgumentException("response is null");
1221 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001222 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001223 if (isCrossUser(callingUid, userId)) {
1224 throw new SecurityException(
1225 String.format(
1226 "User %s tying remove account for %s" ,
1227 UserHandle.getCallingUserId(),
1228 userId));
1229 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001230 /*
1231 * Only the system or authenticator should be allowed to remove accounts for that
1232 * authenticator. This will let users remove accounts (via Settings in the system) but not
1233 * arbitrary applications (like competing authenticators).
1234 */
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001235 UserHandle user = new UserHandle(userId);
1236 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1237 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001238 String msg = String.format(
1239 "uid %s cannot remove accounts of type: %s",
1240 callingUid,
1241 account.type);
1242 throw new SecurityException(msg);
1243 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001244 if (!canUserModifyAccounts(userId)) {
1245 try {
1246 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1247 "User cannot modify accounts");
1248 } catch (RemoteException re) {
1249 }
1250 return;
1251 }
1252 if (!canUserModifyAccountsForType(userId, account.type)) {
1253 try {
1254 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1255 "User cannot modify accounts of this type (policy).");
1256 } catch (RemoteException re) {
1257 }
1258 return;
1259 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001260 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001261 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001262 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001263 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001264 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001265 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001266 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001267 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001268 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001269 }
1270 }
1271 }
1272
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001273 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1274
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001275 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001276 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1277 } finally {
1278 restoreCallingIdentity(identityToken);
1279 }
1280 }
1281
1282 @Override
1283 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001284 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001285 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1286 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001287 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001288 + ", pid " + Binder.getCallingPid());
1289 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001290 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001291 if (account == null) {
1292 /*
1293 * Null accounts should result in returning false, as per
1294 * AccountManage.addAccountExplicitly(...) java doc.
1295 */
1296 Log.e(TAG, "account is null");
1297 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001298 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001299 String msg = String.format(
1300 "uid %s cannot explicitly add accounts of type: %s",
1301 callingUid,
1302 account.type);
1303 throw new SecurityException(msg);
1304 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001305 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001306 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
1307 return false;
1308 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001309 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001310 long identityToken = clearCallingIdentity();
1311 try {
1312 return removeAccountInternal(accounts, account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001313 } finally {
1314 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001315 }
Fred Quintana60307342009-03-24 22:48:12 -07001316 }
1317
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001318 private class RemoveAccountSession extends Session {
1319 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001320 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001321 Account account, boolean expectActivityLaunch) {
1322 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001323 true /* stripAuthTokenFromResult */, account.name,
1324 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001325 mAccount = account;
1326 }
1327
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001328 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001329 protected String toDebugString(long now) {
1330 return super.toDebugString(now) + ", removeAccount"
1331 + ", account " + mAccount;
1332 }
1333
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001334 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001335 public void run() throws RemoteException {
1336 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1337 }
1338
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001339 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001340 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001341 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1342 && !result.containsKey(AccountManager.KEY_INTENT)) {
1343 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001344 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001345 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001346 }
1347 IAccountManagerResponse response = getResponseAndClose();
1348 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001349 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1350 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1351 + response);
1352 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001353 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001354 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001355 try {
1356 response.onResult(result2);
1357 } catch (RemoteException e) {
1358 // ignore
1359 }
1360 }
1361 }
1362 super.onResult(result);
1363 }
1364 }
1365
Amith Yamasani04e0d262012-02-14 11:50:53 -08001366 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001367 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001368 removeAccountInternal(getUserAccountsForCaller(), account);
1369 }
1370
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001371 private boolean removeAccountInternal(UserAccounts accounts, Account account) {
1372 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001373 synchronized (accounts.cacheLock) {
1374 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001375 final long accountId = getAccountIdLocked(db, account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001376 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1377 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001378 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001379 removeAccountFromCacheLocked(accounts, account);
1380 sendAccountsChangedBroadcast(accounts.userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001381
1382 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001383 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001384 if (accounts.userId == UserHandle.USER_OWNER) {
1385 // Owner's account was removed, remove from any users that are sharing
1386 // this account.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001387 int callingUid = getCallingUid();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001388 long id = Binder.clearCallingIdentity();
1389 try {
1390 List<UserInfo> users = mUserManager.getUsers(true);
1391 for (UserInfo user : users) {
1392 if (!user.isPrimary() && user.isRestricted()) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001393 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001394 }
1395 }
1396 } finally {
1397 Binder.restoreCallingIdentity(id);
1398 }
1399 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001400 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001401 }
1402
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001403 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001404 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001405 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001406 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1407 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001408 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001409 + ", pid " + Binder.getCallingPid());
1410 }
Fred Quintana382601f2010-03-25 12:25:10 -07001411 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1412 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001413 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001414 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001415 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001416 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001417 synchronized (accounts.cacheLock) {
1418 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001419 db.beginTransaction();
1420 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001421 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001422 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001423 db.setTransactionSuccessful();
1424 } finally {
1425 db.endTransaction();
1426 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001427 }
Fred Quintana60307342009-03-24 22:48:12 -07001428 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001429 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001430 }
1431 }
1432
Carlos Valdivia91979be2015-05-22 14:11:35 -07001433 private void invalidateCustomTokenLocked(
1434 UserAccounts accounts,
1435 String accountType,
1436 String authToken) {
1437 if (authToken == null || accountType == null) {
1438 return;
1439 }
1440 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001441 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001442 }
1443
Amith Yamasani04e0d262012-02-14 11:50:53 -08001444 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1445 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001446 if (authToken == null || accountType == null) {
1447 return;
1448 }
Fred Quintana33269202009-04-20 16:05:10 -07001449 Cursor cursor = db.rawQuery(
1450 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1451 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1452 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1453 + " FROM " + TABLE_ACCOUNTS
1454 + " JOIN " + TABLE_AUTHTOKENS
1455 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1456 + " = " + AUTHTOKENS_ACCOUNTS_ID
1457 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1458 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1459 new String[]{authToken, accountType});
1460 try {
1461 while (cursor.moveToNext()) {
1462 long authTokenId = cursor.getLong(0);
1463 String accountName = cursor.getString(1);
1464 String authTokenType = cursor.getString(2);
1465 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001466 writeAuthTokenIntoCacheLocked(
1467 accounts,
1468 db,
1469 new Account(accountName, accountType),
1470 authTokenType,
1471 null);
Fred Quintana60307342009-03-24 22:48:12 -07001472 }
Fred Quintana33269202009-04-20 16:05:10 -07001473 } finally {
1474 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001475 }
1476 }
1477
Carlos Valdivia91979be2015-05-22 14:11:35 -07001478 private void saveCachedToken(
1479 UserAccounts accounts,
1480 Account account,
1481 String callerPkg,
1482 byte[] callerSigDigest,
1483 String tokenType,
1484 String token,
1485 long expiryMillis) {
1486
1487 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1488 return;
1489 }
1490 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1491 new UserHandle(accounts.userId));
1492 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001493 accounts.accountTokenCaches.put(
1494 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001495 }
1496 }
1497
Amith Yamasani04e0d262012-02-14 11:50:53 -08001498 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1499 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001500 if (account == null || type == null) {
1501 return false;
1502 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001503 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1504 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001505 synchronized (accounts.cacheLock) {
1506 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001507 db.beginTransaction();
1508 try {
1509 long accountId = getAccountIdLocked(db, account);
1510 if (accountId < 0) {
1511 return false;
1512 }
1513 db.delete(TABLE_AUTHTOKENS,
1514 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1515 new String[]{type});
1516 ContentValues values = new ContentValues();
1517 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1518 values.put(AUTHTOKENS_TYPE, type);
1519 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1520 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1521 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001522 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001523 return true;
1524 }
Fred Quintana33269202009-04-20 16:05:10 -07001525 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001526 } finally {
1527 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001528 }
Fred Quintana60307342009-03-24 22:48:12 -07001529 }
1530 }
1531
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001532 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001533 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001534 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001535 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1536 Log.v(TAG, "peekAuthToken: " + account
1537 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001538 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001539 + ", pid " + Binder.getCallingPid());
1540 }
Fred Quintana382601f2010-03-25 12:25:10 -07001541 if (account == null) throw new IllegalArgumentException("account is null");
1542 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001543 int userId = UserHandle.getCallingUserId();
1544 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001545 String msg = String.format(
1546 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1547 callingUid,
1548 account.type);
1549 throw new SecurityException(msg);
1550 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001551 long identityToken = clearCallingIdentity();
1552 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001553 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001554 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001555 } finally {
1556 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001557 }
Fred Quintana60307342009-03-24 22:48:12 -07001558 }
1559
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001560 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001561 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001562 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001563 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1564 Log.v(TAG, "setAuthToken: " + account
1565 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001566 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001567 + ", pid " + Binder.getCallingPid());
1568 }
Fred Quintana382601f2010-03-25 12:25:10 -07001569 if (account == null) throw new IllegalArgumentException("account is null");
1570 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001571 int userId = UserHandle.getCallingUserId();
1572 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001573 String msg = String.format(
1574 "uid %s cannot set auth tokens associated with accounts of type: %s",
1575 callingUid,
1576 account.type);
1577 throw new SecurityException(msg);
1578 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001579 long identityToken = clearCallingIdentity();
1580 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001581 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001582 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001583 } finally {
1584 restoreCallingIdentity(identityToken);
1585 }
Fred Quintana60307342009-03-24 22:48:12 -07001586 }
1587
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001588 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001589 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001590 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001591 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1592 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001593 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001594 + ", pid " + Binder.getCallingPid());
1595 }
Fred Quintana382601f2010-03-25 12:25:10 -07001596 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001597 int userId = UserHandle.getCallingUserId();
1598 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001599 String msg = String.format(
1600 "uid %s cannot set secrets for accounts of type: %s",
1601 callingUid,
1602 account.type);
1603 throw new SecurityException(msg);
1604 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001605 long identityToken = clearCallingIdentity();
1606 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001607 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001608 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001609 } finally {
1610 restoreCallingIdentity(identityToken);
1611 }
Fred Quintana60307342009-03-24 22:48:12 -07001612 }
1613
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001614 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1615 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001616 if (account == null) {
1617 return;
1618 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001619 synchronized (accounts.cacheLock) {
1620 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001621 db.beginTransaction();
1622 try {
1623 final ContentValues values = new ContentValues();
1624 values.put(ACCOUNTS_PASSWORD, password);
1625 final long accountId = getAccountIdLocked(db, account);
1626 if (accountId >= 0) {
1627 final String[] argsAccountId = {String.valueOf(accountId)};
1628 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1629 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001630 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001631 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001632 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001633
1634 String action = (password == null || password.length() == 0) ?
1635 DebugDbHelper.ACTION_CLEAR_PASSWORD
1636 : DebugDbHelper.ACTION_SET_PASSWORD;
1637 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001638 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001639 } finally {
1640 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001641 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001642 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001643 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001644 }
1645
Amith Yamasani04e0d262012-02-14 11:50:53 -08001646 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001647 Log.i(TAG, "the accounts changed, sending broadcast of "
1648 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001649 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001650 }
1651
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001652 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001653 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001654 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001655 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1656 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001657 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001658 + ", pid " + Binder.getCallingPid());
1659 }
Fred Quintana382601f2010-03-25 12:25:10 -07001660 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001661 int userId = UserHandle.getCallingUserId();
1662 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001663 String msg = String.format(
1664 "uid %s cannot clear passwords for accounts of type: %s",
1665 callingUid,
1666 account.type);
1667 throw new SecurityException(msg);
1668 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001669 long identityToken = clearCallingIdentity();
1670 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001671 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001672 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001673 } finally {
1674 restoreCallingIdentity(identityToken);
1675 }
Fred Quintana60307342009-03-24 22:48:12 -07001676 }
1677
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001678 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001679 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001680 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001681 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1682 Log.v(TAG, "setUserData: " + account
1683 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001684 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001685 + ", pid " + Binder.getCallingPid());
1686 }
Fred Quintana382601f2010-03-25 12:25:10 -07001687 if (key == null) throw new IllegalArgumentException("key is null");
1688 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001689 int userId = UserHandle.getCallingUserId();
1690 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001691 String msg = String.format(
1692 "uid %s cannot set user data for accounts of type: %s",
1693 callingUid,
1694 account.type);
1695 throw new SecurityException(msg);
1696 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001697 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001698 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001699 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001700 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001701 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001702 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001703 }
1704 }
1705
Amith Yamasani04e0d262012-02-14 11:50:53 -08001706 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1707 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001708 if (account == null || key == null) {
1709 return;
1710 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001711 synchronized (accounts.cacheLock) {
1712 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001713 db.beginTransaction();
1714 try {
1715 long accountId = getAccountIdLocked(db, account);
1716 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001717 return;
1718 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001719 long extrasId = getExtrasIdLocked(db, accountId, key);
1720 if (extrasId < 0 ) {
1721 extrasId = insertExtraLocked(db, accountId, key, value);
1722 if (extrasId < 0) {
1723 return;
1724 }
1725 } else {
1726 ContentValues values = new ContentValues();
1727 values.put(EXTRAS_VALUE, value);
1728 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1729 return;
1730 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001731
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001732 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001733 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001734 db.setTransactionSuccessful();
1735 } finally {
1736 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001737 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001738 }
1739 }
1740
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001741 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001742 if (result == null) {
1743 Log.e(TAG, "the result is unexpectedly null", new Exception());
1744 }
1745 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1746 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1747 + response);
1748 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001749 try {
1750 response.onResult(result);
1751 } catch (RemoteException e) {
1752 // if the caller is dead then there is no one to care about remote
1753 // exceptions
1754 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1755 Log.v(TAG, "failure while notifying response", e);
1756 }
1757 }
1758 }
1759
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001760 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001761 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1762 final String authTokenType)
1763 throws RemoteException {
1764 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001765 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1766
Fred Quintanad9640ec2012-05-23 12:37:00 -07001767 final int callingUid = getCallingUid();
1768 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001769 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001770 throw new SecurityException("can only call from system");
1771 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001772 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001773 long identityToken = clearCallingIdentity();
1774 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001775 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001776 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1777 false /* stripAuthTokenFromResult */, null /* accountName */,
1778 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001779 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001780 protected String toDebugString(long now) {
1781 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001782 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001783 + ", authTokenType " + authTokenType;
1784 }
1785
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001786 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001787 public void run() throws RemoteException {
1788 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1789 }
1790
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001791 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001792 public void onResult(Bundle result) {
1793 if (result != null) {
1794 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1795 Bundle bundle = new Bundle();
1796 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1797 super.onResult(bundle);
1798 return;
1799 } else {
1800 super.onResult(result);
1801 }
1802 }
1803 }.bind();
1804 } finally {
1805 restoreCallingIdentity(identityToken);
1806 }
1807 }
1808
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001809 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07001810 public void getAuthToken(
1811 IAccountManagerResponse response,
1812 final Account account,
1813 final String authTokenType,
1814 final boolean notifyOnAuthFailure,
1815 final boolean expectActivityLaunch,
1816 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001817 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1818 Log.v(TAG, "getAuthToken: " + account
1819 + ", response " + response
1820 + ", authTokenType " + authTokenType
1821 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1822 + ", expectActivityLaunch " + expectActivityLaunch
1823 + ", caller's uid " + Binder.getCallingUid()
1824 + ", pid " + Binder.getCallingPid());
1825 }
Fred Quintana382601f2010-03-25 12:25:10 -07001826 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001827 try {
1828 if (account == null) {
1829 Slog.w(TAG, "getAuthToken called with null account");
1830 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1831 return;
1832 }
1833 if (authTokenType == null) {
1834 Slog.w(TAG, "getAuthToken called with null authTokenType");
1835 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1836 return;
1837 }
1838 } catch (RemoteException e) {
1839 Slog.w(TAG, "Failed to report error back to the client." + e);
1840 return;
1841 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001842 int userId = UserHandle.getCallingUserId();
1843 long ident = Binder.clearCallingIdentity();
1844 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001845 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001846 try {
1847 accounts = getUserAccounts(userId);
1848 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1849 AuthenticatorDescription.newKey(account.type), accounts.userId);
1850 } finally {
1851 Binder.restoreCallingIdentity(ident);
1852 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001853
Costin Manolachea40c6302010-12-13 14:50:45 -08001854 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07001855 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08001856
1857 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001858 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001859 final boolean permissionGranted =
1860 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001861
Carlos Valdivia91979be2015-05-22 14:11:35 -07001862 // Get the calling package. We will use it for the purpose of caching.
1863 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07001864 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001865 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07001866 try {
1867 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
1868 } finally {
1869 Binder.restoreCallingIdentity(ident);
1870 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001871 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
1872 String msg = String.format(
1873 "Uid %s is attempting to illegally masquerade as package %s!",
1874 callerUid,
1875 callerPkg);
1876 throw new SecurityException(msg);
1877 }
1878
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001879 // let authenticator know the identity of the caller
1880 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1881 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07001882
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001883 if (notifyOnAuthFailure) {
1884 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001885 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001886
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001887 long identityToken = clearCallingIdentity();
1888 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07001889 // Distill the caller's package signatures into a single digest.
1890 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
1891
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001892 // if the caller has permission, do the peek. otherwise go the more expensive
1893 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001894 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001895 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001896 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001897 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001898 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1899 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1900 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001901 onResult(response, result);
1902 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001903 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001904 }
1905
Carlos Valdivia91979be2015-05-22 14:11:35 -07001906 if (customTokens) {
1907 /*
1908 * Look up tokens in the new cache only if the loginOptions don't have parameters
1909 * outside of those expected to be injected by the AccountManager, e.g.
1910 * ANDORID_PACKAGE_NAME.
1911 */
1912 String token = readCachedTokenInternal(
1913 accounts,
1914 account,
1915 authTokenType,
1916 callerPkg,
1917 callerPkgSigDigest);
1918 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001919 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1920 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
1921 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001922 Bundle result = new Bundle();
1923 result.putString(AccountManager.KEY_AUTHTOKEN, token);
1924 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1925 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
1926 onResult(response, result);
1927 return;
1928 }
1929 }
1930
Amith Yamasani04e0d262012-02-14 11:50:53 -08001931 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001932 false /* stripAuthTokenFromResult */, account.name,
1933 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001934 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001935 protected String toDebugString(long now) {
1936 if (loginOptions != null) loginOptions.keySet();
1937 return super.toDebugString(now) + ", getAuthToken"
1938 + ", " + account
1939 + ", authTokenType " + authTokenType
1940 + ", loginOptions " + loginOptions
1941 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1942 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001943
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001944 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001945 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001946 // If the caller doesn't have permission then create and return the
1947 // "grant permission" intent instead of the "getAuthToken" intent.
1948 if (!permissionGranted) {
1949 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1950 } else {
1951 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1952 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001953 }
1954
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001955 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001956 public void onResult(Bundle result) {
1957 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001958 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001959 Intent intent = newGrantCredentialsPermissionIntent(
1960 account,
1961 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001962 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001963 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001964 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001965 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001966 onResult(bundle);
1967 return;
1968 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001969 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001970 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001971 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1972 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001973 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001974 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001975 "the type and name should not be empty");
1976 return;
1977 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001978 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08001979 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001980 saveAuthTokenToDatabase(
1981 mAccounts,
1982 resultAccount,
1983 authTokenType,
1984 authToken);
1985 }
1986 long expiryMillis = result.getLong(
1987 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
1988 if (customTokens
1989 && expiryMillis > System.currentTimeMillis()) {
1990 saveCachedToken(
1991 mAccounts,
1992 account,
1993 callerPkg,
1994 callerPkgSigDigest,
1995 authTokenType,
1996 authToken,
1997 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08001998 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001999 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002000
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002001 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002002 if (intent != null && notifyOnAuthFailure && !customTokens) {
Jeff Sharkeyd87d2742017-06-12 17:33:07 -06002003 intent.setFlags(
2004 intent.getFlags() & ~(Intent.FLAG_GRANT_READ_URI_PERMISSION
2005 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
2006 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
2007 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002008 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002009 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002010 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002011 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002012 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002013 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002014 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002015 }.bind();
2016 } finally {
2017 restoreCallingIdentity(identityToken);
2018 }
Fred Quintana60307342009-03-24 22:48:12 -07002019 }
2020
Carlos Valdivia91979be2015-05-22 14:11:35 -07002021 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2022 MessageDigest digester;
2023 try {
2024 digester = MessageDigest.getInstance("SHA-256");
2025 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2026 callerPkg, PackageManager.GET_SIGNATURES);
2027 for (Signature sig : pkgInfo.signatures) {
2028 digester.update(sig.toByteArray());
2029 }
2030 } catch (NoSuchAlgorithmException x) {
2031 Log.wtf(TAG, "SHA-256 should be available", x);
2032 digester = null;
2033 } catch (NameNotFoundException e) {
2034 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2035 digester = null;
2036 }
2037 return (digester == null) ? null : digester.digest();
2038 }
2039
Dianne Hackborn41203752012-08-31 14:05:51 -07002040 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2041 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002042 int uid = intent.getIntExtra(
2043 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2044 String authTokenType = intent.getStringExtra(
2045 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002046 final String titleAndSubtitle =
2047 mContext.getString(R.string.permission_request_notification_with_subtitle,
2048 account.name);
2049 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002050 String title = titleAndSubtitle;
2051 String subtitle = "";
2052 if (index > 0) {
2053 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002054 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002055 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002056 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002057 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002058 Notification n = new Notification.Builder(contextForUser)
2059 .setSmallIcon(android.R.drawable.stat_sys_warning)
2060 .setWhen(0)
2061 .setColor(contextForUser.getColor(
2062 com.android.internal.R.color.system_notification_accent_color))
2063 .setContentTitle(title)
2064 .setContentText(subtitle)
2065 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2066 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2067 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002068 installNotification(getCredentialPermissionNotificationId(
2069 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002070 }
2071
Costin Manolache5f383ad92010-12-02 16:44:46 -08002072 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002073 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002074
2075 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002076 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002077 // Since it was set in Eclair+ we can't change it without breaking apps using
2078 // the intent from a non-Activity context.
2079 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002080 intent.addCategory(
2081 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002082
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002083 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002084 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2085 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002086 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002087
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002088 return intent;
2089 }
2090
2091 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2092 int uid) {
2093 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002094 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002095 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002096 final Pair<Pair<Account, String>, Integer> key =
2097 new Pair<Pair<Account, String>, Integer>(
2098 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002099 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002100 if (id == null) {
2101 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002102 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002103 }
2104 }
2105 return id;
2106 }
2107
Amith Yamasani04e0d262012-02-14 11:50:53 -08002108 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002109 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002110 synchronized (accounts.signinRequiredNotificationIds) {
2111 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002112 if (id == null) {
2113 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002114 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002115 }
2116 }
2117 return id;
2118 }
2119
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002120 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002121 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002122 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002123 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08002124 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2125 Log.v(TAG, "addAccount: accountType " + accountType
2126 + ", response " + response
2127 + ", authTokenType " + authTokenType
2128 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2129 + ", expectActivityLaunch " + expectActivityLaunch
2130 + ", caller's uid " + Binder.getCallingUid()
2131 + ", pid " + Binder.getCallingPid());
2132 }
Fred Quintana382601f2010-03-25 12:25:10 -07002133 if (response == null) throw new IllegalArgumentException("response is null");
2134 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002135
Amith Yamasani71e6c692013-03-24 17:39:28 -07002136 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002137 int userId = Binder.getCallingUserHandle().getIdentifier();
2138 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002139 try {
2140 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2141 "User is not allowed to add an account!");
2142 } catch (RemoteException re) {
2143 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002144 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002145 return;
2146 }
2147 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002148 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002149 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2150 "User cannot modify accounts of this type (policy).");
2151 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002152 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002153 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2154 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002155 return;
2156 }
2157
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002158 final int pid = Binder.getCallingPid();
2159 final int uid = Binder.getCallingUid();
2160 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2161 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2162 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2163
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002164 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002165 long identityToken = clearCallingIdentity();
2166 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002167 UserAccounts accounts = getUserAccounts(usrId);
2168 logRecordWithUid(
2169 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002170 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002171 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002172 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002173 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002174 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002175 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002176 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002177 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002178
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002179 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002180 protected String toDebugString(long now) {
2181 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002182 + ", accountType " + accountType
2183 + ", requiredFeatures "
2184 + (requiredFeatures != null
2185 ? TextUtils.join(",", requiredFeatures)
2186 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002187 }
2188 }.bind();
2189 } finally {
2190 restoreCallingIdentity(identityToken);
2191 }
Fred Quintana60307342009-03-24 22:48:12 -07002192 }
2193
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002194 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002195 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2196 final String authTokenType, final String[] requiredFeatures,
2197 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002198 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002199 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2200 Log.v(TAG, "addAccount: accountType " + accountType
2201 + ", response " + response
2202 + ", authTokenType " + authTokenType
2203 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2204 + ", expectActivityLaunch " + expectActivityLaunch
2205 + ", caller's uid " + Binder.getCallingUid()
2206 + ", pid " + Binder.getCallingPid()
2207 + ", for user id " + userId);
2208 }
2209 if (response == null) throw new IllegalArgumentException("response is null");
2210 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002211 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002212 if (isCrossUser(callingUid, userId)) {
2213 throw new SecurityException(
2214 String.format(
2215 "User %s trying to add account for %s" ,
2216 UserHandle.getCallingUserId(),
2217 userId));
2218 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002219
2220 // Is user disallowed from modifying accounts?
2221 if (!canUserModifyAccounts(userId)) {
2222 try {
2223 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2224 "User is not allowed to add an account!");
2225 } catch (RemoteException re) {
2226 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002227 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002228 return;
2229 }
2230 if (!canUserModifyAccountsForType(userId, accountType)) {
2231 try {
2232 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2233 "User cannot modify accounts of this type (policy).");
2234 } catch (RemoteException re) {
2235 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002236 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2237 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002238 return;
2239 }
2240
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002241 final int pid = Binder.getCallingPid();
2242 final int uid = Binder.getCallingUid();
2243 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2244 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2245 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2246
2247 long identityToken = clearCallingIdentity();
2248 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002249 UserAccounts accounts = getUserAccounts(userId);
2250 logRecordWithUid(
2251 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002252 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002253 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002254 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002255 @Override
2256 public void run() throws RemoteException {
2257 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2258 options);
2259 }
2260
2261 @Override
2262 protected String toDebugString(long now) {
2263 return super.toDebugString(now) + ", addAccount"
2264 + ", accountType " + accountType
2265 + ", requiredFeatures "
2266 + (requiredFeatures != null
2267 ? TextUtils.join(",", requiredFeatures)
2268 : null);
2269 }
2270 }.bind();
2271 } finally {
2272 restoreCallingIdentity(identityToken);
2273 }
2274 }
2275
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002276 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002277 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2278 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2279 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2280 long identityToken = clearCallingIdentity();
2281 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002282 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002283 } finally {
2284 restoreCallingIdentity(identityToken);
2285 }
2286 }
2287
2288 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002289 public void confirmCredentialsAsUser(
2290 IAccountManagerResponse response,
2291 final Account account,
2292 final Bundle options,
2293 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002294 int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002295 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002296 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2297 Log.v(TAG, "confirmCredentials: " + account
2298 + ", response " + response
2299 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002300 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002301 + ", pid " + Binder.getCallingPid());
2302 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002303 // Only allow the system process to read accounts of other users
2304 if (isCrossUser(callingUid, userId)) {
2305 throw new SecurityException(
2306 String.format(
2307 "User %s trying to confirm account credentials for %s" ,
2308 UserHandle.getCallingUserId(),
2309 userId));
2310 }
Fred Quintana382601f2010-03-25 12:25:10 -07002311 if (response == null) throw new IllegalArgumentException("response is null");
2312 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002313 long identityToken = clearCallingIdentity();
2314 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002315 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002316 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002317 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002318 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002319 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002320 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002321 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002322 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002323 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002324 protected String toDebugString(long now) {
2325 return super.toDebugString(now) + ", confirmCredentials"
2326 + ", " + account;
2327 }
2328 }.bind();
2329 } finally {
2330 restoreCallingIdentity(identityToken);
2331 }
Fred Quintana60307342009-03-24 22:48:12 -07002332 }
2333
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002334 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002335 public void updateCredentials(IAccountManagerResponse response, final Account account,
2336 final String authTokenType, final boolean expectActivityLaunch,
2337 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08002338 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2339 Log.v(TAG, "updateCredentials: " + account
2340 + ", response " + response
2341 + ", authTokenType " + authTokenType
2342 + ", expectActivityLaunch " + expectActivityLaunch
2343 + ", caller's uid " + Binder.getCallingUid()
2344 + ", pid " + Binder.getCallingPid());
2345 }
Fred Quintana382601f2010-03-25 12:25:10 -07002346 if (response == null) throw new IllegalArgumentException("response is null");
2347 if (account == null) throw new IllegalArgumentException("account is null");
2348 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002349 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002350 long identityToken = clearCallingIdentity();
2351 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002352 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002353 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002354 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002355 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002356 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002357 public void run() throws RemoteException {
2358 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2359 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002360 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002361 protected String toDebugString(long now) {
2362 if (loginOptions != null) loginOptions.keySet();
2363 return super.toDebugString(now) + ", updateCredentials"
2364 + ", " + account
2365 + ", authTokenType " + authTokenType
2366 + ", loginOptions " + loginOptions;
2367 }
2368 }.bind();
2369 } finally {
2370 restoreCallingIdentity(identityToken);
2371 }
Fred Quintana60307342009-03-24 22:48:12 -07002372 }
2373
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002374 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002375 public void editProperties(IAccountManagerResponse response, final String accountType,
2376 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002377 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002378 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2379 Log.v(TAG, "editProperties: accountType " + accountType
2380 + ", response " + response
2381 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002382 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002383 + ", pid " + Binder.getCallingPid());
2384 }
Fred Quintana382601f2010-03-25 12:25:10 -07002385 if (response == null) throw new IllegalArgumentException("response is null");
2386 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002387 int userId = UserHandle.getCallingUserId();
2388 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002389 String msg = String.format(
2390 "uid %s cannot edit authenticator properites for account type: %s",
2391 callingUid,
2392 accountType);
2393 throw new SecurityException(msg);
2394 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002395 long identityToken = clearCallingIdentity();
2396 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002397 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002398 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002399 true /* stripAuthTokenFromResult */, null /* accountName */,
2400 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002401 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002402 public void run() throws RemoteException {
2403 mAuthenticator.editProperties(this, mAccountType);
2404 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002405 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002406 protected String toDebugString(long now) {
2407 return super.toDebugString(now) + ", editProperties"
2408 + ", accountType " + accountType;
2409 }
2410 }.bind();
2411 } finally {
2412 restoreCallingIdentity(identityToken);
2413 }
Fred Quintana60307342009-03-24 22:48:12 -07002414 }
2415
Fred Quintana33269202009-04-20 16:05:10 -07002416 private class GetAccountsByTypeAndFeatureSession extends Session {
2417 private final String[] mFeatures;
2418 private volatile Account[] mAccountsOfType = null;
2419 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2420 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002421 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002422
Amith Yamasani04e0d262012-02-14 11:50:53 -08002423 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002424 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002425 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002426 true /* stripAuthTokenFromResult */, null /* accountName */,
2427 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002428 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002429 mFeatures = features;
2430 }
2431
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002432 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002433 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002434 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002435 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2436 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002437 }
Fred Quintana33269202009-04-20 16:05:10 -07002438 // check whether each account matches the requested features
2439 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2440 mCurrentAccount = 0;
2441
2442 checkAccount();
2443 }
2444
2445 public void checkAccount() {
2446 if (mCurrentAccount >= mAccountsOfType.length) {
2447 sendResult();
2448 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002449 }
Fred Quintana33269202009-04-20 16:05:10 -07002450
Fred Quintana29e94b82010-03-10 12:11:51 -08002451 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2452 if (accountAuthenticator == null) {
2453 // It is possible that the authenticator has died, which is indicated by
2454 // mAuthenticator being set to null. If this happens then just abort.
2455 // There is no need to send back a result or error in this case since
2456 // that already happened when mAuthenticator was cleared.
2457 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2458 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2459 + " connected to the authenticator, " + toDebugString());
2460 }
2461 return;
2462 }
Fred Quintana33269202009-04-20 16:05:10 -07002463 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002464 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002465 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002466 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002467 }
2468 }
2469
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002470 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002471 public void onResult(Bundle result) {
2472 mNumResults++;
2473 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002474 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002475 return;
2476 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002477 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002478 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2479 }
2480 mCurrentAccount++;
2481 checkAccount();
2482 }
2483
2484 public void sendResult() {
2485 IAccountManagerResponse response = getResponseAndClose();
2486 if (response != null) {
2487 try {
2488 Account[] accounts = new Account[mAccountsWithFeatures.size()];
2489 for (int i = 0; i < accounts.length; i++) {
2490 accounts[i] = mAccountsWithFeatures.get(i);
2491 }
Fred Quintana56285a62010-12-02 14:20:51 -08002492 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2493 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2494 + response);
2495 }
Fred Quintana33269202009-04-20 16:05:10 -07002496 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002497 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07002498 response.onResult(result);
2499 } catch (RemoteException e) {
2500 // if the caller is dead then there is no one to care about remote exceptions
2501 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2502 Log.v(TAG, "failure while notifying response", e);
2503 }
2504 }
2505 }
2506 }
2507
2508
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002509 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002510 protected String toDebugString(long now) {
2511 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2512 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2513 }
2514 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002515
Amith Yamasani04e0d262012-02-14 11:50:53 -08002516 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002517 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08002518 * @hide
2519 */
Svetoslavce852dd2015-09-08 14:36:35 -07002520 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002521 int callingUid = Binder.getCallingUid();
Svetoslavce852dd2015-09-08 14:36:35 -07002522 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2523 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002524 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002525 return new Account[0];
2526 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002527 long identityToken = clearCallingIdentity();
2528 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002529 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002530 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002531 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002532 callingUid,
2533 null, // packageName
2534 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002535 } finally {
2536 restoreCallingIdentity(identityToken);
2537 }
2538 }
2539
Amith Yamasanif29f2362012-04-05 18:29:52 -07002540 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002541 * Returns accounts for all running users.
2542 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07002543 * @hide
2544 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002545 public AccountAndUser[] getRunningAccounts() {
2546 final int[] runningUserIds;
2547 try {
2548 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2549 } catch (RemoteException e) {
2550 // Running in system_server; should never happen
2551 throw new RuntimeException(e);
2552 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002553 return getAccounts(runningUserIds);
2554 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07002555
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002556 /** {@hide} */
2557 public AccountAndUser[] getAllAccounts() {
2558 final List<UserInfo> users = getUserManager().getUsers();
2559 final int[] userIds = new int[users.size()];
2560 for (int i = 0; i < userIds.length; i++) {
2561 userIds[i] = users.get(i).id;
2562 }
2563 return getAccounts(userIds);
2564 }
2565
2566 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002567 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002568 for (int userId : userIds) {
2569 UserAccounts userAccounts = getUserAccounts(userId);
2570 if (userAccounts == null) continue;
2571 synchronized (userAccounts.cacheLock) {
2572 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2573 Binder.getCallingUid(), null);
2574 for (int a = 0; a < accounts.length; a++) {
2575 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07002576 }
2577 }
2578 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002579
2580 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2581 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002582 }
2583
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002584 @Override
Svetoslavce852dd2015-09-08 14:36:35 -07002585 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
2586 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07002587 }
2588
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002589 private Account[] getAccountsAsUser(
2590 String type,
2591 int userId,
2592 String callingPackage,
Svetoslavce852dd2015-09-08 14:36:35 -07002593 int packageUid,
2594 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002595 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002596 // Only allow the system process to read accounts of other users
2597 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002598 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002599 && mContext.checkCallingOrSelfPermission(
2600 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2601 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002602 throw new SecurityException("User " + UserHandle.getCallingUserId()
2603 + " trying to get account for " + userId);
2604 }
2605
Fred Quintana56285a62010-12-02 14:20:51 -08002606 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2607 Log.v(TAG, "getAccounts: accountType " + type
2608 + ", caller's uid " + Binder.getCallingUid()
2609 + ", pid " + Binder.getCallingPid());
2610 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002611 // If the original calling app was using the framework account chooser activity, we'll
2612 // be passed in the original caller's uid here, which is what should be used for filtering.
2613 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2614 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07002615 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07002616 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002617
Svetoslavce852dd2015-09-08 14:36:35 -07002618 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2619 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002620 if (visibleAccountTypes.isEmpty()
2621 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002622 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002623 } else if (visibleAccountTypes.contains(type)) {
2624 // Prune the list down to just the requested type.
2625 visibleAccountTypes = new ArrayList<>();
2626 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07002627 } // else aggregate all the visible accounts (it won't matter if the
2628 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002629
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002630 long identityToken = clearCallingIdentity();
2631 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002632 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002633 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002634 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002635 callingUid,
2636 callingPackage,
2637 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002638 } finally {
2639 restoreCallingIdentity(identityToken);
2640 }
2641 }
2642
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002643 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002644 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002645 int callingUid,
2646 String callingPackage,
2647 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002648 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002649 ArrayList<Account> visibleAccounts = new ArrayList<>();
2650 for (String visibleType : visibleAccountTypes) {
2651 Account[] accountsForType = getAccountsFromCacheLocked(
2652 userAccounts, visibleType, callingUid, callingPackage);
2653 if (accountsForType != null) {
2654 visibleAccounts.addAll(Arrays.asList(accountsForType));
2655 }
2656 }
2657 Account[] result = new Account[visibleAccounts.size()];
2658 for (int i = 0; i < visibleAccounts.size(); i++) {
2659 result[i] = visibleAccounts.get(i);
2660 }
2661 return result;
2662 }
2663 }
2664
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002665 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002666 public boolean addSharedAccountAsUser(Account account, int userId) {
2667 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002668 UserAccounts accounts = getUserAccounts(userId);
2669 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002670 ContentValues values = new ContentValues();
2671 values.put(ACCOUNTS_NAME, account.name);
2672 values.put(ACCOUNTS_TYPE, account.type);
2673 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2674 new String[] {account.name, account.type});
2675 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2676 if (accountId < 0) {
2677 Log.w(TAG, "insertAccountIntoDatabase: " + account
2678 + ", skipping the DB insert failed");
2679 return false;
2680 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002681 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002682 return true;
2683 }
2684
2685 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002686 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
2687 userId = handleIncomingUser(userId);
2688 UserAccounts accounts = getUserAccounts(userId);
2689 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002690 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002691 final ContentValues values = new ContentValues();
2692 values.put(ACCOUNTS_NAME, newName);
2693 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
2694 int r = db.update(
2695 TABLE_SHARED_ACCOUNTS,
2696 values,
2697 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2698 new String[] { account.name, account.type });
2699 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002700 int callingUid = getCallingUid();
2701 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
2702 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002703 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002704 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002705 }
2706 return r > 0;
2707 }
2708
2709 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002710 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002711 return removeSharedAccountAsUser(account, userId, getCallingUid());
2712 }
2713
2714 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08002715 userId = handleIncomingUser(userId);
2716 UserAccounts accounts = getUserAccounts(userId);
2717 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002718 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002719 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2720 new String[] {account.name, account.type});
2721 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002722 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
2723 sharedTableAccountId, accounts, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002724 removeAccountInternal(accounts, account);
2725 }
2726 return r > 0;
2727 }
2728
2729 @Override
2730 public Account[] getSharedAccountsAsUser(int userId) {
2731 userId = handleIncomingUser(userId);
2732 UserAccounts accounts = getUserAccounts(userId);
2733 ArrayList<Account> accountList = new ArrayList<Account>();
2734 Cursor cursor = null;
2735 try {
2736 cursor = accounts.openHelper.getReadableDatabase()
2737 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2738 null, null, null, null, null);
2739 if (cursor != null && cursor.moveToFirst()) {
2740 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2741 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2742 do {
2743 accountList.add(new Account(cursor.getString(nameIndex),
2744 cursor.getString(typeIndex)));
2745 } while (cursor.moveToNext());
2746 }
2747 } finally {
2748 if (cursor != null) {
2749 cursor.close();
2750 }
2751 }
2752 Account[] accountArray = new Account[accountList.size()];
2753 accountList.toArray(accountArray);
2754 return accountArray;
2755 }
2756
2757 @Override
Svetoslavce852dd2015-09-08 14:36:35 -07002758 public Account[] getAccounts(String type, String opPackageName) {
2759 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002760 }
2761
Amith Yamasani27db4682013-03-30 17:07:47 -07002762 @Override
Svetoslavce852dd2015-09-08 14:36:35 -07002763 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002764 int callingUid = Binder.getCallingUid();
2765 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2766 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2767 + callingUid + " with uid=" + uid);
2768 }
Svetoslavce852dd2015-09-08 14:36:35 -07002769 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
2770 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07002771 }
2772
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002773 @Override
Svetoslavce852dd2015-09-08 14:36:35 -07002774 public Account[] getAccountsByTypeForPackage(String type, String packageName,
2775 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002776 int packageUid = -1;
2777 try {
2778 packageUid = AppGlobals.getPackageManager().getPackageUid(
2779 packageName, UserHandle.getCallingUserId());
2780 } catch (RemoteException re) {
2781 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2782 return new Account[0];
2783 }
Svetoslavce852dd2015-09-08 14:36:35 -07002784 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
2785 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002786 }
2787
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002788 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002789 public void getAccountsByFeatures(
2790 IAccountManagerResponse response,
2791 String type,
Svetoslavce852dd2015-09-08 14:36:35 -07002792 String[] features,
2793 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002794 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002795 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2796 Log.v(TAG, "getAccounts: accountType " + type
2797 + ", response " + response
2798 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002799 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002800 + ", pid " + Binder.getCallingPid());
2801 }
Fred Quintana382601f2010-03-25 12:25:10 -07002802 if (response == null) throw new IllegalArgumentException("response is null");
2803 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002804 int userId = UserHandle.getCallingUserId();
2805
Svetoslavce852dd2015-09-08 14:36:35 -07002806 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2807 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002808 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002809 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002810 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002811 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
2812 try {
2813 response.onResult(result);
2814 } catch (RemoteException e) {
2815 Log.e(TAG, "Cannot respond to caller do to exception." , e);
2816 }
2817 return;
2818 }
Fred Quintana33269202009-04-20 16:05:10 -07002819 long identityToken = clearCallingIdentity();
2820 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002821 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002822 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002823 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002824 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002825 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002826 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002827 Bundle result = new Bundle();
2828 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2829 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002830 return;
2831 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002832 new GetAccountsByTypeAndFeatureSession(
2833 userAccounts,
2834 response,
2835 type,
2836 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002837 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002838 } finally {
2839 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002840 }
2841 }
2842
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002843 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
2844 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
2845 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
2846 try {
2847 if (cursor.moveToNext()) {
2848 return cursor.getLong(0);
2849 }
2850 return -1;
2851 } finally {
2852 cursor.close();
2853 }
2854 }
2855
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002856 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002857 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002858 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002859 try {
2860 if (cursor.moveToNext()) {
2861 return cursor.getLong(0);
2862 }
2863 return -1;
2864 } finally {
2865 cursor.close();
2866 }
2867 }
2868
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002869 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002870 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2871 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2872 new String[]{key}, null, null, null);
2873 try {
2874 if (cursor.moveToNext()) {
2875 return cursor.getLong(0);
2876 }
2877 return -1;
2878 } finally {
2879 cursor.close();
2880 }
2881 }
2882
Fred Quintanaa698f422009-04-08 19:14:54 -07002883 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002884 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002885 IAccountManagerResponse mResponse;
2886 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002887 final boolean mExpectActivityLaunch;
2888 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002889 final String mAccountName;
2890 // Indicates if we need to add auth details(like last credential time)
2891 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002892 // If set, we need to update the last authenticated time. This is
2893 // currently
2894 // used on
2895 // successful confirming credentials.
2896 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07002897
Fred Quintana33269202009-04-20 16:05:10 -07002898 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002899 private int mNumRequestContinued = 0;
2900 private int mNumErrors = 0;
2901
Fred Quintana60307342009-03-24 22:48:12 -07002902 IAccountAuthenticator mAuthenticator = null;
2903
Fred Quintana8570f742010-02-18 10:32:54 -08002904 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002905 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002906
Amith Yamasani04e0d262012-02-14 11:50:53 -08002907 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002908 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2909 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002910 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
2911 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
2912 }
2913
2914 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
2915 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2916 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07002917 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002918 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002919 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002920 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002921 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002922 mResponse = response;
2923 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002924 mExpectActivityLaunch = expectActivityLaunch;
2925 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002926 mAccountName = accountName;
2927 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002928 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002929
Fred Quintanaa698f422009-04-08 19:14:54 -07002930 synchronized (mSessions) {
2931 mSessions.put(toString(), this);
2932 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002933 if (response != null) {
2934 try {
2935 response.asBinder().linkToDeath(this, 0 /* flags */);
2936 } catch (RemoteException e) {
2937 mResponse = null;
2938 binderDied();
2939 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002940 }
Fred Quintana60307342009-03-24 22:48:12 -07002941 }
2942
Fred Quintanaa698f422009-04-08 19:14:54 -07002943 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002944 if (mResponse == null) {
2945 // this session has already been closed
2946 return null;
2947 }
Fred Quintana60307342009-03-24 22:48:12 -07002948 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002949 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002950 return response;
2951 }
2952
Fred Quintanaa698f422009-04-08 19:14:54 -07002953 private void close() {
2954 synchronized (mSessions) {
2955 if (mSessions.remove(toString()) == null) {
2956 // the session was already closed, so bail out now
2957 return;
2958 }
2959 }
2960 if (mResponse != null) {
2961 // stop listening for response deaths
2962 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2963
2964 // clear this so that we don't accidentally send any further results
2965 mResponse = null;
2966 }
2967 cancelTimeout();
2968 unbind();
2969 }
2970
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002971 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002972 public void binderDied() {
2973 mResponse = null;
2974 close();
2975 }
2976
2977 protected String toDebugString() {
2978 return toDebugString(SystemClock.elapsedRealtime());
2979 }
2980
2981 protected String toDebugString(long now) {
2982 return "Session: expectLaunch " + mExpectActivityLaunch
2983 + ", connected " + (mAuthenticator != null)
2984 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2985 + "/" + mNumErrors + ")"
2986 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2987 }
2988
Fred Quintana60307342009-03-24 22:48:12 -07002989 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002990 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2991 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2992 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002993 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002994 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002995 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002996 }
2997 }
2998
2999 private void unbind() {
3000 if (mAuthenticator != null) {
3001 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003002 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003003 }
3004 }
3005
Fred Quintana60307342009-03-24 22:48:12 -07003006 public void cancelTimeout() {
3007 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3008 }
3009
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003010 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003011 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003012 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003013 try {
3014 run();
3015 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003016 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003017 "remote exception");
3018 }
Fred Quintana60307342009-03-24 22:48:12 -07003019 }
3020
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003021 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003022 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003023 mAuthenticator = null;
3024 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003025 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003026 try {
3027 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3028 "disconnected");
3029 } catch (RemoteException e) {
3030 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3031 Log.v(TAG, "Session.onServiceDisconnected: "
3032 + "caught RemoteException while responding", e);
3033 }
3034 }
Fred Quintana60307342009-03-24 22:48:12 -07003035 }
3036 }
3037
Fred Quintanab839afc2009-10-14 15:57:28 -07003038 public abstract void run() throws RemoteException;
3039
Fred Quintana60307342009-03-24 22:48:12 -07003040 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003041 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003042 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003043 try {
3044 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3045 "timeout");
3046 } catch (RemoteException e) {
3047 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3048 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3049 e);
3050 }
3051 }
Fred Quintana60307342009-03-24 22:48:12 -07003052 }
3053 }
3054
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003055 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003056 public void onResult(Bundle result) {
3057 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003058 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003059 if (result != null) {
3060 boolean isSuccessfulConfirmCreds = result.getBoolean(
3061 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003062 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003063 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3064 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003065 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003066 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3067 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003068 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003069 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003070 if (needUpdate || mAuthDetailsRequired) {
3071 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3072 if (needUpdate && accountPresent) {
3073 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3074 }
3075 if (mAuthDetailsRequired) {
3076 long lastAuthenticatedTime = -1;
3077 if (accountPresent) {
3078 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3079 mAccounts.openHelper.getReadableDatabase(),
3080 "select " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3081 + " from " +
3082 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3083 + ACCOUNTS_TYPE + "=?",
3084 new String[] {
3085 mAccountName, mAccountType
3086 });
3087 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003088 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003089 lastAuthenticatedTime);
3090 }
3091 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003092 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003093 if (result != null
3094 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Jeff Sharkeyd87d2742017-06-12 17:33:07 -06003095 intent.setFlags(
3096 intent.getFlags() & ~(Intent.FLAG_GRANT_READ_URI_PERMISSION
3097 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3098 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
3099 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION));
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003100 /*
3101 * The Authenticator API allows third party authenticators to
3102 * supply arbitrary intents to other apps that they can run,
3103 * this can be very bad when those apps are in the system like
3104 * the System Settings.
3105 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003106 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07003107 long bid = Binder.clearCallingIdentity();
3108 try {
3109 PackageManager pm = mContext.getPackageManager();
3110 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3111 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
3112 if (PackageManager.SIGNATURE_MATCH !=
3113 pm.checkSignatures(authenticatorUid, targetUid)) {
3114 throw new SecurityException(
3115 "Activity to be started with KEY_INTENT must " +
3116 "share Authenticator's signatures");
3117 }
3118 } finally {
3119 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003120 }
3121 }
3122 if (result != null
3123 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003124 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3125 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003126 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3127 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003128 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3129 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003130 }
Fred Quintana60307342009-03-24 22:48:12 -07003131 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003132 IAccountManagerResponse response;
3133 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003134 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003135 response = mResponse;
3136 } else {
3137 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003138 }
Fred Quintana60307342009-03-24 22:48:12 -07003139 if (response != null) {
3140 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07003141 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08003142 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3143 Log.v(TAG, getClass().getSimpleName()
3144 + " calling onError() on response " + response);
3145 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003146 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07003147 "null bundle returned");
3148 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08003149 if (mStripAuthTokenFromResult) {
3150 result.remove(AccountManager.KEY_AUTHTOKEN);
3151 }
Fred Quintana56285a62010-12-02 14:20:51 -08003152 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3153 Log.v(TAG, getClass().getSimpleName()
3154 + " calling onResult() on response " + response);
3155 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003156 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3157 (intent == null)) {
3158 // All AccountManager error codes are greater than 0
3159 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3160 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3161 } else {
3162 response.onResult(result);
3163 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003164 }
Fred Quintana60307342009-03-24 22:48:12 -07003165 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003166 // if the caller is dead then there is no one to care about remote exceptions
3167 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3168 Log.v(TAG, "failure while notifying response", e);
3169 }
Fred Quintana60307342009-03-24 22:48:12 -07003170 }
3171 }
3172 }
Fred Quintana60307342009-03-24 22:48:12 -07003173
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003174 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003175 public void onRequestContinued() {
3176 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003177 }
3178
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003179 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003180 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003181 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003182 IAccountManagerResponse response = getResponseAndClose();
3183 if (response != null) {
3184 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003185 Log.v(TAG, getClass().getSimpleName()
3186 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003187 }
3188 try {
3189 response.onError(errorCode, errorMessage);
3190 } catch (RemoteException e) {
3191 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3192 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3193 }
3194 }
3195 } else {
3196 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3197 Log.v(TAG, "Session.onError: already closed");
3198 }
Fred Quintana60307342009-03-24 22:48:12 -07003199 }
3200 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003201
3202 /**
3203 * find the component name for the authenticator and initiate a bind
3204 * if no authenticator or the bind fails then return false, otherwise return true
3205 */
3206 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003207 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3208 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3209 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003210 if (authenticatorInfo == null) {
3211 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3212 Log.v(TAG, "there is no authenticator for " + authenticatorType
3213 + ", bailing out");
3214 }
3215 return false;
3216 }
3217
3218 Intent intent = new Intent();
3219 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3220 intent.setComponent(authenticatorInfo.componentName);
3221 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3222 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3223 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003224 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
3225 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003226 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3227 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3228 }
3229 return false;
3230 }
3231
3232
3233 return true;
3234 }
Fred Quintana60307342009-03-24 22:48:12 -07003235 }
3236
3237 private class MessageHandler extends Handler {
3238 MessageHandler(Looper looper) {
3239 super(looper);
3240 }
Costin Manolache3348f142009-09-29 18:58:36 -07003241
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003242 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003243 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07003244 switch (msg.what) {
3245 case MESSAGE_TIMED_OUT:
3246 Session session = (Session)msg.obj;
3247 session.onTimedOut();
3248 break;
3249
Amith Yamasani5be347b2013-03-31 17:44:31 -07003250 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00003251 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07003252 break;
3253
Fred Quintana60307342009-03-24 22:48:12 -07003254 default:
3255 throw new IllegalStateException("unhandled message: " + msg.what);
3256 }
3257 }
3258 }
3259
Amith Yamasani04e0d262012-02-14 11:50:53 -08003260 private static String getDatabaseName(int userId) {
3261 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07003262 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003263 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07003264 // Migrate old file, if it exists, to the new location.
3265 // Make sure the new file doesn't already exist. A dummy file could have been
3266 // accidentally created in the old location, causing the new one to become corrupted
3267 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08003268 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07003269 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07003270 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07003271 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07003272 if (!userDir.exists()) {
3273 if (!userDir.mkdirs()) {
3274 throw new IllegalStateException("User dir cannot be created: " + userDir);
3275 }
3276 }
3277 if (!oldFile.renameTo(databaseFile)) {
3278 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
3279 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003280 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003281 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003282 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08003283 }
3284
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003285 private static class DebugDbHelper{
3286 private DebugDbHelper() {
3287 }
3288
3289 private static String TABLE_DEBUG = "debug_table";
3290
3291 // Columns for the table
3292 private static String ACTION_TYPE = "action_type";
3293 private static String TIMESTAMP = "time";
3294 private static String CALLER_UID = "caller_uid";
3295 private static String TABLE_NAME = "table_name";
3296 private static String KEY = "primary_key";
3297
3298 // These actions correspond to the occurrence of real actions. Since
3299 // these are called by the authenticators, the uid associated will be
3300 // of the authenticator.
3301 private static String ACTION_SET_PASSWORD = "action_set_password";
3302 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
3303 private static String ACTION_ACCOUNT_ADD = "action_account_add";
3304 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
3305 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
3306 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
3307
3308 // These actions don't necessarily correspond to any action on
3309 // accountDb taking place. As an example, there might be a request for
3310 // addingAccount, which might not lead to addition of account on grounds
3311 // of bad authentication. We will still be logging it to keep track of
3312 // who called.
3313 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
3314 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003315
3316 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3317
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003318 private static void createDebugTable(SQLiteDatabase db) {
3319 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
3320 + ACCOUNTS_ID + " INTEGER,"
3321 + ACTION_TYPE + " TEXT NOT NULL, "
3322 + TIMESTAMP + " DATETIME,"
3323 + CALLER_UID + " INTEGER NOT NULL,"
3324 + TABLE_NAME + " TEXT NOT NULL,"
3325 + KEY + " INTEGER PRIMARY KEY)");
3326 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
3327 }
3328 }
3329
3330 private void logRecord(UserAccounts accounts, String action, String tableName) {
3331 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3332 logRecord(db, action, tableName, -1, accounts);
3333 }
3334
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003335 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
3336 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3337 logRecord(db, action, tableName, -1, accounts, uid);
3338 }
3339
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003340 /*
3341 * This function receives an opened writable database.
3342 */
3343 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3344 UserAccounts userAccount) {
3345 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
3346 }
3347
3348 /*
3349 * This function receives an opened writable database.
3350 */
3351 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3352 UserAccounts userAccount, int callingUid) {
3353 SQLiteStatement logStatement = userAccount.statementForLogging;
3354 logStatement.bindLong(1, accountId);
3355 logStatement.bindString(2, action);
3356 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
3357 logStatement.bindLong(4, callingUid);
3358 logStatement.bindString(5, tableName);
3359 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
3360 logStatement.execute();
3361 logStatement.clearBindings();
3362 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
3363 % MAX_DEBUG_DB_SIZE;
3364 }
3365
3366 /*
3367 * This should only be called once to compile the sql statement for logging
3368 * and to find the insertion point.
3369 */
3370 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
3371 UserAccounts userAccount) {
3372 // Initialize the count if not done earlier.
3373 int size = (int) getDebugTableRowCount(db);
3374 if (size >= MAX_DEBUG_DB_SIZE) {
3375 // Table is full, and we need to find the point where to insert.
3376 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
3377 } else {
3378 userAccount.debugDbInsertionPoint = size;
3379 }
3380 compileSqlStatementForLogging(db, userAccount);
3381 }
3382
3383 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
3384 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
3385 + " VALUES (?,?,?,?,?,?)";
3386 userAccount.statementForLogging = db.compileStatement(sql);
3387 }
3388
3389 private long getDebugTableRowCount(SQLiteDatabase db) {
3390 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
3391 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3392 }
3393
3394 /*
3395 * Finds the row key where the next insertion should take place. This should
3396 * be invoked only if the table has reached its full capacity.
3397 */
3398 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
3399 // This query finds the smallest timestamp value (and if 2 records have
3400 // same timestamp, the choose the lower id).
3401 String queryCountDebugDbRows = new StringBuilder()
3402 .append("SELECT ").append(DebugDbHelper.KEY)
3403 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
3404 .append(" ORDER BY ")
3405 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
3406 .append(" LIMIT 1")
3407 .toString();
3408 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3409 }
3410
Amith Yamasani04e0d262012-02-14 11:50:53 -08003411 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003412
Amith Yamasani04e0d262012-02-14 11:50:53 -08003413 public DatabaseHelper(Context context, int userId) {
3414 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07003415 }
3416
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003417 /**
3418 * This call needs to be made while the mCacheLock is held. The way to
3419 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
3420 * @param db The database.
3421 */
Fred Quintana60307342009-03-24 22:48:12 -07003422 @Override
3423 public void onCreate(SQLiteDatabase db) {
3424 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
3425 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3426 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3427 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3428 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003429 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003430 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
Fred Quintana60307342009-03-24 22:48:12 -07003431 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3432
3433 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
3434 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3435 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3436 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
3437 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
3438 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
3439
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003440 createGrantsTable(db);
3441
Fred Quintana60307342009-03-24 22:48:12 -07003442 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
3443 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3444 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
3445 + EXTRAS_KEY + " TEXT NOT NULL, "
3446 + EXTRAS_VALUE + " TEXT, "
3447 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
3448
3449 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
3450 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
3451 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07003452
Amith Yamasani67df64b2012-12-14 12:09:36 -08003453 createSharedAccountsTable(db);
3454
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003455 createAccountsDeletionTrigger(db);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003456
3457 DebugDbHelper.createDebugTable(db);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003458 }
3459
Amith Yamasani67df64b2012-12-14 12:09:36 -08003460 private void createSharedAccountsTable(SQLiteDatabase db) {
3461 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
3462 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3463 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3464 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3465 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3466 }
3467
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003468 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
3469 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
3470 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
3471 }
3472
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003473 private void addOldAccountNameColumn(SQLiteDatabase db) {
3474 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
3475 }
3476
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003477 private void addDebugTable(SQLiteDatabase db) {
3478 DebugDbHelper.createDebugTable(db);
3479 }
3480
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003481 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003482 db.execSQL(""
3483 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
3484 + " BEGIN"
3485 + " DELETE FROM " + TABLE_AUTHTOKENS
3486 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
3487 + " DELETE FROM " + TABLE_EXTRAS
3488 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003489 + " DELETE FROM " + TABLE_GRANTS
3490 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07003491 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07003492 }
3493
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003494 private void createGrantsTable(SQLiteDatabase db) {
3495 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
3496 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3497 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
3498 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
3499 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
3500 + "," + GRANTS_GRANTEE_UID + "))");
3501 }
3502
Fred Quintana60307342009-03-24 22:48:12 -07003503 @Override
3504 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003505 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07003506
Fred Quintanaa698f422009-04-08 19:14:54 -07003507 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003508 // no longer need to do anything since the work is done
3509 // when upgrading from version 2
3510 oldVersion++;
3511 }
3512
3513 if (oldVersion == 2) {
3514 createGrantsTable(db);
3515 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
3516 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07003517 oldVersion++;
3518 }
Costin Manolache3348f142009-09-29 18:58:36 -07003519
3520 if (oldVersion == 3) {
3521 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
3522 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
3523 oldVersion++;
3524 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003525
3526 if (oldVersion == 4) {
3527 createSharedAccountsTable(db);
3528 oldVersion++;
3529 }
3530
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003531 if (oldVersion == 5) {
3532 addOldAccountNameColumn(db);
3533 oldVersion++;
3534 }
3535
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003536 if (oldVersion == 6) {
3537 addLastSuccessfullAuthenticatedTimeColumn(db);
3538 oldVersion++;
3539 }
3540
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003541 if (oldVersion == 7) {
3542 addDebugTable(db);
3543 oldVersion++;
3544 }
3545
Amith Yamasani67df64b2012-12-14 12:09:36 -08003546 if (oldVersion != newVersion) {
3547 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
3548 }
Fred Quintana60307342009-03-24 22:48:12 -07003549 }
3550
3551 @Override
3552 public void onOpen(SQLiteDatabase db) {
3553 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
3554 }
3555 }
3556
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003557 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07003558 return asBinder();
3559 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003560
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003561 /**
3562 * Searches array of arguments for the specified string
3563 * @param args array of argument strings
3564 * @param value value to search for
3565 * @return true if the value is contained in the array
3566 */
3567 private static boolean scanArgs(String[] args, String value) {
3568 if (args != null) {
3569 for (String arg : args) {
3570 if (value.equals(arg)) {
3571 return true;
3572 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003573 }
3574 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003575 return false;
3576 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003577
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003578 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003579 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07003580 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3581 != PackageManager.PERMISSION_GRANTED) {
3582 fout.println("Permission Denial: can't dump AccountsManager from from pid="
3583 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3584 + " without permission " + android.Manifest.permission.DUMP);
3585 return;
3586 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003587 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003588 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07003589
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003590 final List<UserInfo> users = getUserManager().getUsers();
3591 for (UserInfo user : users) {
3592 ipw.println("User " + user + ":");
3593 ipw.increaseIndent();
3594 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
3595 ipw.println();
3596 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08003597 }
3598 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003599
Amith Yamasani04e0d262012-02-14 11:50:53 -08003600 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
3601 String[] args, boolean isCheckinRequest) {
3602 synchronized (userAccounts.cacheLock) {
3603 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003604
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003605 if (isCheckinRequest) {
3606 // This is a checkin request. *Only* upload the account types and the count of each.
3607 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
3608 null, null, ACCOUNTS_TYPE, null, null);
3609 try {
3610 while (cursor.moveToNext()) {
3611 // print type,count
3612 fout.println(cursor.getString(0) + "," + cursor.getString(1));
3613 }
3614 } finally {
3615 if (cursor != null) {
3616 cursor.close();
3617 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003618 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003619 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003620 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07003621 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003622 fout.println("Accounts: " + accounts.length);
3623 for (Account account : accounts) {
3624 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003625 }
Fred Quintana307da1a2010-01-21 14:24:20 -08003626
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003627 // Add debug information.
3628 fout.println();
3629 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
3630 null, null, null, null, DebugDbHelper.TIMESTAMP);
3631 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
3632 fout.println("Accounts History");
3633 try {
3634 while (cursor.moveToNext()) {
3635 // print type,count
3636 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
3637 cursor.getString(2) + "," + cursor.getString(3) + ","
3638 + cursor.getString(4) + "," + cursor.getString(5));
3639 }
3640 } finally {
3641 cursor.close();
3642 }
3643
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003644 fout.println();
3645 synchronized (mSessions) {
3646 final long now = SystemClock.elapsedRealtime();
3647 fout.println("Active Sessions: " + mSessions.size());
3648 for (Session session : mSessions.values()) {
3649 fout.println(" " + session.toDebugString(now));
3650 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003651 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003652
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003653 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003654 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003655 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003656 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003657 }
3658
Amith Yamasani04e0d262012-02-14 11:50:53 -08003659 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07003660 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003661 long identityToken = clearCallingIdentity();
3662 try {
3663 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3664 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
3665 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003666
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003667 if (intent.getComponent() != null &&
3668 GrantCredentialsPermissionActivity.class.getName().equals(
3669 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003670 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003671 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003672 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07003673 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003674 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003675 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07003676 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003677 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003678 Notification n = new Notification.Builder(contextForUser)
3679 .setWhen(0)
3680 .setSmallIcon(android.R.drawable.stat_sys_warning)
3681 .setColor(contextForUser.getColor(
3682 com.android.internal.R.color.system_notification_accent_color))
3683 .setContentTitle(String.format(notificationTitleFormat, account.name))
3684 .setContentText(message)
3685 .setContentIntent(PendingIntent.getActivityAsUser(
3686 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
3687 null, user))
3688 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003689 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003690 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003691 } finally {
3692 restoreCallingIdentity(identityToken);
3693 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003694 }
3695
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003696 protected void installNotification(final int notificationId, final Notification n,
3697 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08003698 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003699 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08003700 }
3701
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003702 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003703 long identityToken = clearCallingIdentity();
3704 try {
3705 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003706 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003707 } finally {
3708 restoreCallingIdentity(identityToken);
3709 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003710 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003711
Svetoslavce852dd2015-09-08 14:36:35 -07003712 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
Fred Quintanab38eb142010-02-24 13:40:54 -08003713 for (String perm : permissions) {
3714 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
3715 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003716 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08003717 }
Svetoslavce852dd2015-09-08 14:36:35 -07003718 final int opCode = AppOpsManager.permissionToOpCode(perm);
3719 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
3720 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
3721 return true;
3722 }
Fred Quintanab38eb142010-02-24 13:40:54 -08003723 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003724 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003725 return false;
3726 }
3727
Amith Yamasani67df64b2012-12-14 12:09:36 -08003728 private int handleIncomingUser(int userId) {
3729 try {
3730 return ActivityManagerNative.getDefault().handleIncomingUser(
3731 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
3732 } catch (RemoteException re) {
3733 // Shouldn't happen, local.
3734 }
3735 return userId;
3736 }
3737
Christopher Tateccbf84f2013-05-08 15:25:41 -07003738 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003739 final int callingUserId = UserHandle.getUserId(callingUid);
3740
3741 final PackageManager userPackageManager;
3742 try {
3743 userPackageManager = mContext.createPackageContextAsUser(
3744 "android", 0, new UserHandle(callingUserId)).getPackageManager();
3745 } catch (NameNotFoundException e) {
3746 return false;
3747 }
3748
3749 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07003750 for (String name : packages) {
3751 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003752 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08003753 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003754 && (packageInfo.applicationInfo.privateFlags
3755 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07003756 return true;
3757 }
3758 } catch (PackageManager.NameNotFoundException e) {
3759 return false;
3760 }
3761 }
3762 return false;
3763 }
3764
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003765 private boolean permissionIsGranted(
3766 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07003767 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07003768 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003769 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07003770 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08003771 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003772 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3773 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08003774 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003775 + ": is authenticator? " + fromAuthenticator
3776 + ", has explicit permission? " + hasExplicitGrants);
3777 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07003778 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003779 }
3780
Svetoslavce852dd2015-09-08 14:36:35 -07003781 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
3782 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003783 if (accountType == null) {
3784 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003785 } else {
Svetoslavce852dd2015-09-08 14:36:35 -07003786 return getTypesVisibleToCaller(callingUid, userId,
3787 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003788 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003789 }
3790
3791 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
3792 if (accountType == null) {
3793 return false;
3794 } else {
3795 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
3796 }
3797 }
3798
Svetoslavce852dd2015-09-08 14:36:35 -07003799 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
3800 String opPackageName) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003801 boolean isPermitted =
Svetoslavce852dd2015-09-08 14:36:35 -07003802 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003803 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
3804 Log.i(TAG, String.format("getTypesVisibleToCaller: isPermitted? %s", isPermitted));
3805 return getTypesForCaller(callingUid, userId, isPermitted);
3806 }
3807
3808 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
3809 return getTypesForCaller(callingUid, userId, false);
3810 }
3811
3812 private List<String> getTypesForCaller(
3813 int callingUid, int userId, boolean isOtherwisePermitted) {
3814 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003815 long identityToken = Binder.clearCallingIdentity();
3816 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
3817 try {
3818 serviceInfos = mAuthenticatorCache.getAllServices(userId);
3819 } finally {
3820 Binder.restoreCallingIdentity(identityToken);
3821 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003822 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003823 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003824 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
3825 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
3826 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003827 }
3828 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003829 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003830 }
3831
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003832 private boolean isAccountPresentForCaller(String accountName, String accountType) {
3833 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
3834 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
3835 if (account.name.equals(accountName)) {
3836 return true;
3837 }
3838 }
3839 }
3840 return false;
3841 }
3842
Amith Yamasani04e0d262012-02-14 11:50:53 -08003843 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
3844 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003845 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003846 return true;
3847 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003848 UserAccounts accounts = getUserAccountsForCaller();
3849 synchronized (accounts.cacheLock) {
3850 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3851 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003852 account.name, account.type};
3853 final boolean permissionGranted =
3854 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
3855 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
3856 // TODO: Skip this check when running automated tests. Replace this
3857 // with a more general solution.
3858 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08003859 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003860 + " but ignoring since device is in test harness.");
3861 return true;
3862 }
3863 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003864 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003865 }
3866
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003867 private boolean isSystemUid(int callingUid) {
3868 String[] packages = null;
3869 long ident = Binder.clearCallingIdentity();
3870 try {
3871 packages = mPackageManager.getPackagesForUid(callingUid);
3872 } finally {
3873 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07003874 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003875 if (packages != null) {
3876 for (String name : packages) {
3877 try {
3878 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
3879 if (packageInfo != null
3880 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
3881 != 0) {
3882 return true;
3883 }
3884 } catch (PackageManager.NameNotFoundException e) {
3885 Log.w(TAG, String.format("Could not find package [%s]", name), e);
3886 }
3887 }
3888 } else {
3889 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07003890 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003891 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003892 }
3893
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003894 /** Succeeds if any of the specified permissions are granted. */
3895 private void checkReadAccountsPermitted(
3896 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003897 String accountType,
Svetoslavce852dd2015-09-08 14:36:35 -07003898 int userId,
3899 String opPackageName) {
3900 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003901 String msg = String.format(
3902 "caller uid %s cannot access %s accounts",
3903 callingUid,
3904 accountType);
3905 Log.w(TAG, " " + msg);
3906 throw new SecurityException(msg);
3907 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003908 }
3909
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003910 private boolean canUserModifyAccounts(int userId) {
3911 if (getUserManager().getUserRestrictions(new UserHandle(userId))
3912 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
3913 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003914 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003915 return true;
3916 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003917
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003918 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003919 DevicePolicyManager dpm = (DevicePolicyManager) mContext
3920 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003921 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02003922 if (typesArray == null) {
3923 return true;
3924 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003925 for (String forbiddenType : typesArray) {
3926 if (forbiddenType.equals(accountType)) {
3927 return false;
3928 }
3929 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003930 return true;
3931 }
3932
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003933 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07003934 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
3935 throws RemoteException {
3936 final int callingUid = getCallingUid();
3937
Amith Yamasani27db4682013-03-30 17:07:47 -07003938 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07003939 throw new SecurityException();
3940 }
3941
3942 if (value) {
3943 grantAppPermission(account, authTokenType, uid);
3944 } else {
3945 revokeAppPermission(account, authTokenType, uid);
3946 }
3947 }
3948
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003949 /**
3950 * Allow callers with the given uid permission to get credentials for account/authTokenType.
3951 * <p>
3952 * Although this is public it can only be accessed via the AccountManagerService object
3953 * which is in the system. This means we don't need to protect it with permissions.
3954 * @hide
3955 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003956 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003957 if (account == null || authTokenType == null) {
3958 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003959 return;
3960 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003961 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003962 synchronized (accounts.cacheLock) {
3963 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003964 db.beginTransaction();
3965 try {
3966 long accountId = getAccountIdLocked(db, account);
3967 if (accountId >= 0) {
3968 ContentValues values = new ContentValues();
3969 values.put(GRANTS_ACCOUNTS_ID, accountId);
3970 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
3971 values.put(GRANTS_GRANTEE_UID, uid);
3972 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
3973 db.setTransactionSuccessful();
3974 }
3975 } finally {
3976 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003977 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003978 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3979 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003980 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003981 }
3982
3983 /**
3984 * Don't allow callers with the given uid permission to get credentials for
3985 * account/authTokenType.
3986 * <p>
3987 * Although this is public it can only be accessed via the AccountManagerService object
3988 * which is in the system. This means we don't need to protect it with permissions.
3989 * @hide
3990 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003991 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003992 if (account == null || authTokenType == null) {
3993 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003994 return;
3995 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003996 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003997 synchronized (accounts.cacheLock) {
3998 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003999 db.beginTransaction();
4000 try {
4001 long accountId = getAccountIdLocked(db, account);
4002 if (accountId >= 0) {
4003 db.delete(TABLE_GRANTS,
4004 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
4005 + GRANTS_GRANTEE_UID + "=?",
4006 new String[]{String.valueOf(accountId), authTokenType,
4007 String.valueOf(uid)});
4008 db.setTransactionSuccessful();
4009 }
4010 } finally {
4011 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004012 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004013 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
4014 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004015 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004016 }
Fred Quintana56285a62010-12-02 14:20:51 -08004017
4018 static final private String stringArrayToString(String[] value) {
4019 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
4020 }
4021
Amith Yamasani04e0d262012-02-14 11:50:53 -08004022 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
4023 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004024 if (oldAccountsForType != null) {
4025 ArrayList<Account> newAccountsList = new ArrayList<Account>();
4026 for (Account curAccount : oldAccountsForType) {
4027 if (!curAccount.equals(account)) {
4028 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004029 }
4030 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004031 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004032 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004033 } else {
4034 Account[] newAccountsForType = new Account[newAccountsList.size()];
4035 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004036 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004037 }
Fred Quintana56285a62010-12-02 14:20:51 -08004038 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004039 accounts.userDataCache.remove(account);
4040 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004041 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004042 }
4043
4044 /**
4045 * This assumes that the caller has already checked that the account is not already present.
4046 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08004047 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
4048 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004049 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
4050 Account[] newAccountsForType = new Account[oldLength + 1];
4051 if (accountsForType != null) {
4052 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08004053 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004054 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004055 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08004056 }
4057
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004058 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07004059 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004060 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07004061 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004062 return unfiltered;
4063 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004064 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
4065 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004066 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004067 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004068 // otherwise return non-shared accounts only.
4069 // This might be a temporary way to specify a whitelist
4070 String whiteList = mContext.getResources().getString(
4071 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
4072 for (String packageName : packages) {
4073 if (whiteList.contains(";" + packageName + ";")) {
4074 return unfiltered;
4075 }
4076 }
4077 ArrayList<Account> allowed = new ArrayList<Account>();
4078 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
4079 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004080 String requiredAccountType = "";
4081 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07004082 // If there's an explicit callingPackage specified, check if that package
4083 // opted in to see restricted accounts.
4084 if (callingPackage != null) {
4085 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004086 if (pi != null && pi.restrictedAccountType != null) {
4087 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07004088 }
4089 } else {
4090 // Otherwise check if the callingUid has a package that has opted in
4091 for (String packageName : packages) {
4092 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
4093 if (pi != null && pi.restrictedAccountType != null) {
4094 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07004095 break;
4096 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004097 }
4098 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004099 } catch (NameNotFoundException nnfe) {
4100 }
4101 for (Account account : unfiltered) {
4102 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004103 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004104 } else {
4105 boolean found = false;
4106 for (Account shared : sharedAccounts) {
4107 if (shared.equals(account)) {
4108 found = true;
4109 break;
4110 }
4111 }
4112 if (!found) {
4113 allowed.add(account);
4114 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004115 }
4116 }
4117 Account[] filtered = new Account[allowed.size()];
4118 allowed.toArray(filtered);
4119 return filtered;
4120 } else {
4121 return unfiltered;
4122 }
4123 }
4124
Amith Yamasani27db4682013-03-30 17:07:47 -07004125 /*
4126 * packageName can be null. If not null, it should be used to filter out restricted accounts
4127 * that the package is not allowed to access.
4128 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004129 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07004130 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004131 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004132 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004133 if (accounts == null) {
4134 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08004135 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004136 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07004137 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004138 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004139 } else {
4140 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004141 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004142 totalLength += accounts.length;
4143 }
4144 if (totalLength == 0) {
4145 return EMPTY_ACCOUNT_ARRAY;
4146 }
4147 Account[] accounts = new Account[totalLength];
4148 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004149 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004150 System.arraycopy(accountsOfType, 0, accounts, totalLength,
4151 accountsOfType.length);
4152 totalLength += accountsOfType.length;
4153 }
Amith Yamasani27db4682013-03-30 17:07:47 -07004154 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004155 }
4156 }
4157
Amith Yamasani04e0d262012-02-14 11:50:53 -08004158 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4159 Account account, String key, String value) {
4160 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004161 if (userDataForAccount == null) {
4162 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004163 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004164 }
4165 if (value == null) {
4166 userDataForAccount.remove(key);
4167 } else {
4168 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004169 }
4170 }
4171
Carlos Valdivia91979be2015-05-22 14:11:35 -07004172 protected String readCachedTokenInternal(
4173 UserAccounts accounts,
4174 Account account,
4175 String tokenType,
4176 String callingPackage,
4177 byte[] pkgSigDigest) {
4178 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004179 return accounts.accountTokenCaches.get(
4180 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004181 }
4182 }
4183
Amith Yamasani04e0d262012-02-14 11:50:53 -08004184 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4185 Account account, String key, String value) {
4186 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004187 if (authTokensForAccount == null) {
4188 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004189 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004190 }
4191 if (value == null) {
4192 authTokensForAccount.remove(key);
4193 } else {
4194 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004195 }
4196 }
4197
Amith Yamasani04e0d262012-02-14 11:50:53 -08004198 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
4199 String authTokenType) {
4200 synchronized (accounts.cacheLock) {
4201 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004202 if (authTokensForAccount == null) {
4203 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004204 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004205 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004206 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004207 }
4208 return authTokensForAccount.get(authTokenType);
4209 }
4210 }
4211
Amith Yamasani04e0d262012-02-14 11:50:53 -08004212 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
4213 synchronized (accounts.cacheLock) {
4214 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004215 if (userDataForAccount == null) {
4216 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004217 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004218 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004219 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004220 }
4221 return userDataForAccount.get(key);
4222 }
4223 }
4224
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004225 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
4226 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004227 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004228 Cursor cursor = db.query(TABLE_EXTRAS,
4229 COLUMNS_EXTRAS_KEY_AND_VALUE,
4230 SELECTION_USERDATA_BY_ACCOUNT,
4231 new String[]{account.name, account.type},
4232 null, null, null);
4233 try {
4234 while (cursor.moveToNext()) {
4235 final String tmpkey = cursor.getString(0);
4236 final String value = cursor.getString(1);
4237 userDataForAccount.put(tmpkey, value);
4238 }
4239 } finally {
4240 cursor.close();
4241 }
4242 return userDataForAccount;
4243 }
4244
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004245 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
4246 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004247 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004248 Cursor cursor = db.query(TABLE_AUTHTOKENS,
4249 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
4250 SELECTION_AUTHTOKENS_BY_ACCOUNT,
4251 new String[]{account.name, account.type},
4252 null, null, null);
4253 try {
4254 while (cursor.moveToNext()) {
4255 final String type = cursor.getString(0);
4256 final String authToken = cursor.getString(1);
4257 authTokensForAccount.put(type, authToken);
4258 }
4259 } finally {
4260 cursor.close();
4261 }
4262 return authTokensForAccount;
4263 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004264
4265 private Context getContextForUser(UserHandle user) {
4266 try {
4267 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
4268 } catch (NameNotFoundException e) {
4269 // Default to mContext, not finding the package system is running as is unlikely.
4270 return mContext;
4271 }
4272 }
Fred Quintana60307342009-03-24 22:48:12 -07004273}