blob: a0f9f81a1ddc167e7587ec1522b9d8834a5b12fe [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;
Svetoslavf3f02ac2015-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;
Svetoslavf3f02ac2015-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;
Svetoslavf3f02ac2015-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;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700516 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700517 int parentUserId = UserManager.isSplitSystemUser()
518 ? mUserManager.getUserInfo(userId).restrictedProfileParentId
519 : UserHandle.USER_SYSTEM;
520 if (parentUserId < 0) {
521 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
522 return;
523 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800524 for (Account sa : sharedAccounts) {
525 if (ArrayUtils.contains(accounts, sa)) continue;
526 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700527 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800528 }
529 }
530
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700531 @Override
532 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700533 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700534 }
535
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800536 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700537 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700538 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800539 if (Log.isLoggable(TAG, Log.VERBOSE)) {
540 Log.v(TAG, "getPassword: " + account
541 + ", caller's uid " + Binder.getCallingUid()
542 + ", pid " + Binder.getCallingPid());
543 }
Fred Quintana382601f2010-03-25 12:25:10 -0700544 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000545 int userId = UserHandle.getCallingUserId();
546 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700547 String msg = String.format(
548 "uid %s cannot get secrets for accounts of type: %s",
549 callingUid,
550 account.type);
551 throw new SecurityException(msg);
552 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700553 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700554 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700555 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800556 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700557 } finally {
558 restoreCallingIdentity(identityToken);
559 }
560 }
561
Amith Yamasani04e0d262012-02-14 11:50:53 -0800562 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700563 if (account == null) {
564 return null;
565 }
566
Amith Yamasani04e0d262012-02-14 11:50:53 -0800567 synchronized (accounts.cacheLock) {
568 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800569 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
570 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
571 new String[]{account.name, account.type}, null, null, null);
572 try {
573 if (cursor.moveToNext()) {
574 return cursor.getString(0);
575 }
576 return null;
577 } finally {
578 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700579 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700580 }
581 }
582
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800583 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700584 public String getPreviousName(Account account) {
585 if (Log.isLoggable(TAG, Log.VERBOSE)) {
586 Log.v(TAG, "getPreviousName: " + account
587 + ", caller's uid " + Binder.getCallingUid()
588 + ", pid " + Binder.getCallingPid());
589 }
590 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700591 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700592 long identityToken = clearCallingIdentity();
593 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700594 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700595 return readPreviousNameInternal(accounts, account);
596 } finally {
597 restoreCallingIdentity(identityToken);
598 }
599 }
600
601 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
602 if (account == null) {
603 return null;
604 }
605 synchronized (accounts.cacheLock) {
606 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
607 if (previousNameRef == null) {
608 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
609 Cursor cursor = db.query(
610 TABLE_ACCOUNTS,
611 new String[]{ ACCOUNTS_PREVIOUS_NAME },
612 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
613 new String[] { account.name, account.type },
614 null,
615 null,
616 null);
617 try {
618 if (cursor.moveToNext()) {
619 String previousName = cursor.getString(0);
620 previousNameRef = new AtomicReference<String>(previousName);
621 accounts.previousNameCache.put(account, previousNameRef);
622 return previousName;
623 } else {
624 return null;
625 }
626 } finally {
627 cursor.close();
628 }
629 } else {
630 return previousNameRef.get();
631 }
632 }
633 }
634
635 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700636 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700637 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800638 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700639 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
640 account, key, callingUid, Binder.getCallingPid());
641 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800642 }
Fred Quintana382601f2010-03-25 12:25:10 -0700643 if (account == null) throw new IllegalArgumentException("account is null");
644 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000645 int userId = UserHandle.getCallingUserId();
646 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700647 String msg = String.format(
648 "uid %s cannot get user data for accounts of type: %s",
649 callingUid,
650 account.type);
651 throw new SecurityException(msg);
652 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700653 long identityToken = clearCallingIdentity();
654 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700655 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800656 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700657 } finally {
658 restoreCallingIdentity(identityToken);
659 }
660 }
661
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800662 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100663 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700664 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800665 if (Log.isLoggable(TAG, Log.VERBOSE)) {
666 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100667 + "for user id " + userId
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700668 + "caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800669 + ", pid " + Binder.getCallingPid());
670 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100671 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700672 if (isCrossUser(callingUid, userId)) {
673 throw new SecurityException(
674 String.format(
675 "User %s tying to get authenticator types for %s" ,
676 UserHandle.getCallingUserId(),
677 userId));
678 }
679
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700680 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700681 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000682 return getAuthenticatorTypesInternal(userId);
683
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700684 } finally {
685 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700686 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700687 }
688
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000689 /**
690 * Should only be called inside of a clearCallingIdentity block.
691 */
692 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
693 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
694 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
695 AuthenticatorDescription[] types =
696 new AuthenticatorDescription[authenticatorCollection.size()];
697 int i = 0;
698 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
699 : authenticatorCollection) {
700 types[i] = authenticator.type;
701 i++;
702 }
703 return types;
704 }
705
706
707
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700708 private boolean isCrossUser(int callingUid, int userId) {
709 return (userId != UserHandle.getCallingUserId()
710 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100711 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700712 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
713 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100714 }
715
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700716 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700717 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700718 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800719 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700720 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700721 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800722 + ", pid " + Binder.getCallingPid());
723 }
Fred Quintana382601f2010-03-25 12:25:10 -0700724 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000725 int userId = UserHandle.getCallingUserId();
726 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700727 String msg = String.format(
728 "uid %s cannot explicitly add accounts of type: %s",
729 callingUid,
730 account.type);
731 throw new SecurityException(msg);
732 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700733 /*
734 * Child users are not allowed to add accounts. Only the accounts that are
735 * shared by the parent profile can be added to child profile.
736 *
737 * TODO: Only allow accounts that were shared to be added by
738 * a limited user.
739 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700740
Fred Quintana60307342009-03-24 22:48:12 -0700741 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700742 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700743 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700744 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000745 return addAccountInternal(accounts, account, password, extras, false, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700746 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700747 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700748 }
749 }
750
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000751 @Override
752 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700753 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700754 int callingUid = Binder.getCallingUid();
755 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
756 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000757 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700758 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800759 final UserAccounts fromAccounts = getUserAccounts(userFrom);
760 final UserAccounts toAccounts = getUserAccounts(userTo);
761 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000762 if (response != null) {
763 Bundle result = new Bundle();
764 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
765 try {
766 response.onResult(result);
767 } catch (RemoteException e) {
768 Slog.w(TAG, "Failed to report error back to the client." + e);
769 }
770 }
771 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800772 }
773
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000774 Slog.d(TAG, "Copying account " + account.name
775 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800776 long identityToken = clearCallingIdentity();
777 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000778 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800779 false /* stripAuthTokenFromResult */, account.name,
780 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700781 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800782 protected String toDebugString(long now) {
783 return super.toDebugString(now) + ", getAccountCredentialsForClone"
784 + ", " + account.type;
785 }
786
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700787 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800788 public void run() throws RemoteException {
789 mAuthenticator.getAccountCredentialsForCloning(this, account);
790 }
791
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700792 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800793 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000794 if (result != null
795 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
796 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700797 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800798 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800799 super.onResult(result);
800 }
801 }
802 }.bind();
803 } finally {
804 restoreCallingIdentity(identityToken);
805 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800806 }
807
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800808 @Override
809 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700810 final int callingUid = Binder.getCallingUid();
811 if (Log.isLoggable(TAG, Log.VERBOSE)) {
812 String msg = String.format(
813 "accountAuthenticated( account: %s, callerUid: %s)",
814 account,
815 callingUid);
816 Log.v(TAG, msg);
817 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800818 if (account == null) {
819 throw new IllegalArgumentException("account is null");
820 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000821 int userId = UserHandle.getCallingUserId();
822 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700823 String msg = String.format(
824 "uid %s cannot notify authentication for accounts of type: %s",
825 callingUid,
826 account.type);
827 throw new SecurityException(msg);
828 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000829
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800830 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
831 return false;
832 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000833
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700834 long identityToken = clearCallingIdentity();
835 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000836 UserAccounts accounts = getUserAccounts(userId);
837 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700838 } finally {
839 restoreCallingIdentity(identityToken);
840 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -0700841 }
842
843 private boolean updateLastAuthenticatedTime(Account account) {
844 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800845 synchronized (accounts.cacheLock) {
846 final ContentValues values = new ContentValues();
847 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
848 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
849 int i = db.update(
850 TABLE_ACCOUNTS,
851 values,
852 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
853 new String[] {
854 account.name, account.type
855 });
856 if (i > 0) {
857 return true;
858 }
859 }
860 return false;
861 }
862
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000863 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700864 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
865 final int parentUserId){
Amith Yamasani67df64b2012-12-14 12:09:36 -0800866 long id = clearCallingIdentity();
867 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000868 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800869 false /* stripAuthTokenFromResult */, account.name,
870 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700871 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800872 protected String toDebugString(long now) {
873 return super.toDebugString(now) + ", getAccountCredentialsForClone"
874 + ", " + account.type;
875 }
876
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700877 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800878 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700879 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700880 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700881 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700882 for (Account acc : getAccounts(parentUserId,
883 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700884 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000885 mAuthenticator.addAccountFromCredentials(
886 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700887 break;
888 }
889 }
890 }
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 onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000895 // TODO: Anything to do if if succedded?
896 // TODO: If it failed: Show error notification? Should we remove the shadow
897 // account to avoid retries?
898 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800899 }
900
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700901 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800902 public void onError(int errorCode, String errorMessage) {
903 super.onError(errorCode, errorMessage);
904 // TODO: Show error notification to user
905 // TODO: Should we remove the shadow account so that it doesn't keep trying?
906 }
907
908 }.bind();
909 } finally {
910 restoreCallingIdentity(id);
911 }
912 }
913
Amith Yamasani04e0d262012-02-14 11:50:53 -0800914 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700915 Bundle extras, boolean restricted, int callingUid) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700916 if (account == null) {
917 return false;
918 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800919 synchronized (accounts.cacheLock) {
920 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800921 db.beginTransaction();
922 try {
923 long numMatches = DatabaseUtils.longForQuery(db,
924 "select count(*) from " + TABLE_ACCOUNTS
925 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
926 new String[]{account.name, account.type});
927 if (numMatches > 0) {
928 Log.w(TAG, "insertAccountIntoDatabase: " + account
929 + ", skipping since the account already exists");
930 return false;
931 }
932 ContentValues values = new ContentValues();
933 values.put(ACCOUNTS_NAME, account.name);
934 values.put(ACCOUNTS_TYPE, account.type);
935 values.put(ACCOUNTS_PASSWORD, password);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800936 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800937 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
938 if (accountId < 0) {
939 Log.w(TAG, "insertAccountIntoDatabase: " + account
940 + ", skipping the DB insert failed");
941 return false;
942 }
943 if (extras != null) {
944 for (String key : extras.keySet()) {
945 final String value = extras.getString(key);
946 if (insertExtraLocked(db, accountId, key, value) < 0) {
947 Log.w(TAG, "insertAccountIntoDatabase: " + account
948 + ", skipping since insertExtra failed for key " + key);
949 return false;
950 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700951 }
952 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800953 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700954
955 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
956 accounts, callingUid);
957
Amith Yamasani04e0d262012-02-14 11:50:53 -0800958 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800959 } finally {
960 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700961 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800962 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700963 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700964 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
965 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700966 }
967 return true;
968 }
969
970 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700971 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -0700972 * running, then clone the account too.
973 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700974 *
Amith Yamasani5be347b2013-03-31 17:44:31 -0700975 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700976 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700977 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700978 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700979 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700980 addSharedAccountAsUser(account, user.id);
981 try {
982 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
983 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700984 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -0700985 }
986 } catch (RemoteException re) {
987 // Shouldn't happen
988 }
989 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700990 }
991 }
992
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800993 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700994 ContentValues values = new ContentValues();
995 values.put(EXTRAS_KEY, key);
996 values.put(EXTRAS_ACCOUNTS_ID, accountId);
997 values.put(EXTRAS_VALUE, value);
998 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
999 }
1000
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001001 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001002 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001003 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001004 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001005 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1006 Log.v(TAG, "hasFeatures: " + account
1007 + ", response " + response
1008 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001009 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001010 + ", pid " + Binder.getCallingPid());
1011 }
Fred Quintana382601f2010-03-25 12:25:10 -07001012 if (response == null) throw new IllegalArgumentException("response is null");
1013 if (account == null) throw new IllegalArgumentException("account is null");
1014 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001015 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001016 checkReadAccountsPermitted(callingUid, account.type, userId,
1017 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001018
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001019 long identityToken = clearCallingIdentity();
1020 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001021 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001022 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001023 } finally {
1024 restoreCallingIdentity(identityToken);
1025 }
1026 }
1027
1028 private class TestFeaturesSession extends Session {
1029 private final String[] mFeatures;
1030 private final Account mAccount;
1031
Amith Yamasani04e0d262012-02-14 11:50:53 -08001032 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001033 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001034 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001035 true /* stripAuthTokenFromResult */, account.name,
1036 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001037 mFeatures = features;
1038 mAccount = account;
1039 }
1040
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001041 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001042 public void run() throws RemoteException {
1043 try {
1044 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1045 } catch (RemoteException e) {
1046 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1047 }
1048 }
1049
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001050 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001051 public void onResult(Bundle result) {
1052 IAccountManagerResponse response = getResponseAndClose();
1053 if (response != null) {
1054 try {
1055 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001056 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001057 return;
1058 }
Fred Quintana56285a62010-12-02 14:20:51 -08001059 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1060 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1061 + response);
1062 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001063 final Bundle newResult = new Bundle();
1064 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1065 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1066 response.onResult(newResult);
1067 } catch (RemoteException e) {
1068 // if the caller is dead then there is no one to care about remote exceptions
1069 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1070 Log.v(TAG, "failure while notifying response", e);
1071 }
1072 }
1073 }
1074 }
1075
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001076 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001077 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001078 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001079 + ", " + mAccount
1080 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1081 }
1082 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001083
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001084 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001085 public void renameAccount(
1086 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001087 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001088 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1089 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001090 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001091 + ", pid " + Binder.getCallingPid());
1092 }
1093 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001094 int userId = UserHandle.getCallingUserId();
1095 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001096 String msg = String.format(
1097 "uid %s cannot rename accounts of type: %s",
1098 callingUid,
1099 accountToRename.type);
1100 throw new SecurityException(msg);
1101 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001102 long identityToken = clearCallingIdentity();
1103 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001104 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001105 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001106 Bundle result = new Bundle();
1107 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1108 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1109 try {
1110 response.onResult(result);
1111 } catch (RemoteException e) {
1112 Log.w(TAG, e.getMessage());
1113 }
1114 } finally {
1115 restoreCallingIdentity(identityToken);
1116 }
1117 }
1118
1119 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001120 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001121 Account resultAccount = null;
1122 /*
1123 * Cancel existing notifications. Let authenticators
1124 * re-post notifications as required. But we don't know if
1125 * the authenticators have bound their notifications to
1126 * now stale account name data.
1127 *
1128 * With a rename api, we might not need to do this anymore but it
1129 * shouldn't hurt.
1130 */
1131 cancelNotification(
1132 getSigninRequiredNotificationId(accounts, accountToRename),
1133 new UserHandle(accounts.userId));
1134 synchronized(accounts.credentialsPermissionNotificationIds) {
1135 for (Pair<Pair<Account, String>, Integer> pair:
1136 accounts.credentialsPermissionNotificationIds.keySet()) {
1137 if (accountToRename.equals(pair.first.first)) {
1138 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1139 cancelNotification(id, new UserHandle(accounts.userId));
1140 }
1141 }
1142 }
1143 synchronized (accounts.cacheLock) {
1144 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1145 db.beginTransaction();
1146 boolean isSuccessful = false;
1147 Account renamedAccount = new Account(newName, accountToRename.type);
1148 try {
1149 final ContentValues values = new ContentValues();
1150 values.put(ACCOUNTS_NAME, newName);
1151 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
1152 final long accountId = getAccountIdLocked(db, accountToRename);
1153 if (accountId >= 0) {
1154 final String[] argsAccountId = { String.valueOf(accountId) };
1155 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1156 db.setTransactionSuccessful();
1157 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001158 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1159 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001160 }
1161 } finally {
1162 db.endTransaction();
1163 if (isSuccessful) {
1164 /*
1165 * Database transaction was successful. Clean up cached
1166 * data associated with the account in the user profile.
1167 */
1168 insertAccountIntoCacheLocked(accounts, renamedAccount);
1169 /*
1170 * Extract the data and token caches before removing the
1171 * old account to preserve the user data associated with
1172 * the account.
1173 */
1174 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1175 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1176 removeAccountFromCacheLocked(accounts, accountToRename);
1177 /*
1178 * Update the cached data associated with the renamed
1179 * account.
1180 */
1181 accounts.userDataCache.put(renamedAccount, tmpData);
1182 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1183 accounts.previousNameCache.put(
1184 renamedAccount,
1185 new AtomicReference<String>(accountToRename.name));
1186 resultAccount = renamedAccount;
1187
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001188 int parentUserId = accounts.userId;
1189 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001190 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001191 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001192 * those users with which the account was shared.
1193 */
1194 List<UserInfo> users = mUserManager.getUsers(true);
1195 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001196 if (user.isRestricted()
1197 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001198 renameSharedAccountAsUser(accountToRename, newName, user.id);
1199 }
1200 }
1201 }
1202 sendAccountsChangedBroadcast(accounts.userId);
1203 }
1204 }
1205 }
1206 return resultAccount;
1207 }
1208
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001209 private boolean canHaveProfile(final int parentUserId) {
1210 final UserInfo userInfo = mUserManager.getUserInfo(parentUserId);
1211 return userInfo != null && userInfo.canHaveProfile();
1212 }
1213
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001214 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001215 public void removeAccount(IAccountManagerResponse response, Account account,
1216 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001217 removeAccountAsUser(
1218 response,
1219 account,
1220 expectActivityLaunch,
1221 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001222 }
1223
1224 @Override
1225 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001226 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001227 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001228 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1229 Log.v(TAG, "removeAccount: " + account
1230 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001231 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001232 + ", pid " + Binder.getCallingPid()
1233 + ", for user id " + userId);
1234 }
1235 if (response == null) throw new IllegalArgumentException("response is null");
1236 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001237 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001238 if (isCrossUser(callingUid, userId)) {
1239 throw new SecurityException(
1240 String.format(
1241 "User %s tying remove account for %s" ,
1242 UserHandle.getCallingUserId(),
1243 userId));
1244 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001245 /*
1246 * Only the system or authenticator should be allowed to remove accounts for that
1247 * authenticator. This will let users remove accounts (via Settings in the system) but not
1248 * arbitrary applications (like competing authenticators).
1249 */
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001250 UserHandle user = new UserHandle(userId);
1251 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1252 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001253 String msg = String.format(
1254 "uid %s cannot remove accounts of type: %s",
1255 callingUid,
1256 account.type);
1257 throw new SecurityException(msg);
1258 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001259 if (!canUserModifyAccounts(userId)) {
1260 try {
1261 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1262 "User cannot modify accounts");
1263 } catch (RemoteException re) {
1264 }
1265 return;
1266 }
1267 if (!canUserModifyAccountsForType(userId, account.type)) {
1268 try {
1269 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1270 "User cannot modify accounts of this type (policy).");
1271 } catch (RemoteException re) {
1272 }
1273 return;
1274 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001275 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001276 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001277 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001278 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001279 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001280 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001281 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001282 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001283 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001284 }
1285 }
1286 }
1287
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001288 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1289
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001290 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001291 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1292 } finally {
1293 restoreCallingIdentity(identityToken);
1294 }
1295 }
1296
1297 @Override
1298 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001299 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001300 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1301 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001302 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001303 + ", pid " + Binder.getCallingPid());
1304 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001305 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001306 if (account == null) {
1307 /*
1308 * Null accounts should result in returning false, as per
1309 * AccountManage.addAccountExplicitly(...) java doc.
1310 */
1311 Log.e(TAG, "account is null");
1312 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001313 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001314 String msg = String.format(
1315 "uid %s cannot explicitly add accounts of type: %s",
1316 callingUid,
1317 account.type);
1318 throw new SecurityException(msg);
1319 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001320 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001321 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
1322 return false;
1323 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001324 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001325 long identityToken = clearCallingIdentity();
1326 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001327 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001328 } finally {
1329 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001330 }
Fred Quintana60307342009-03-24 22:48:12 -07001331 }
1332
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001333 private class RemoveAccountSession extends Session {
1334 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001335 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001336 Account account, boolean expectActivityLaunch) {
1337 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001338 true /* stripAuthTokenFromResult */, account.name,
1339 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001340 mAccount = account;
1341 }
1342
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001343 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001344 protected String toDebugString(long now) {
1345 return super.toDebugString(now) + ", removeAccount"
1346 + ", account " + mAccount;
1347 }
1348
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001349 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001350 public void run() throws RemoteException {
1351 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1352 }
1353
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001354 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001355 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001356 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1357 && !result.containsKey(AccountManager.KEY_INTENT)) {
1358 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001359 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001360 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001361 }
1362 IAccountManagerResponse response = getResponseAndClose();
1363 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001364 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1365 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1366 + response);
1367 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001368 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001369 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001370 try {
1371 response.onResult(result2);
1372 } catch (RemoteException e) {
1373 // ignore
1374 }
1375 }
1376 }
1377 super.onResult(result);
1378 }
1379 }
1380
Amith Yamasani04e0d262012-02-14 11:50:53 -08001381 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001382 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001383 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001384 }
1385
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001386 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001387 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001388 synchronized (accounts.cacheLock) {
1389 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001390 final long accountId = getAccountIdLocked(db, account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001391 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1392 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001393 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001394 removeAccountFromCacheLocked(accounts, account);
1395 sendAccountsChangedBroadcast(accounts.userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001396
1397 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001398 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001399 long id = Binder.clearCallingIdentity();
1400 try {
1401 int parentUserId = accounts.userId;
1402 if (canHaveProfile(parentUserId)) {
1403 // Remove from any restricted profiles that are sharing this account.
Amith Yamasani67df64b2012-12-14 12:09:36 -08001404 List<UserInfo> users = mUserManager.getUsers(true);
1405 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001406 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001407 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001408 }
1409 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001410 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001411 } finally {
1412 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001413 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001414 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001415 }
1416
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001417 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001418 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001419 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001420 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1421 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001422 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001423 + ", pid " + Binder.getCallingPid());
1424 }
Fred Quintana382601f2010-03-25 12:25:10 -07001425 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1426 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001427 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001428 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001429 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001430 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001431 synchronized (accounts.cacheLock) {
1432 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001433 db.beginTransaction();
1434 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001435 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001436 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001437 db.setTransactionSuccessful();
1438 } finally {
1439 db.endTransaction();
1440 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001441 }
Fred Quintana60307342009-03-24 22:48:12 -07001442 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001443 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001444 }
1445 }
1446
Carlos Valdivia91979be2015-05-22 14:11:35 -07001447 private void invalidateCustomTokenLocked(
1448 UserAccounts accounts,
1449 String accountType,
1450 String authToken) {
1451 if (authToken == null || accountType == null) {
1452 return;
1453 }
1454 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001455 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001456 }
1457
Amith Yamasani04e0d262012-02-14 11:50:53 -08001458 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1459 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001460 if (authToken == null || accountType == null) {
1461 return;
1462 }
Fred Quintana33269202009-04-20 16:05:10 -07001463 Cursor cursor = db.rawQuery(
1464 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1465 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1466 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1467 + " FROM " + TABLE_ACCOUNTS
1468 + " JOIN " + TABLE_AUTHTOKENS
1469 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1470 + " = " + AUTHTOKENS_ACCOUNTS_ID
1471 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1472 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1473 new String[]{authToken, accountType});
1474 try {
1475 while (cursor.moveToNext()) {
1476 long authTokenId = cursor.getLong(0);
1477 String accountName = cursor.getString(1);
1478 String authTokenType = cursor.getString(2);
1479 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001480 writeAuthTokenIntoCacheLocked(
1481 accounts,
1482 db,
1483 new Account(accountName, accountType),
1484 authTokenType,
1485 null);
Fred Quintana60307342009-03-24 22:48:12 -07001486 }
Fred Quintana33269202009-04-20 16:05:10 -07001487 } finally {
1488 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001489 }
1490 }
1491
Carlos Valdivia91979be2015-05-22 14:11:35 -07001492 private void saveCachedToken(
1493 UserAccounts accounts,
1494 Account account,
1495 String callerPkg,
1496 byte[] callerSigDigest,
1497 String tokenType,
1498 String token,
1499 long expiryMillis) {
1500
1501 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1502 return;
1503 }
1504 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1505 new UserHandle(accounts.userId));
1506 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001507 accounts.accountTokenCaches.put(
1508 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001509 }
1510 }
1511
Amith Yamasani04e0d262012-02-14 11:50:53 -08001512 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1513 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001514 if (account == null || type == null) {
1515 return false;
1516 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001517 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1518 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001519 synchronized (accounts.cacheLock) {
1520 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001521 db.beginTransaction();
1522 try {
1523 long accountId = getAccountIdLocked(db, account);
1524 if (accountId < 0) {
1525 return false;
1526 }
1527 db.delete(TABLE_AUTHTOKENS,
1528 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1529 new String[]{type});
1530 ContentValues values = new ContentValues();
1531 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1532 values.put(AUTHTOKENS_TYPE, type);
1533 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1534 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1535 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001536 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001537 return true;
1538 }
Fred Quintana33269202009-04-20 16:05:10 -07001539 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001540 } finally {
1541 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001542 }
Fred Quintana60307342009-03-24 22:48:12 -07001543 }
1544 }
1545
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001546 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001547 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001548 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001549 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1550 Log.v(TAG, "peekAuthToken: " + account
1551 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001552 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001553 + ", pid " + Binder.getCallingPid());
1554 }
Fred Quintana382601f2010-03-25 12:25:10 -07001555 if (account == null) throw new IllegalArgumentException("account is null");
1556 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001557 int userId = UserHandle.getCallingUserId();
1558 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001559 String msg = String.format(
1560 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1561 callingUid,
1562 account.type);
1563 throw new SecurityException(msg);
1564 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001565 long identityToken = clearCallingIdentity();
1566 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001567 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001568 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001569 } finally {
1570 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001571 }
Fred Quintana60307342009-03-24 22:48:12 -07001572 }
1573
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001574 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001575 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001576 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001577 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1578 Log.v(TAG, "setAuthToken: " + account
1579 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001580 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001581 + ", pid " + Binder.getCallingPid());
1582 }
Fred Quintana382601f2010-03-25 12:25:10 -07001583 if (account == null) throw new IllegalArgumentException("account is null");
1584 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001585 int userId = UserHandle.getCallingUserId();
1586 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001587 String msg = String.format(
1588 "uid %s cannot set auth tokens associated with accounts of type: %s",
1589 callingUid,
1590 account.type);
1591 throw new SecurityException(msg);
1592 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001593 long identityToken = clearCallingIdentity();
1594 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001595 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001596 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001597 } finally {
1598 restoreCallingIdentity(identityToken);
1599 }
Fred Quintana60307342009-03-24 22:48:12 -07001600 }
1601
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001602 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001603 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001604 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001605 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1606 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001607 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001608 + ", pid " + Binder.getCallingPid());
1609 }
Fred Quintana382601f2010-03-25 12:25:10 -07001610 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001611 int userId = UserHandle.getCallingUserId();
1612 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001613 String msg = String.format(
1614 "uid %s cannot set secrets for accounts of type: %s",
1615 callingUid,
1616 account.type);
1617 throw new SecurityException(msg);
1618 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001619 long identityToken = clearCallingIdentity();
1620 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001621 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001622 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001623 } finally {
1624 restoreCallingIdentity(identityToken);
1625 }
Fred Quintana60307342009-03-24 22:48:12 -07001626 }
1627
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001628 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1629 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001630 if (account == null) {
1631 return;
1632 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001633 synchronized (accounts.cacheLock) {
1634 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001635 db.beginTransaction();
1636 try {
1637 final ContentValues values = new ContentValues();
1638 values.put(ACCOUNTS_PASSWORD, password);
1639 final long accountId = getAccountIdLocked(db, account);
1640 if (accountId >= 0) {
1641 final String[] argsAccountId = {String.valueOf(accountId)};
1642 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1643 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001644 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001645 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001646 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001647
1648 String action = (password == null || password.length() == 0) ?
1649 DebugDbHelper.ACTION_CLEAR_PASSWORD
1650 : DebugDbHelper.ACTION_SET_PASSWORD;
1651 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001652 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001653 } finally {
1654 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001655 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001656 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001657 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001658 }
1659
Amith Yamasani04e0d262012-02-14 11:50:53 -08001660 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001661 Log.i(TAG, "the accounts changed, sending broadcast of "
1662 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001663 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001664 }
1665
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001666 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001667 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001668 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001669 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1670 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001671 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001672 + ", pid " + Binder.getCallingPid());
1673 }
Fred Quintana382601f2010-03-25 12:25:10 -07001674 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001675 int userId = UserHandle.getCallingUserId();
1676 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001677 String msg = String.format(
1678 "uid %s cannot clear passwords for accounts of type: %s",
1679 callingUid,
1680 account.type);
1681 throw new SecurityException(msg);
1682 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001683 long identityToken = clearCallingIdentity();
1684 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001685 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001686 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001687 } finally {
1688 restoreCallingIdentity(identityToken);
1689 }
Fred Quintana60307342009-03-24 22:48:12 -07001690 }
1691
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001692 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001693 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001694 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001695 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1696 Log.v(TAG, "setUserData: " + account
1697 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001698 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001699 + ", pid " + Binder.getCallingPid());
1700 }
Fred Quintana382601f2010-03-25 12:25:10 -07001701 if (key == null) throw new IllegalArgumentException("key is null");
1702 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001703 int userId = UserHandle.getCallingUserId();
1704 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001705 String msg = String.format(
1706 "uid %s cannot set user data for accounts of type: %s",
1707 callingUid,
1708 account.type);
1709 throw new SecurityException(msg);
1710 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001711 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001712 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001713 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001714 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001715 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001716 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001717 }
1718 }
1719
Amith Yamasani04e0d262012-02-14 11:50:53 -08001720 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1721 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001722 if (account == null || key == null) {
1723 return;
1724 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001725 synchronized (accounts.cacheLock) {
1726 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001727 db.beginTransaction();
1728 try {
1729 long accountId = getAccountIdLocked(db, account);
1730 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001731 return;
1732 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001733 long extrasId = getExtrasIdLocked(db, accountId, key);
1734 if (extrasId < 0 ) {
1735 extrasId = insertExtraLocked(db, accountId, key, value);
1736 if (extrasId < 0) {
1737 return;
1738 }
1739 } else {
1740 ContentValues values = new ContentValues();
1741 values.put(EXTRAS_VALUE, value);
1742 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1743 return;
1744 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001745
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001746 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001747 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001748 db.setTransactionSuccessful();
1749 } finally {
1750 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001751 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001752 }
1753 }
1754
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001755 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001756 if (result == null) {
1757 Log.e(TAG, "the result is unexpectedly null", new Exception());
1758 }
1759 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1760 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1761 + response);
1762 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001763 try {
1764 response.onResult(result);
1765 } catch (RemoteException e) {
1766 // if the caller is dead then there is no one to care about remote
1767 // exceptions
1768 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1769 Log.v(TAG, "failure while notifying response", e);
1770 }
1771 }
1772 }
1773
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001774 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001775 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1776 final String authTokenType)
1777 throws RemoteException {
1778 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001779 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1780
Fred Quintanad9640ec2012-05-23 12:37:00 -07001781 final int callingUid = getCallingUid();
1782 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001783 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001784 throw new SecurityException("can only call from system");
1785 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001786 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001787 long identityToken = clearCallingIdentity();
1788 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001789 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001790 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1791 false /* stripAuthTokenFromResult */, null /* accountName */,
1792 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001793 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001794 protected String toDebugString(long now) {
1795 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001796 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001797 + ", authTokenType " + authTokenType;
1798 }
1799
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001800 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001801 public void run() throws RemoteException {
1802 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1803 }
1804
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001805 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001806 public void onResult(Bundle result) {
1807 if (result != null) {
1808 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1809 Bundle bundle = new Bundle();
1810 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1811 super.onResult(bundle);
1812 return;
1813 } else {
1814 super.onResult(result);
1815 }
1816 }
1817 }.bind();
1818 } finally {
1819 restoreCallingIdentity(identityToken);
1820 }
1821 }
1822
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001823 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07001824 public void getAuthToken(
1825 IAccountManagerResponse response,
1826 final Account account,
1827 final String authTokenType,
1828 final boolean notifyOnAuthFailure,
1829 final boolean expectActivityLaunch,
1830 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001831 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1832 Log.v(TAG, "getAuthToken: " + account
1833 + ", response " + response
1834 + ", authTokenType " + authTokenType
1835 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1836 + ", expectActivityLaunch " + expectActivityLaunch
1837 + ", caller's uid " + Binder.getCallingUid()
1838 + ", pid " + Binder.getCallingPid());
1839 }
Fred Quintana382601f2010-03-25 12:25:10 -07001840 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001841 try {
1842 if (account == null) {
1843 Slog.w(TAG, "getAuthToken called with null account");
1844 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1845 return;
1846 }
1847 if (authTokenType == null) {
1848 Slog.w(TAG, "getAuthToken called with null authTokenType");
1849 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1850 return;
1851 }
1852 } catch (RemoteException e) {
1853 Slog.w(TAG, "Failed to report error back to the client." + e);
1854 return;
1855 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001856 int userId = UserHandle.getCallingUserId();
1857 long ident = Binder.clearCallingIdentity();
1858 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001859 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001860 try {
1861 accounts = getUserAccounts(userId);
1862 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1863 AuthenticatorDescription.newKey(account.type), accounts.userId);
1864 } finally {
1865 Binder.restoreCallingIdentity(ident);
1866 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001867
Costin Manolachea40c6302010-12-13 14:50:45 -08001868 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07001869 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08001870
1871 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001872 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001873 final boolean permissionGranted =
1874 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001875
Carlos Valdivia91979be2015-05-22 14:11:35 -07001876 // Get the calling package. We will use it for the purpose of caching.
1877 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07001878 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001879 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07001880 try {
1881 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
1882 } finally {
1883 Binder.restoreCallingIdentity(ident);
1884 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001885 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
1886 String msg = String.format(
1887 "Uid %s is attempting to illegally masquerade as package %s!",
1888 callerUid,
1889 callerPkg);
1890 throw new SecurityException(msg);
1891 }
1892
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001893 // let authenticator know the identity of the caller
1894 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1895 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07001896
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001897 if (notifyOnAuthFailure) {
1898 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001899 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001900
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001901 long identityToken = clearCallingIdentity();
1902 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07001903 // Distill the caller's package signatures into a single digest.
1904 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
1905
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001906 // if the caller has permission, do the peek. otherwise go the more expensive
1907 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001908 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001909 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001910 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001911 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001912 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1913 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1914 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001915 onResult(response, result);
1916 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001917 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001918 }
1919
Carlos Valdivia91979be2015-05-22 14:11:35 -07001920 if (customTokens) {
1921 /*
1922 * Look up tokens in the new cache only if the loginOptions don't have parameters
1923 * outside of those expected to be injected by the AccountManager, e.g.
1924 * ANDORID_PACKAGE_NAME.
1925 */
1926 String token = readCachedTokenInternal(
1927 accounts,
1928 account,
1929 authTokenType,
1930 callerPkg,
1931 callerPkgSigDigest);
1932 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001933 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1934 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
1935 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001936 Bundle result = new Bundle();
1937 result.putString(AccountManager.KEY_AUTHTOKEN, token);
1938 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1939 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
1940 onResult(response, result);
1941 return;
1942 }
1943 }
1944
Amith Yamasani04e0d262012-02-14 11:50:53 -08001945 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001946 false /* stripAuthTokenFromResult */, account.name,
1947 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001948 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001949 protected String toDebugString(long now) {
1950 if (loginOptions != null) loginOptions.keySet();
1951 return super.toDebugString(now) + ", getAuthToken"
1952 + ", " + account
1953 + ", authTokenType " + authTokenType
1954 + ", loginOptions " + loginOptions
1955 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1956 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001957
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001958 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001959 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001960 // If the caller doesn't have permission then create and return the
1961 // "grant permission" intent instead of the "getAuthToken" intent.
1962 if (!permissionGranted) {
1963 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1964 } else {
1965 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1966 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001967 }
1968
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001969 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001970 public void onResult(Bundle result) {
1971 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001972 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001973 Intent intent = newGrantCredentialsPermissionIntent(
1974 account,
1975 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001976 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001977 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001978 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001979 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001980 onResult(bundle);
1981 return;
1982 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001983 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001984 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001985 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1986 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001987 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001988 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001989 "the type and name should not be empty");
1990 return;
1991 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001992 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08001993 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001994 saveAuthTokenToDatabase(
1995 mAccounts,
1996 resultAccount,
1997 authTokenType,
1998 authToken);
1999 }
2000 long expiryMillis = result.getLong(
2001 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2002 if (customTokens
2003 && expiryMillis > System.currentTimeMillis()) {
2004 saveCachedToken(
2005 mAccounts,
2006 account,
2007 callerPkg,
2008 callerPkgSigDigest,
2009 authTokenType,
2010 authToken,
2011 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002012 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002013 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002014
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002015 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002016 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002017 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002018 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002019 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002020 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002021 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002022 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002023 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002024 }.bind();
2025 } finally {
2026 restoreCallingIdentity(identityToken);
2027 }
Fred Quintana60307342009-03-24 22:48:12 -07002028 }
2029
Carlos Valdivia91979be2015-05-22 14:11:35 -07002030 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2031 MessageDigest digester;
2032 try {
2033 digester = MessageDigest.getInstance("SHA-256");
2034 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2035 callerPkg, PackageManager.GET_SIGNATURES);
2036 for (Signature sig : pkgInfo.signatures) {
2037 digester.update(sig.toByteArray());
2038 }
2039 } catch (NoSuchAlgorithmException x) {
2040 Log.wtf(TAG, "SHA-256 should be available", x);
2041 digester = null;
2042 } catch (NameNotFoundException e) {
2043 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2044 digester = null;
2045 }
2046 return (digester == null) ? null : digester.digest();
2047 }
2048
Dianne Hackborn41203752012-08-31 14:05:51 -07002049 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2050 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002051 int uid = intent.getIntExtra(
2052 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2053 String authTokenType = intent.getStringExtra(
2054 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002055 final String titleAndSubtitle =
2056 mContext.getString(R.string.permission_request_notification_with_subtitle,
2057 account.name);
2058 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002059 String title = titleAndSubtitle;
2060 String subtitle = "";
2061 if (index > 0) {
2062 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002063 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002064 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002065 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002066 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002067 Notification n = new Notification.Builder(contextForUser)
2068 .setSmallIcon(android.R.drawable.stat_sys_warning)
2069 .setWhen(0)
2070 .setColor(contextForUser.getColor(
2071 com.android.internal.R.color.system_notification_accent_color))
2072 .setContentTitle(title)
2073 .setContentText(subtitle)
2074 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2075 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2076 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002077 installNotification(getCredentialPermissionNotificationId(
2078 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002079 }
2080
Costin Manolache5f383ad92010-12-02 16:44:46 -08002081 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002082 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002083
2084 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002085 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002086 // Since it was set in Eclair+ we can't change it without breaking apps using
2087 // the intent from a non-Activity context.
2088 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002089 intent.addCategory(
2090 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002091
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002092 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002093 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2094 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002095 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002096
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002097 return intent;
2098 }
2099
2100 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2101 int uid) {
2102 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002103 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002104 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002105 final Pair<Pair<Account, String>, Integer> key =
2106 new Pair<Pair<Account, String>, Integer>(
2107 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002108 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002109 if (id == null) {
2110 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002111 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002112 }
2113 }
2114 return id;
2115 }
2116
Amith Yamasani04e0d262012-02-14 11:50:53 -08002117 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002118 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002119 synchronized (accounts.signinRequiredNotificationIds) {
2120 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002121 if (id == null) {
2122 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002123 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002124 }
2125 }
2126 return id;
2127 }
2128
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002129 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002130 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002131 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002132 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08002133 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2134 Log.v(TAG, "addAccount: accountType " + accountType
2135 + ", response " + response
2136 + ", authTokenType " + authTokenType
2137 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2138 + ", expectActivityLaunch " + expectActivityLaunch
2139 + ", caller's uid " + Binder.getCallingUid()
2140 + ", pid " + Binder.getCallingPid());
2141 }
Fred Quintana382601f2010-03-25 12:25:10 -07002142 if (response == null) throw new IllegalArgumentException("response is null");
2143 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002144
Amith Yamasani71e6c692013-03-24 17:39:28 -07002145 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002146 int userId = Binder.getCallingUserHandle().getIdentifier();
2147 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002148 try {
2149 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2150 "User is not allowed to add an account!");
2151 } catch (RemoteException re) {
2152 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002153 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002154 return;
2155 }
2156 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002157 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002158 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2159 "User cannot modify accounts of this type (policy).");
2160 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002161 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002162 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2163 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002164 return;
2165 }
2166
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002167 final int pid = Binder.getCallingPid();
2168 final int uid = Binder.getCallingUid();
2169 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2170 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2171 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2172
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002173 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002174 long identityToken = clearCallingIdentity();
2175 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002176 UserAccounts accounts = getUserAccounts(usrId);
2177 logRecordWithUid(
2178 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002179 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002180 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002181 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002182 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002183 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002184 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002185 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002186 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002187
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002188 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002189 protected String toDebugString(long now) {
2190 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002191 + ", accountType " + accountType
2192 + ", requiredFeatures "
2193 + (requiredFeatures != null
2194 ? TextUtils.join(",", requiredFeatures)
2195 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002196 }
2197 }.bind();
2198 } finally {
2199 restoreCallingIdentity(identityToken);
2200 }
Fred Quintana60307342009-03-24 22:48:12 -07002201 }
2202
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002203 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002204 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2205 final String authTokenType, final String[] requiredFeatures,
2206 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002207 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002208 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2209 Log.v(TAG, "addAccount: accountType " + accountType
2210 + ", response " + response
2211 + ", authTokenType " + authTokenType
2212 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2213 + ", expectActivityLaunch " + expectActivityLaunch
2214 + ", caller's uid " + Binder.getCallingUid()
2215 + ", pid " + Binder.getCallingPid()
2216 + ", for user id " + userId);
2217 }
2218 if (response == null) throw new IllegalArgumentException("response is null");
2219 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002220 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002221 if (isCrossUser(callingUid, userId)) {
2222 throw new SecurityException(
2223 String.format(
2224 "User %s trying to add account for %s" ,
2225 UserHandle.getCallingUserId(),
2226 userId));
2227 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002228
2229 // Is user disallowed from modifying accounts?
2230 if (!canUserModifyAccounts(userId)) {
2231 try {
2232 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2233 "User is not allowed to add an account!");
2234 } catch (RemoteException re) {
2235 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002236 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002237 return;
2238 }
2239 if (!canUserModifyAccountsForType(userId, accountType)) {
2240 try {
2241 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2242 "User cannot modify accounts of this type (policy).");
2243 } catch (RemoteException re) {
2244 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002245 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2246 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002247 return;
2248 }
2249
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002250 final int pid = Binder.getCallingPid();
2251 final int uid = Binder.getCallingUid();
2252 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2253 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2254 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2255
2256 long identityToken = clearCallingIdentity();
2257 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002258 UserAccounts accounts = getUserAccounts(userId);
2259 logRecordWithUid(
2260 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002261 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002262 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002263 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002264 @Override
2265 public void run() throws RemoteException {
2266 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2267 options);
2268 }
2269
2270 @Override
2271 protected String toDebugString(long now) {
2272 return super.toDebugString(now) + ", addAccount"
2273 + ", accountType " + accountType
2274 + ", requiredFeatures "
2275 + (requiredFeatures != null
2276 ? TextUtils.join(",", requiredFeatures)
2277 : null);
2278 }
2279 }.bind();
2280 } finally {
2281 restoreCallingIdentity(identityToken);
2282 }
2283 }
2284
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002285 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002286 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2287 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2288 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2289 long identityToken = clearCallingIdentity();
2290 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002291 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002292 } finally {
2293 restoreCallingIdentity(identityToken);
2294 }
2295 }
2296
2297 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002298 public void confirmCredentialsAsUser(
2299 IAccountManagerResponse response,
2300 final Account account,
2301 final Bundle options,
2302 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002303 int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002304 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002305 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2306 Log.v(TAG, "confirmCredentials: " + account
2307 + ", response " + response
2308 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002309 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002310 + ", pid " + Binder.getCallingPid());
2311 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002312 // Only allow the system process to read accounts of other users
2313 if (isCrossUser(callingUid, userId)) {
2314 throw new SecurityException(
2315 String.format(
2316 "User %s trying to confirm account credentials for %s" ,
2317 UserHandle.getCallingUserId(),
2318 userId));
2319 }
Fred Quintana382601f2010-03-25 12:25:10 -07002320 if (response == null) throw new IllegalArgumentException("response is null");
2321 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002322 long identityToken = clearCallingIdentity();
2323 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002324 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002325 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002326 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002327 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002328 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002329 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002330 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002331 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002332 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002333 protected String toDebugString(long now) {
2334 return super.toDebugString(now) + ", confirmCredentials"
2335 + ", " + account;
2336 }
2337 }.bind();
2338 } finally {
2339 restoreCallingIdentity(identityToken);
2340 }
Fred Quintana60307342009-03-24 22:48:12 -07002341 }
2342
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002343 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002344 public void updateCredentials(IAccountManagerResponse response, final Account account,
2345 final String authTokenType, final boolean expectActivityLaunch,
2346 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08002347 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2348 Log.v(TAG, "updateCredentials: " + account
2349 + ", response " + response
2350 + ", authTokenType " + authTokenType
2351 + ", expectActivityLaunch " + expectActivityLaunch
2352 + ", caller's uid " + Binder.getCallingUid()
2353 + ", pid " + Binder.getCallingPid());
2354 }
Fred Quintana382601f2010-03-25 12:25:10 -07002355 if (response == null) throw new IllegalArgumentException("response is null");
2356 if (account == null) throw new IllegalArgumentException("account is null");
2357 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002358 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002359 long identityToken = clearCallingIdentity();
2360 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002361 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002362 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002363 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002364 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002365 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002366 public void run() throws RemoteException {
2367 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2368 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002369 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002370 protected String toDebugString(long now) {
2371 if (loginOptions != null) loginOptions.keySet();
2372 return super.toDebugString(now) + ", updateCredentials"
2373 + ", " + account
2374 + ", authTokenType " + authTokenType
2375 + ", loginOptions " + loginOptions;
2376 }
2377 }.bind();
2378 } finally {
2379 restoreCallingIdentity(identityToken);
2380 }
Fred Quintana60307342009-03-24 22:48:12 -07002381 }
2382
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002383 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002384 public void editProperties(IAccountManagerResponse response, final String accountType,
2385 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002386 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002387 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2388 Log.v(TAG, "editProperties: accountType " + accountType
2389 + ", response " + response
2390 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002391 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002392 + ", pid " + Binder.getCallingPid());
2393 }
Fred Quintana382601f2010-03-25 12:25:10 -07002394 if (response == null) throw new IllegalArgumentException("response is null");
2395 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002396 int userId = UserHandle.getCallingUserId();
2397 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002398 String msg = String.format(
2399 "uid %s cannot edit authenticator properites for account type: %s",
2400 callingUid,
2401 accountType);
2402 throw new SecurityException(msg);
2403 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002404 long identityToken = clearCallingIdentity();
2405 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002406 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002407 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002408 true /* stripAuthTokenFromResult */, null /* accountName */,
2409 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002410 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002411 public void run() throws RemoteException {
2412 mAuthenticator.editProperties(this, mAccountType);
2413 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002414 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002415 protected String toDebugString(long now) {
2416 return super.toDebugString(now) + ", editProperties"
2417 + ", accountType " + accountType;
2418 }
2419 }.bind();
2420 } finally {
2421 restoreCallingIdentity(identityToken);
2422 }
Fred Quintana60307342009-03-24 22:48:12 -07002423 }
2424
Fred Quintana33269202009-04-20 16:05:10 -07002425 private class GetAccountsByTypeAndFeatureSession extends Session {
2426 private final String[] mFeatures;
2427 private volatile Account[] mAccountsOfType = null;
2428 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2429 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002430 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002431
Amith Yamasani04e0d262012-02-14 11:50:53 -08002432 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002433 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002434 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002435 true /* stripAuthTokenFromResult */, null /* accountName */,
2436 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002437 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002438 mFeatures = features;
2439 }
2440
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002441 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002442 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002443 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002444 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2445 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002446 }
Fred Quintana33269202009-04-20 16:05:10 -07002447 // check whether each account matches the requested features
2448 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2449 mCurrentAccount = 0;
2450
2451 checkAccount();
2452 }
2453
2454 public void checkAccount() {
2455 if (mCurrentAccount >= mAccountsOfType.length) {
2456 sendResult();
2457 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002458 }
Fred Quintana33269202009-04-20 16:05:10 -07002459
Fred Quintana29e94b82010-03-10 12:11:51 -08002460 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2461 if (accountAuthenticator == null) {
2462 // It is possible that the authenticator has died, which is indicated by
2463 // mAuthenticator being set to null. If this happens then just abort.
2464 // There is no need to send back a result or error in this case since
2465 // that already happened when mAuthenticator was cleared.
2466 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2467 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2468 + " connected to the authenticator, " + toDebugString());
2469 }
2470 return;
2471 }
Fred Quintana33269202009-04-20 16:05:10 -07002472 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002473 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002474 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002475 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002476 }
2477 }
2478
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002479 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002480 public void onResult(Bundle result) {
2481 mNumResults++;
2482 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002483 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002484 return;
2485 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002486 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002487 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2488 }
2489 mCurrentAccount++;
2490 checkAccount();
2491 }
2492
2493 public void sendResult() {
2494 IAccountManagerResponse response = getResponseAndClose();
2495 if (response != null) {
2496 try {
2497 Account[] accounts = new Account[mAccountsWithFeatures.size()];
2498 for (int i = 0; i < accounts.length; i++) {
2499 accounts[i] = mAccountsWithFeatures.get(i);
2500 }
Fred Quintana56285a62010-12-02 14:20:51 -08002501 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2502 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2503 + response);
2504 }
Fred Quintana33269202009-04-20 16:05:10 -07002505 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002506 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07002507 response.onResult(result);
2508 } catch (RemoteException e) {
2509 // if the caller is dead then there is no one to care about remote exceptions
2510 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2511 Log.v(TAG, "failure while notifying response", e);
2512 }
2513 }
2514 }
2515 }
2516
2517
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002518 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002519 protected String toDebugString(long now) {
2520 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2521 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2522 }
2523 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002524
Amith Yamasani04e0d262012-02-14 11:50:53 -08002525 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002526 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08002527 * @hide
2528 */
Svetoslavf3f02ac2015-09-08 14:36:35 -07002529 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002530 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07002531 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2532 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002533 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002534 return new Account[0];
2535 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002536 long identityToken = clearCallingIdentity();
2537 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002538 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002539 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002540 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002541 callingUid,
2542 null, // packageName
2543 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002544 } finally {
2545 restoreCallingIdentity(identityToken);
2546 }
2547 }
2548
Amith Yamasanif29f2362012-04-05 18:29:52 -07002549 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002550 * Returns accounts for all running users.
2551 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07002552 * @hide
2553 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002554 public AccountAndUser[] getRunningAccounts() {
2555 final int[] runningUserIds;
2556 try {
2557 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2558 } catch (RemoteException e) {
2559 // Running in system_server; should never happen
2560 throw new RuntimeException(e);
2561 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002562 return getAccounts(runningUserIds);
2563 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07002564
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002565 /** {@hide} */
2566 public AccountAndUser[] getAllAccounts() {
2567 final List<UserInfo> users = getUserManager().getUsers();
2568 final int[] userIds = new int[users.size()];
2569 for (int i = 0; i < userIds.length; i++) {
2570 userIds[i] = users.get(i).id;
2571 }
2572 return getAccounts(userIds);
2573 }
2574
2575 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002576 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002577 for (int userId : userIds) {
2578 UserAccounts userAccounts = getUserAccounts(userId);
2579 if (userAccounts == null) continue;
2580 synchronized (userAccounts.cacheLock) {
2581 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2582 Binder.getCallingUid(), null);
2583 for (int a = 0; a < accounts.length; a++) {
2584 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07002585 }
2586 }
2587 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002588
2589 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2590 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002591 }
2592
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002593 @Override
Svetoslavf3f02ac2015-09-08 14:36:35 -07002594 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
2595 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07002596 }
2597
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002598 private Account[] getAccountsAsUser(
2599 String type,
2600 int userId,
2601 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07002602 int packageUid,
2603 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002604 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002605 // Only allow the system process to read accounts of other users
2606 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002607 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002608 && mContext.checkCallingOrSelfPermission(
2609 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2610 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002611 throw new SecurityException("User " + UserHandle.getCallingUserId()
2612 + " trying to get account for " + userId);
2613 }
2614
Fred Quintana56285a62010-12-02 14:20:51 -08002615 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2616 Log.v(TAG, "getAccounts: accountType " + type
2617 + ", caller's uid " + Binder.getCallingUid()
2618 + ", pid " + Binder.getCallingPid());
2619 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002620 // If the original calling app was using the framework account chooser activity, we'll
2621 // be passed in the original caller's uid here, which is what should be used for filtering.
2622 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2623 callingUid = packageUid;
2624 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002625
Svetoslavf3f02ac2015-09-08 14:36:35 -07002626 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2627 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002628 if (visibleAccountTypes.isEmpty()
2629 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002630 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002631 } else if (visibleAccountTypes.contains(type)) {
2632 // Prune the list down to just the requested type.
2633 visibleAccountTypes = new ArrayList<>();
2634 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07002635 } // else aggregate all the visible accounts (it won't matter if the
2636 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002637
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002638 long identityToken = clearCallingIdentity();
2639 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002640 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002641 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002642 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002643 callingUid,
2644 callingPackage,
2645 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002646 } finally {
2647 restoreCallingIdentity(identityToken);
2648 }
2649 }
2650
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002651 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002652 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002653 int callingUid,
2654 String callingPackage,
2655 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002656 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002657 ArrayList<Account> visibleAccounts = new ArrayList<>();
2658 for (String visibleType : visibleAccountTypes) {
2659 Account[] accountsForType = getAccountsFromCacheLocked(
2660 userAccounts, visibleType, callingUid, callingPackage);
2661 if (accountsForType != null) {
2662 visibleAccounts.addAll(Arrays.asList(accountsForType));
2663 }
2664 }
2665 Account[] result = new Account[visibleAccounts.size()];
2666 for (int i = 0; i < visibleAccounts.size(); i++) {
2667 result[i] = visibleAccounts.get(i);
2668 }
2669 return result;
2670 }
2671 }
2672
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002673 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002674 public boolean addSharedAccountAsUser(Account account, int userId) {
2675 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002676 UserAccounts accounts = getUserAccounts(userId);
2677 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002678 ContentValues values = new ContentValues();
2679 values.put(ACCOUNTS_NAME, account.name);
2680 values.put(ACCOUNTS_TYPE, account.type);
2681 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2682 new String[] {account.name, account.type});
2683 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2684 if (accountId < 0) {
2685 Log.w(TAG, "insertAccountIntoDatabase: " + account
2686 + ", skipping the DB insert failed");
2687 return false;
2688 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002689 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002690 return true;
2691 }
2692
2693 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002694 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
2695 userId = handleIncomingUser(userId);
2696 UserAccounts accounts = getUserAccounts(userId);
2697 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002698 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002699 final ContentValues values = new ContentValues();
2700 values.put(ACCOUNTS_NAME, newName);
2701 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
2702 int r = db.update(
2703 TABLE_SHARED_ACCOUNTS,
2704 values,
2705 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2706 new String[] { account.name, account.type });
2707 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002708 int callingUid = getCallingUid();
2709 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
2710 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002711 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002712 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002713 }
2714 return r > 0;
2715 }
2716
2717 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002718 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002719 return removeSharedAccountAsUser(account, userId, getCallingUid());
2720 }
2721
2722 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08002723 userId = handleIncomingUser(userId);
2724 UserAccounts accounts = getUserAccounts(userId);
2725 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002726 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002727 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2728 new String[] {account.name, account.type});
2729 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002730 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
2731 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002732 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002733 }
2734 return r > 0;
2735 }
2736
2737 @Override
2738 public Account[] getSharedAccountsAsUser(int userId) {
2739 userId = handleIncomingUser(userId);
2740 UserAccounts accounts = getUserAccounts(userId);
2741 ArrayList<Account> accountList = new ArrayList<Account>();
2742 Cursor cursor = null;
2743 try {
2744 cursor = accounts.openHelper.getReadableDatabase()
2745 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2746 null, null, null, null, null);
2747 if (cursor != null && cursor.moveToFirst()) {
2748 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2749 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2750 do {
2751 accountList.add(new Account(cursor.getString(nameIndex),
2752 cursor.getString(typeIndex)));
2753 } while (cursor.moveToNext());
2754 }
2755 } finally {
2756 if (cursor != null) {
2757 cursor.close();
2758 }
2759 }
2760 Account[] accountArray = new Account[accountList.size()];
2761 accountList.toArray(accountArray);
2762 return accountArray;
2763 }
2764
2765 @Override
Svetoslavf3f02ac2015-09-08 14:36:35 -07002766 public Account[] getAccounts(String type, String opPackageName) {
2767 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002768 }
2769
Amith Yamasani27db4682013-03-30 17:07:47 -07002770 @Override
Svetoslavf3f02ac2015-09-08 14:36:35 -07002771 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002772 int callingUid = Binder.getCallingUid();
2773 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2774 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2775 + callingUid + " with uid=" + uid);
2776 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07002777 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
2778 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07002779 }
2780
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002781 @Override
Svetoslavf3f02ac2015-09-08 14:36:35 -07002782 public Account[] getAccountsByTypeForPackage(String type, String packageName,
2783 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002784 int packageUid = -1;
2785 try {
2786 packageUid = AppGlobals.getPackageManager().getPackageUid(
2787 packageName, UserHandle.getCallingUserId());
2788 } catch (RemoteException re) {
2789 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2790 return new Account[0];
2791 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07002792 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
2793 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002794 }
2795
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002796 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002797 public void getAccountsByFeatures(
2798 IAccountManagerResponse response,
2799 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07002800 String[] features,
2801 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002802 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002803 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2804 Log.v(TAG, "getAccounts: accountType " + type
2805 + ", response " + response
2806 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002807 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002808 + ", pid " + Binder.getCallingPid());
2809 }
Fred Quintana382601f2010-03-25 12:25:10 -07002810 if (response == null) throw new IllegalArgumentException("response is null");
2811 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002812 int userId = UserHandle.getCallingUserId();
2813
Svetoslavf3f02ac2015-09-08 14:36:35 -07002814 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2815 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002816 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002817 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002818 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002819 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
2820 try {
2821 response.onResult(result);
2822 } catch (RemoteException e) {
2823 Log.e(TAG, "Cannot respond to caller do to exception." , e);
2824 }
2825 return;
2826 }
Fred Quintana33269202009-04-20 16:05:10 -07002827 long identityToken = clearCallingIdentity();
2828 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002829 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002830 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002831 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002832 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002833 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002834 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002835 Bundle result = new Bundle();
2836 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2837 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002838 return;
2839 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002840 new GetAccountsByTypeAndFeatureSession(
2841 userAccounts,
2842 response,
2843 type,
2844 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002845 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002846 } finally {
2847 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002848 }
2849 }
2850
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002851 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
2852 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
2853 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
2854 try {
2855 if (cursor.moveToNext()) {
2856 return cursor.getLong(0);
2857 }
2858 return -1;
2859 } finally {
2860 cursor.close();
2861 }
2862 }
2863
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002864 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002865 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002866 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002867 try {
2868 if (cursor.moveToNext()) {
2869 return cursor.getLong(0);
2870 }
2871 return -1;
2872 } finally {
2873 cursor.close();
2874 }
2875 }
2876
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002877 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002878 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2879 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2880 new String[]{key}, null, null, null);
2881 try {
2882 if (cursor.moveToNext()) {
2883 return cursor.getLong(0);
2884 }
2885 return -1;
2886 } finally {
2887 cursor.close();
2888 }
2889 }
2890
Fred Quintanaa698f422009-04-08 19:14:54 -07002891 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002892 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002893 IAccountManagerResponse mResponse;
2894 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002895 final boolean mExpectActivityLaunch;
2896 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002897 final String mAccountName;
2898 // Indicates if we need to add auth details(like last credential time)
2899 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002900 // If set, we need to update the last authenticated time. This is
2901 // currently
2902 // used on
2903 // successful confirming credentials.
2904 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07002905
Fred Quintana33269202009-04-20 16:05:10 -07002906 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002907 private int mNumRequestContinued = 0;
2908 private int mNumErrors = 0;
2909
Fred Quintana60307342009-03-24 22:48:12 -07002910 IAccountAuthenticator mAuthenticator = null;
2911
Fred Quintana8570f742010-02-18 10:32:54 -08002912 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002913 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002914
Amith Yamasani04e0d262012-02-14 11:50:53 -08002915 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002916 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2917 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002918 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
2919 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
2920 }
2921
2922 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
2923 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2924 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07002925 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002926 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002927 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002928 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002929 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002930 mResponse = response;
2931 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002932 mExpectActivityLaunch = expectActivityLaunch;
2933 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002934 mAccountName = accountName;
2935 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002936 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002937
Fred Quintanaa698f422009-04-08 19:14:54 -07002938 synchronized (mSessions) {
2939 mSessions.put(toString(), this);
2940 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002941 if (response != null) {
2942 try {
2943 response.asBinder().linkToDeath(this, 0 /* flags */);
2944 } catch (RemoteException e) {
2945 mResponse = null;
2946 binderDied();
2947 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002948 }
Fred Quintana60307342009-03-24 22:48:12 -07002949 }
2950
Fred Quintanaa698f422009-04-08 19:14:54 -07002951 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002952 if (mResponse == null) {
2953 // this session has already been closed
2954 return null;
2955 }
Fred Quintana60307342009-03-24 22:48:12 -07002956 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002957 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002958 return response;
2959 }
2960
Fred Quintanaa698f422009-04-08 19:14:54 -07002961 private void close() {
2962 synchronized (mSessions) {
2963 if (mSessions.remove(toString()) == null) {
2964 // the session was already closed, so bail out now
2965 return;
2966 }
2967 }
2968 if (mResponse != null) {
2969 // stop listening for response deaths
2970 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2971
2972 // clear this so that we don't accidentally send any further results
2973 mResponse = null;
2974 }
2975 cancelTimeout();
2976 unbind();
2977 }
2978
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002979 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002980 public void binderDied() {
2981 mResponse = null;
2982 close();
2983 }
2984
2985 protected String toDebugString() {
2986 return toDebugString(SystemClock.elapsedRealtime());
2987 }
2988
2989 protected String toDebugString(long now) {
2990 return "Session: expectLaunch " + mExpectActivityLaunch
2991 + ", connected " + (mAuthenticator != null)
2992 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2993 + "/" + mNumErrors + ")"
2994 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2995 }
2996
Fred Quintana60307342009-03-24 22:48:12 -07002997 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002998 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2999 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3000 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003001 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003002 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003003 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003004 }
3005 }
3006
3007 private void unbind() {
3008 if (mAuthenticator != null) {
3009 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003010 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003011 }
3012 }
3013
Fred Quintana60307342009-03-24 22:48:12 -07003014 public void cancelTimeout() {
3015 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3016 }
3017
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003018 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003019 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003020 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003021 try {
3022 run();
3023 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003024 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003025 "remote exception");
3026 }
Fred Quintana60307342009-03-24 22:48:12 -07003027 }
3028
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003029 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003030 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003031 mAuthenticator = null;
3032 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003033 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003034 try {
3035 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3036 "disconnected");
3037 } catch (RemoteException e) {
3038 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3039 Log.v(TAG, "Session.onServiceDisconnected: "
3040 + "caught RemoteException while responding", e);
3041 }
3042 }
Fred Quintana60307342009-03-24 22:48:12 -07003043 }
3044 }
3045
Fred Quintanab839afc2009-10-14 15:57:28 -07003046 public abstract void run() throws RemoteException;
3047
Fred Quintana60307342009-03-24 22:48:12 -07003048 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003049 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003050 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003051 try {
3052 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3053 "timeout");
3054 } catch (RemoteException e) {
3055 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3056 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3057 e);
3058 }
3059 }
Fred Quintana60307342009-03-24 22:48:12 -07003060 }
3061 }
3062
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003063 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003064 public void onResult(Bundle result) {
3065 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003066 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003067 if (result != null) {
3068 boolean isSuccessfulConfirmCreds = result.getBoolean(
3069 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003070 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003071 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3072 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003073 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003074 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3075 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003076 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003077 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003078 if (needUpdate || mAuthDetailsRequired) {
3079 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3080 if (needUpdate && accountPresent) {
3081 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3082 }
3083 if (mAuthDetailsRequired) {
3084 long lastAuthenticatedTime = -1;
3085 if (accountPresent) {
3086 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3087 mAccounts.openHelper.getReadableDatabase(),
3088 "select " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3089 + " from " +
3090 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3091 + ACCOUNTS_TYPE + "=?",
3092 new String[] {
3093 mAccountName, mAccountType
3094 });
3095 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003096 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003097 lastAuthenticatedTime);
3098 }
3099 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003100 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003101 if (result != null
3102 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
3103 /*
3104 * The Authenticator API allows third party authenticators to
3105 * supply arbitrary intents to other apps that they can run,
3106 * this can be very bad when those apps are in the system like
3107 * the System Settings.
3108 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003109 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07003110 long bid = Binder.clearCallingIdentity();
3111 try {
3112 PackageManager pm = mContext.getPackageManager();
3113 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3114 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
3115 if (PackageManager.SIGNATURE_MATCH !=
3116 pm.checkSignatures(authenticatorUid, targetUid)) {
3117 throw new SecurityException(
3118 "Activity to be started with KEY_INTENT must " +
3119 "share Authenticator's signatures");
3120 }
3121 } finally {
3122 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003123 }
3124 }
3125 if (result != null
3126 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003127 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3128 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003129 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3130 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003131 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3132 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003133 }
Fred Quintana60307342009-03-24 22:48:12 -07003134 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003135 IAccountManagerResponse response;
3136 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003137 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003138 response = mResponse;
3139 } else {
3140 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003141 }
Fred Quintana60307342009-03-24 22:48:12 -07003142 if (response != null) {
3143 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07003144 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08003145 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3146 Log.v(TAG, getClass().getSimpleName()
3147 + " calling onError() on response " + response);
3148 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003149 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07003150 "null bundle returned");
3151 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08003152 if (mStripAuthTokenFromResult) {
3153 result.remove(AccountManager.KEY_AUTHTOKEN);
3154 }
Fred Quintana56285a62010-12-02 14:20:51 -08003155 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3156 Log.v(TAG, getClass().getSimpleName()
3157 + " calling onResult() on response " + response);
3158 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003159 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3160 (intent == null)) {
3161 // All AccountManager error codes are greater than 0
3162 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3163 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3164 } else {
3165 response.onResult(result);
3166 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003167 }
Fred Quintana60307342009-03-24 22:48:12 -07003168 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003169 // if the caller is dead then there is no one to care about remote exceptions
3170 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3171 Log.v(TAG, "failure while notifying response", e);
3172 }
Fred Quintana60307342009-03-24 22:48:12 -07003173 }
3174 }
3175 }
Fred Quintana60307342009-03-24 22:48:12 -07003176
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003177 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003178 public void onRequestContinued() {
3179 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003180 }
3181
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003182 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003183 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003184 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003185 IAccountManagerResponse response = getResponseAndClose();
3186 if (response != null) {
3187 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003188 Log.v(TAG, getClass().getSimpleName()
3189 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003190 }
3191 try {
3192 response.onError(errorCode, errorMessage);
3193 } catch (RemoteException e) {
3194 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3195 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3196 }
3197 }
3198 } else {
3199 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3200 Log.v(TAG, "Session.onError: already closed");
3201 }
Fred Quintana60307342009-03-24 22:48:12 -07003202 }
3203 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003204
3205 /**
3206 * find the component name for the authenticator and initiate a bind
3207 * if no authenticator or the bind fails then return false, otherwise return true
3208 */
3209 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003210 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3211 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3212 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003213 if (authenticatorInfo == null) {
3214 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3215 Log.v(TAG, "there is no authenticator for " + authenticatorType
3216 + ", bailing out");
3217 }
3218 return false;
3219 }
3220
3221 Intent intent = new Intent();
3222 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3223 intent.setComponent(authenticatorInfo.componentName);
3224 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3225 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3226 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003227 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
3228 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003229 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3230 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3231 }
3232 return false;
3233 }
3234
3235
3236 return true;
3237 }
Fred Quintana60307342009-03-24 22:48:12 -07003238 }
3239
3240 private class MessageHandler extends Handler {
3241 MessageHandler(Looper looper) {
3242 super(looper);
3243 }
Costin Manolache3348f142009-09-29 18:58:36 -07003244
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003245 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003246 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07003247 switch (msg.what) {
3248 case MESSAGE_TIMED_OUT:
3249 Session session = (Session)msg.obj;
3250 session.onTimedOut();
3251 break;
3252
Amith Yamasani5be347b2013-03-31 17:44:31 -07003253 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00003254 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07003255 break;
3256
Fred Quintana60307342009-03-24 22:48:12 -07003257 default:
3258 throw new IllegalStateException("unhandled message: " + msg.what);
3259 }
3260 }
3261 }
3262
Amith Yamasani04e0d262012-02-14 11:50:53 -08003263 private static String getDatabaseName(int userId) {
3264 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07003265 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003266 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07003267 // Migrate old file, if it exists, to the new location.
3268 // Make sure the new file doesn't already exist. A dummy file could have been
3269 // accidentally created in the old location, causing the new one to become corrupted
3270 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08003271 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07003272 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07003273 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07003274 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07003275 if (!userDir.exists()) {
3276 if (!userDir.mkdirs()) {
3277 throw new IllegalStateException("User dir cannot be created: " + userDir);
3278 }
3279 }
3280 if (!oldFile.renameTo(databaseFile)) {
3281 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
3282 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003283 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003284 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003285 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08003286 }
3287
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003288 private static class DebugDbHelper{
3289 private DebugDbHelper() {
3290 }
3291
3292 private static String TABLE_DEBUG = "debug_table";
3293
3294 // Columns for the table
3295 private static String ACTION_TYPE = "action_type";
3296 private static String TIMESTAMP = "time";
3297 private static String CALLER_UID = "caller_uid";
3298 private static String TABLE_NAME = "table_name";
3299 private static String KEY = "primary_key";
3300
3301 // These actions correspond to the occurrence of real actions. Since
3302 // these are called by the authenticators, the uid associated will be
3303 // of the authenticator.
3304 private static String ACTION_SET_PASSWORD = "action_set_password";
3305 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
3306 private static String ACTION_ACCOUNT_ADD = "action_account_add";
3307 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
3308 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
3309 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
3310
3311 // These actions don't necessarily correspond to any action on
3312 // accountDb taking place. As an example, there might be a request for
3313 // addingAccount, which might not lead to addition of account on grounds
3314 // of bad authentication. We will still be logging it to keep track of
3315 // who called.
3316 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
3317 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003318
3319 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3320
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003321 private static void createDebugTable(SQLiteDatabase db) {
3322 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
3323 + ACCOUNTS_ID + " INTEGER,"
3324 + ACTION_TYPE + " TEXT NOT NULL, "
3325 + TIMESTAMP + " DATETIME,"
3326 + CALLER_UID + " INTEGER NOT NULL,"
3327 + TABLE_NAME + " TEXT NOT NULL,"
3328 + KEY + " INTEGER PRIMARY KEY)");
3329 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
3330 }
3331 }
3332
3333 private void logRecord(UserAccounts accounts, String action, String tableName) {
3334 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3335 logRecord(db, action, tableName, -1, accounts);
3336 }
3337
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003338 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
3339 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3340 logRecord(db, action, tableName, -1, accounts, uid);
3341 }
3342
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003343 /*
3344 * This function receives an opened writable database.
3345 */
3346 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3347 UserAccounts userAccount) {
3348 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
3349 }
3350
3351 /*
3352 * This function receives an opened writable database.
3353 */
3354 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3355 UserAccounts userAccount, int callingUid) {
3356 SQLiteStatement logStatement = userAccount.statementForLogging;
3357 logStatement.bindLong(1, accountId);
3358 logStatement.bindString(2, action);
3359 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
3360 logStatement.bindLong(4, callingUid);
3361 logStatement.bindString(5, tableName);
3362 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
3363 logStatement.execute();
3364 logStatement.clearBindings();
3365 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
3366 % MAX_DEBUG_DB_SIZE;
3367 }
3368
3369 /*
3370 * This should only be called once to compile the sql statement for logging
3371 * and to find the insertion point.
3372 */
3373 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
3374 UserAccounts userAccount) {
3375 // Initialize the count if not done earlier.
3376 int size = (int) getDebugTableRowCount(db);
3377 if (size >= MAX_DEBUG_DB_SIZE) {
3378 // Table is full, and we need to find the point where to insert.
3379 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
3380 } else {
3381 userAccount.debugDbInsertionPoint = size;
3382 }
3383 compileSqlStatementForLogging(db, userAccount);
3384 }
3385
3386 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
3387 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
3388 + " VALUES (?,?,?,?,?,?)";
3389 userAccount.statementForLogging = db.compileStatement(sql);
3390 }
3391
3392 private long getDebugTableRowCount(SQLiteDatabase db) {
3393 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
3394 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3395 }
3396
3397 /*
3398 * Finds the row key where the next insertion should take place. This should
3399 * be invoked only if the table has reached its full capacity.
3400 */
3401 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
3402 // This query finds the smallest timestamp value (and if 2 records have
3403 // same timestamp, the choose the lower id).
3404 String queryCountDebugDbRows = new StringBuilder()
3405 .append("SELECT ").append(DebugDbHelper.KEY)
3406 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
3407 .append(" ORDER BY ")
3408 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
3409 .append(" LIMIT 1")
3410 .toString();
3411 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3412 }
3413
Amith Yamasani04e0d262012-02-14 11:50:53 -08003414 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003415
Amith Yamasani04e0d262012-02-14 11:50:53 -08003416 public DatabaseHelper(Context context, int userId) {
3417 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07003418 }
3419
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003420 /**
3421 * This call needs to be made while the mCacheLock is held. The way to
3422 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
3423 * @param db The database.
3424 */
Fred Quintana60307342009-03-24 22:48:12 -07003425 @Override
3426 public void onCreate(SQLiteDatabase db) {
3427 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
3428 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3429 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3430 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3431 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003432 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003433 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
Fred Quintana60307342009-03-24 22:48:12 -07003434 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3435
3436 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
3437 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3438 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3439 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
3440 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
3441 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
3442
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003443 createGrantsTable(db);
3444
Fred Quintana60307342009-03-24 22:48:12 -07003445 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
3446 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3447 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
3448 + EXTRAS_KEY + " TEXT NOT NULL, "
3449 + EXTRAS_VALUE + " TEXT, "
3450 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
3451
3452 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
3453 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
3454 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07003455
Amith Yamasani67df64b2012-12-14 12:09:36 -08003456 createSharedAccountsTable(db);
3457
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003458 createAccountsDeletionTrigger(db);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003459
3460 DebugDbHelper.createDebugTable(db);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003461 }
3462
Amith Yamasani67df64b2012-12-14 12:09:36 -08003463 private void createSharedAccountsTable(SQLiteDatabase db) {
3464 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
3465 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3466 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3467 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3468 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3469 }
3470
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003471 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
3472 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
3473 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
3474 }
3475
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003476 private void addOldAccountNameColumn(SQLiteDatabase db) {
3477 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
3478 }
3479
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003480 private void addDebugTable(SQLiteDatabase db) {
3481 DebugDbHelper.createDebugTable(db);
3482 }
3483
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003484 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003485 db.execSQL(""
3486 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
3487 + " BEGIN"
3488 + " DELETE FROM " + TABLE_AUTHTOKENS
3489 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
3490 + " DELETE FROM " + TABLE_EXTRAS
3491 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003492 + " DELETE FROM " + TABLE_GRANTS
3493 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07003494 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07003495 }
3496
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003497 private void createGrantsTable(SQLiteDatabase db) {
3498 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
3499 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3500 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
3501 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
3502 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
3503 + "," + GRANTS_GRANTEE_UID + "))");
3504 }
3505
Fred Quintana60307342009-03-24 22:48:12 -07003506 @Override
3507 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003508 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07003509
Fred Quintanaa698f422009-04-08 19:14:54 -07003510 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003511 // no longer need to do anything since the work is done
3512 // when upgrading from version 2
3513 oldVersion++;
3514 }
3515
3516 if (oldVersion == 2) {
3517 createGrantsTable(db);
3518 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
3519 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07003520 oldVersion++;
3521 }
Costin Manolache3348f142009-09-29 18:58:36 -07003522
3523 if (oldVersion == 3) {
3524 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
3525 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
3526 oldVersion++;
3527 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003528
3529 if (oldVersion == 4) {
3530 createSharedAccountsTable(db);
3531 oldVersion++;
3532 }
3533
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003534 if (oldVersion == 5) {
3535 addOldAccountNameColumn(db);
3536 oldVersion++;
3537 }
3538
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003539 if (oldVersion == 6) {
3540 addLastSuccessfullAuthenticatedTimeColumn(db);
3541 oldVersion++;
3542 }
3543
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003544 if (oldVersion == 7) {
3545 addDebugTable(db);
3546 oldVersion++;
3547 }
3548
Amith Yamasani67df64b2012-12-14 12:09:36 -08003549 if (oldVersion != newVersion) {
3550 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
3551 }
Fred Quintana60307342009-03-24 22:48:12 -07003552 }
3553
3554 @Override
3555 public void onOpen(SQLiteDatabase db) {
3556 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
3557 }
3558 }
3559
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003560 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07003561 return asBinder();
3562 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003563
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003564 /**
3565 * Searches array of arguments for the specified string
3566 * @param args array of argument strings
3567 * @param value value to search for
3568 * @return true if the value is contained in the array
3569 */
3570 private static boolean scanArgs(String[] args, String value) {
3571 if (args != null) {
3572 for (String arg : args) {
3573 if (value.equals(arg)) {
3574 return true;
3575 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003576 }
3577 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003578 return false;
3579 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003580
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003581 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003582 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07003583 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3584 != PackageManager.PERMISSION_GRANTED) {
3585 fout.println("Permission Denial: can't dump AccountsManager from from pid="
3586 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3587 + " without permission " + android.Manifest.permission.DUMP);
3588 return;
3589 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003590 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003591 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07003592
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003593 final List<UserInfo> users = getUserManager().getUsers();
3594 for (UserInfo user : users) {
3595 ipw.println("User " + user + ":");
3596 ipw.increaseIndent();
3597 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
3598 ipw.println();
3599 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08003600 }
3601 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003602
Amith Yamasani04e0d262012-02-14 11:50:53 -08003603 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
3604 String[] args, boolean isCheckinRequest) {
3605 synchronized (userAccounts.cacheLock) {
3606 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003607
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003608 if (isCheckinRequest) {
3609 // This is a checkin request. *Only* upload the account types and the count of each.
3610 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
3611 null, null, ACCOUNTS_TYPE, null, null);
3612 try {
3613 while (cursor.moveToNext()) {
3614 // print type,count
3615 fout.println(cursor.getString(0) + "," + cursor.getString(1));
3616 }
3617 } finally {
3618 if (cursor != null) {
3619 cursor.close();
3620 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003621 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003622 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003623 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07003624 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003625 fout.println("Accounts: " + accounts.length);
3626 for (Account account : accounts) {
3627 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003628 }
Fred Quintana307da1a2010-01-21 14:24:20 -08003629
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003630 // Add debug information.
3631 fout.println();
3632 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
3633 null, null, null, null, DebugDbHelper.TIMESTAMP);
3634 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
3635 fout.println("Accounts History");
3636 try {
3637 while (cursor.moveToNext()) {
3638 // print type,count
3639 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
3640 cursor.getString(2) + "," + cursor.getString(3) + ","
3641 + cursor.getString(4) + "," + cursor.getString(5));
3642 }
3643 } finally {
3644 cursor.close();
3645 }
3646
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003647 fout.println();
3648 synchronized (mSessions) {
3649 final long now = SystemClock.elapsedRealtime();
3650 fout.println("Active Sessions: " + mSessions.size());
3651 for (Session session : mSessions.values()) {
3652 fout.println(" " + session.toDebugString(now));
3653 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003654 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003655
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003656 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003657 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003658 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003659 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003660 }
3661
Amith Yamasani04e0d262012-02-14 11:50:53 -08003662 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07003663 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003664 long identityToken = clearCallingIdentity();
3665 try {
3666 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3667 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
3668 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003669
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003670 if (intent.getComponent() != null &&
3671 GrantCredentialsPermissionActivity.class.getName().equals(
3672 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003673 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003674 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003675 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07003676 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003677 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003678 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07003679 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003680 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003681 Notification n = new Notification.Builder(contextForUser)
3682 .setWhen(0)
3683 .setSmallIcon(android.R.drawable.stat_sys_warning)
3684 .setColor(contextForUser.getColor(
3685 com.android.internal.R.color.system_notification_accent_color))
3686 .setContentTitle(String.format(notificationTitleFormat, account.name))
3687 .setContentText(message)
3688 .setContentIntent(PendingIntent.getActivityAsUser(
3689 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
3690 null, user))
3691 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003692 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003693 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003694 } finally {
3695 restoreCallingIdentity(identityToken);
3696 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003697 }
3698
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003699 protected void installNotification(final int notificationId, final Notification n,
3700 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08003701 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003702 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08003703 }
3704
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003705 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003706 long identityToken = clearCallingIdentity();
3707 try {
3708 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003709 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003710 } finally {
3711 restoreCallingIdentity(identityToken);
3712 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003713 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003714
Svetoslavf3f02ac2015-09-08 14:36:35 -07003715 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
Fred Quintanab38eb142010-02-24 13:40:54 -08003716 for (String perm : permissions) {
3717 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
3718 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003719 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08003720 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003721 final int opCode = AppOpsManager.permissionToOpCode(perm);
3722 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
3723 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
3724 return true;
3725 }
Fred Quintanab38eb142010-02-24 13:40:54 -08003726 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003727 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003728 return false;
3729 }
3730
Amith Yamasani67df64b2012-12-14 12:09:36 -08003731 private int handleIncomingUser(int userId) {
3732 try {
3733 return ActivityManagerNative.getDefault().handleIncomingUser(
3734 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
3735 } catch (RemoteException re) {
3736 // Shouldn't happen, local.
3737 }
3738 return userId;
3739 }
3740
Christopher Tateccbf84f2013-05-08 15:25:41 -07003741 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003742 final int callingUserId = UserHandle.getUserId(callingUid);
3743
3744 final PackageManager userPackageManager;
3745 try {
3746 userPackageManager = mContext.createPackageContextAsUser(
3747 "android", 0, new UserHandle(callingUserId)).getPackageManager();
3748 } catch (NameNotFoundException e) {
3749 return false;
3750 }
3751
3752 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07003753 for (String name : packages) {
3754 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003755 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08003756 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003757 && (packageInfo.applicationInfo.privateFlags
3758 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07003759 return true;
3760 }
3761 } catch (PackageManager.NameNotFoundException e) {
3762 return false;
3763 }
3764 }
3765 return false;
3766 }
3767
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003768 private boolean permissionIsGranted(
3769 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07003770 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07003771 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003772 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07003773 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08003774 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003775 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3776 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08003777 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003778 + ": is authenticator? " + fromAuthenticator
3779 + ", has explicit permission? " + hasExplicitGrants);
3780 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07003781 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003782 }
3783
Svetoslavf3f02ac2015-09-08 14:36:35 -07003784 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
3785 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003786 if (accountType == null) {
3787 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003788 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07003789 return getTypesVisibleToCaller(callingUid, userId,
3790 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003791 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003792 }
3793
3794 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
3795 if (accountType == null) {
3796 return false;
3797 } else {
3798 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
3799 }
3800 }
3801
Svetoslavf3f02ac2015-09-08 14:36:35 -07003802 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
3803 String opPackageName) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003804 boolean isPermitted =
Svetoslavf3f02ac2015-09-08 14:36:35 -07003805 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003806 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
3807 Log.i(TAG, String.format("getTypesVisibleToCaller: isPermitted? %s", isPermitted));
3808 return getTypesForCaller(callingUid, userId, isPermitted);
3809 }
3810
3811 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
3812 return getTypesForCaller(callingUid, userId, false);
3813 }
3814
3815 private List<String> getTypesForCaller(
3816 int callingUid, int userId, boolean isOtherwisePermitted) {
3817 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003818 long identityToken = Binder.clearCallingIdentity();
3819 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
3820 try {
3821 serviceInfos = mAuthenticatorCache.getAllServices(userId);
3822 } finally {
3823 Binder.restoreCallingIdentity(identityToken);
3824 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003825 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003826 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003827 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
3828 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
3829 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003830 }
3831 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003832 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003833 }
3834
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003835 private boolean isAccountPresentForCaller(String accountName, String accountType) {
3836 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
3837 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
3838 if (account.name.equals(accountName)) {
3839 return true;
3840 }
3841 }
3842 }
3843 return false;
3844 }
3845
Amith Yamasani04e0d262012-02-14 11:50:53 -08003846 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
3847 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003848 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003849 return true;
3850 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003851 UserAccounts accounts = getUserAccountsForCaller();
3852 synchronized (accounts.cacheLock) {
3853 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3854 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003855 account.name, account.type};
3856 final boolean permissionGranted =
3857 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
3858 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
3859 // TODO: Skip this check when running automated tests. Replace this
3860 // with a more general solution.
3861 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08003862 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003863 + " but ignoring since device is in test harness.");
3864 return true;
3865 }
3866 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003867 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003868 }
3869
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003870 private boolean isSystemUid(int callingUid) {
3871 String[] packages = null;
3872 long ident = Binder.clearCallingIdentity();
3873 try {
3874 packages = mPackageManager.getPackagesForUid(callingUid);
3875 } finally {
3876 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07003877 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003878 if (packages != null) {
3879 for (String name : packages) {
3880 try {
3881 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
3882 if (packageInfo != null
3883 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
3884 != 0) {
3885 return true;
3886 }
3887 } catch (PackageManager.NameNotFoundException e) {
3888 Log.w(TAG, String.format("Could not find package [%s]", name), e);
3889 }
3890 }
3891 } else {
3892 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07003893 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003894 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003895 }
3896
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003897 /** Succeeds if any of the specified permissions are granted. */
3898 private void checkReadAccountsPermitted(
3899 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003900 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003901 int userId,
3902 String opPackageName) {
3903 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003904 String msg = String.format(
3905 "caller uid %s cannot access %s accounts",
3906 callingUid,
3907 accountType);
3908 Log.w(TAG, " " + msg);
3909 throw new SecurityException(msg);
3910 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003911 }
3912
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003913 private boolean canUserModifyAccounts(int userId) {
3914 if (getUserManager().getUserRestrictions(new UserHandle(userId))
3915 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
3916 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003917 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003918 return true;
3919 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003920
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003921 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003922 DevicePolicyManager dpm = (DevicePolicyManager) mContext
3923 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003924 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02003925 if (typesArray == null) {
3926 return true;
3927 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003928 for (String forbiddenType : typesArray) {
3929 if (forbiddenType.equals(accountType)) {
3930 return false;
3931 }
3932 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003933 return true;
3934 }
3935
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003936 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07003937 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
3938 throws RemoteException {
3939 final int callingUid = getCallingUid();
3940
Amith Yamasani27db4682013-03-30 17:07:47 -07003941 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07003942 throw new SecurityException();
3943 }
3944
3945 if (value) {
3946 grantAppPermission(account, authTokenType, uid);
3947 } else {
3948 revokeAppPermission(account, authTokenType, uid);
3949 }
3950 }
3951
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003952 /**
3953 * Allow callers with the given uid permission to get credentials for account/authTokenType.
3954 * <p>
3955 * Although this is public it can only be accessed via the AccountManagerService object
3956 * which is in the system. This means we don't need to protect it with permissions.
3957 * @hide
3958 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003959 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003960 if (account == null || authTokenType == null) {
3961 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003962 return;
3963 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003964 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003965 synchronized (accounts.cacheLock) {
3966 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003967 db.beginTransaction();
3968 try {
3969 long accountId = getAccountIdLocked(db, account);
3970 if (accountId >= 0) {
3971 ContentValues values = new ContentValues();
3972 values.put(GRANTS_ACCOUNTS_ID, accountId);
3973 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
3974 values.put(GRANTS_GRANTEE_UID, uid);
3975 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
3976 db.setTransactionSuccessful();
3977 }
3978 } finally {
3979 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003980 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003981 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3982 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003983 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003984 }
3985
3986 /**
3987 * Don't allow callers with the given uid permission to get credentials for
3988 * account/authTokenType.
3989 * <p>
3990 * Although this is public it can only be accessed via the AccountManagerService object
3991 * which is in the system. This means we don't need to protect it with permissions.
3992 * @hide
3993 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003994 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003995 if (account == null || authTokenType == null) {
3996 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003997 return;
3998 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003999 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08004000 synchronized (accounts.cacheLock) {
4001 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004002 db.beginTransaction();
4003 try {
4004 long accountId = getAccountIdLocked(db, account);
4005 if (accountId >= 0) {
4006 db.delete(TABLE_GRANTS,
4007 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
4008 + GRANTS_GRANTEE_UID + "=?",
4009 new String[]{String.valueOf(accountId), authTokenType,
4010 String.valueOf(uid)});
4011 db.setTransactionSuccessful();
4012 }
4013 } finally {
4014 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004015 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004016 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
4017 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004018 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004019 }
Fred Quintana56285a62010-12-02 14:20:51 -08004020
4021 static final private String stringArrayToString(String[] value) {
4022 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
4023 }
4024
Amith Yamasani04e0d262012-02-14 11:50:53 -08004025 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
4026 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004027 if (oldAccountsForType != null) {
4028 ArrayList<Account> newAccountsList = new ArrayList<Account>();
4029 for (Account curAccount : oldAccountsForType) {
4030 if (!curAccount.equals(account)) {
4031 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004032 }
4033 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004034 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004035 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004036 } else {
4037 Account[] newAccountsForType = new Account[newAccountsList.size()];
4038 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004039 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004040 }
Fred Quintana56285a62010-12-02 14:20:51 -08004041 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004042 accounts.userDataCache.remove(account);
4043 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004044 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004045 }
4046
4047 /**
4048 * This assumes that the caller has already checked that the account is not already present.
4049 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08004050 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
4051 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004052 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
4053 Account[] newAccountsForType = new Account[oldLength + 1];
4054 if (accountsForType != null) {
4055 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08004056 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004057 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004058 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08004059 }
4060
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004061 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07004062 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004063 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07004064 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004065 return unfiltered;
4066 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004067 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
4068 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004069 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004070 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004071 // otherwise return non-shared accounts only.
4072 // This might be a temporary way to specify a whitelist
4073 String whiteList = mContext.getResources().getString(
4074 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
4075 for (String packageName : packages) {
4076 if (whiteList.contains(";" + packageName + ";")) {
4077 return unfiltered;
4078 }
4079 }
4080 ArrayList<Account> allowed = new ArrayList<Account>();
4081 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
4082 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004083 String requiredAccountType = "";
4084 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07004085 // If there's an explicit callingPackage specified, check if that package
4086 // opted in to see restricted accounts.
4087 if (callingPackage != null) {
4088 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004089 if (pi != null && pi.restrictedAccountType != null) {
4090 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07004091 }
4092 } else {
4093 // Otherwise check if the callingUid has a package that has opted in
4094 for (String packageName : packages) {
4095 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
4096 if (pi != null && pi.restrictedAccountType != null) {
4097 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07004098 break;
4099 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004100 }
4101 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004102 } catch (NameNotFoundException nnfe) {
4103 }
4104 for (Account account : unfiltered) {
4105 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004106 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004107 } else {
4108 boolean found = false;
4109 for (Account shared : sharedAccounts) {
4110 if (shared.equals(account)) {
4111 found = true;
4112 break;
4113 }
4114 }
4115 if (!found) {
4116 allowed.add(account);
4117 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004118 }
4119 }
4120 Account[] filtered = new Account[allowed.size()];
4121 allowed.toArray(filtered);
4122 return filtered;
4123 } else {
4124 return unfiltered;
4125 }
4126 }
4127
Amith Yamasani27db4682013-03-30 17:07:47 -07004128 /*
4129 * packageName can be null. If not null, it should be used to filter out restricted accounts
4130 * that the package is not allowed to access.
4131 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004132 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07004133 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004134 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004135 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004136 if (accounts == null) {
4137 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08004138 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004139 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07004140 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004141 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004142 } else {
4143 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004144 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004145 totalLength += accounts.length;
4146 }
4147 if (totalLength == 0) {
4148 return EMPTY_ACCOUNT_ARRAY;
4149 }
4150 Account[] accounts = new Account[totalLength];
4151 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004152 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004153 System.arraycopy(accountsOfType, 0, accounts, totalLength,
4154 accountsOfType.length);
4155 totalLength += accountsOfType.length;
4156 }
Amith Yamasani27db4682013-03-30 17:07:47 -07004157 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004158 }
4159 }
4160
Amith Yamasani04e0d262012-02-14 11:50:53 -08004161 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4162 Account account, String key, String value) {
4163 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004164 if (userDataForAccount == null) {
4165 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004166 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004167 }
4168 if (value == null) {
4169 userDataForAccount.remove(key);
4170 } else {
4171 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004172 }
4173 }
4174
Carlos Valdivia91979be2015-05-22 14:11:35 -07004175 protected String readCachedTokenInternal(
4176 UserAccounts accounts,
4177 Account account,
4178 String tokenType,
4179 String callingPackage,
4180 byte[] pkgSigDigest) {
4181 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004182 return accounts.accountTokenCaches.get(
4183 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004184 }
4185 }
4186
Amith Yamasani04e0d262012-02-14 11:50:53 -08004187 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4188 Account account, String key, String value) {
4189 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004190 if (authTokensForAccount == null) {
4191 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004192 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004193 }
4194 if (value == null) {
4195 authTokensForAccount.remove(key);
4196 } else {
4197 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004198 }
4199 }
4200
Amith Yamasani04e0d262012-02-14 11:50:53 -08004201 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
4202 String authTokenType) {
4203 synchronized (accounts.cacheLock) {
4204 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004205 if (authTokensForAccount == null) {
4206 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004207 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004208 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004209 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004210 }
4211 return authTokensForAccount.get(authTokenType);
4212 }
4213 }
4214
Amith Yamasani04e0d262012-02-14 11:50:53 -08004215 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
4216 synchronized (accounts.cacheLock) {
4217 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004218 if (userDataForAccount == null) {
4219 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004220 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004221 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004222 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004223 }
4224 return userDataForAccount.get(key);
4225 }
4226 }
4227
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004228 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
4229 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004230 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004231 Cursor cursor = db.query(TABLE_EXTRAS,
4232 COLUMNS_EXTRAS_KEY_AND_VALUE,
4233 SELECTION_USERDATA_BY_ACCOUNT,
4234 new String[]{account.name, account.type},
4235 null, null, null);
4236 try {
4237 while (cursor.moveToNext()) {
4238 final String tmpkey = cursor.getString(0);
4239 final String value = cursor.getString(1);
4240 userDataForAccount.put(tmpkey, value);
4241 }
4242 } finally {
4243 cursor.close();
4244 }
4245 return userDataForAccount;
4246 }
4247
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004248 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
4249 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004250 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004251 Cursor cursor = db.query(TABLE_AUTHTOKENS,
4252 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
4253 SELECTION_AUTHTOKENS_BY_ACCOUNT,
4254 new String[]{account.name, account.type},
4255 null, null, null);
4256 try {
4257 while (cursor.moveToNext()) {
4258 final String type = cursor.getString(0);
4259 final String authToken = cursor.getString(1);
4260 authTokensForAccount.put(type, authToken);
4261 }
4262 } finally {
4263 cursor.close();
4264 }
4265 return authTokensForAccount;
4266 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004267
4268 private Context getContextForUser(UserHandle user) {
4269 try {
4270 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
4271 } catch (NameNotFoundException e) {
4272 // Default to mContext, not finding the package system is running as is unlikely.
4273 return mContext;
4274 }
4275 }
Fred Quintana60307342009-03-24 22:48:12 -07004276}