blob: d5e9a320da849e46d7d1e85e96d8c026035b60b7 [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Carlos Valdivia91979be2015-05-22 14:11:35 -070020import android.accounts.AbstractAccountAuthenticator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
25import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070026import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.accounts.GrantCredentialsPermissionActivity;
28import android.accounts.IAccountAuthenticator;
29import android.accounts.IAccountAuthenticatorResponse;
30import android.accounts.IAccountManager;
31import android.accounts.IAccountManagerResponse;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080032import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070033import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070034import android.app.AppGlobals;
Svetoslavce852dd2015-09-08 14:36:35 -070035import android.app.AppOpsManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010039import android.app.admin.DevicePolicyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070040import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070041import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070042import android.content.ContentValues;
43import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070046import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070047import android.content.pm.ApplicationInfo;
48import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070049import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070050import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070051import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070052import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070053import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070054import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070055import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070056import android.database.Cursor;
57import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070058import android.database.sqlite.SQLiteDatabase;
59import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070060import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070061import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080063import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070064import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import android.os.IBinder;
66import android.os.Looper;
67import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070068import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070069import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.os.RemoteException;
71import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070072import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070073import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070074import android.text.TextUtils;
75import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070076import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070077import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080078import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070079
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070080import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080081import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080082import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070083import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070084import com.google.android.collect.Lists;
85import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070086
Oscar Montemayora8529f62009-11-18 10:14:20 -080087import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070088import java.io.FileDescriptor;
89import java.io.PrintWriter;
Carlos Valdivia91979be2015-05-22 14:11:35 -070090import java.security.MessageDigest;
91import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070092import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -070093import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080094import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070095import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070096import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070097import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070098import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080099import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700100import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800101import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700102import java.util.concurrent.atomic.AtomicInteger;
103import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700104
Fred Quintana60307342009-03-24 22:48:12 -0700105/**
106 * A system service that provides account, password, and authtoken management for all
107 * accounts on the device. Some of these calls are implemented with the help of the corresponding
108 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
109 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700110 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700111 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700112 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700113public class AccountManagerService
114 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800115 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700116 private static final String TAG = "AccountManagerService";
117
Fred Quintana60307342009-03-24 22:48:12 -0700118 private static final String DATABASE_NAME = "accounts.db";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700119 private static final int DATABASE_VERSION = 8;
120
121 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700122
123 private final Context mContext;
124
Fred Quintana56285a62010-12-02 14:20:51 -0800125 private final PackageManager mPackageManager;
Svetoslavce852dd2015-09-08 14:36:35 -0700126 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700127 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800128
Fred Quintana60307342009-03-24 22:48:12 -0700129 private final MessageHandler mMessageHandler;
130
131 // Messages that can be sent on mHandler
132 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700133 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700134
Fred Quintana56285a62010-12-02 14:20:51 -0800135 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700136
137 private static final String TABLE_ACCOUNTS = "accounts";
138 private static final String ACCOUNTS_ID = "_id";
139 private static final String ACCOUNTS_NAME = "name";
140 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700141 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700142 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700143 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800144 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
145 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700146
147 private static final String TABLE_AUTHTOKENS = "authtokens";
148 private static final String AUTHTOKENS_ID = "_id";
149 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
150 private static final String AUTHTOKENS_TYPE = "type";
151 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
152
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700153 private static final String TABLE_GRANTS = "grants";
154 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
155 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
156 private static final String GRANTS_GRANTEE_UID = "uid";
157
Fred Quintana60307342009-03-24 22:48:12 -0700158 private static final String TABLE_EXTRAS = "extras";
159 private static final String EXTRAS_ID = "_id";
160 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
161 private static final String EXTRAS_KEY = "key";
162 private static final String EXTRAS_VALUE = "value";
163
164 private static final String TABLE_META = "meta";
165 private static final String META_KEY = "key";
166 private static final String META_VALUE = "value";
167
Amith Yamasani67df64b2012-12-14 12:09:36 -0800168 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
169
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700170 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
171 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700172 private static final Intent ACCOUNTS_CHANGED_INTENT;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700173 static {
174 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
175 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
176 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700177
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700178 private static final String COUNT_OF_MATCHING_GRANTS = ""
179 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
180 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
181 + " AND " + GRANTS_GRANTEE_UID + "=?"
182 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
183 + " AND " + ACCOUNTS_NAME + "=?"
184 + " AND " + ACCOUNTS_TYPE + "=?";
185
Fred Quintana56285a62010-12-02 14:20:51 -0800186 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
187 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700188
Fred Quintana56285a62010-12-02 14:20:51 -0800189 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
190 AUTHTOKENS_AUTHTOKEN};
191
192 private static final String SELECTION_USERDATA_BY_ACCOUNT =
193 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
194 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
195
Fred Quintanaa698f422009-04-08 19:14:54 -0700196 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700197 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
198
Amith Yamasani04e0d262012-02-14 11:50:53 -0800199 static class UserAccounts {
200 private final int userId;
201 private final DatabaseHelper openHelper;
202 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
203 credentialsPermissionNotificationIds =
204 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
205 private final HashMap<Account, Integer> signinRequiredNotificationIds =
206 new HashMap<Account, Integer>();
207 private final Object cacheLock = new Object();
208 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700209 private final HashMap<String, Account[]> accountCache =
210 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800211 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800212 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800213 new HashMap<Account, HashMap<String, String>>();
214 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800215 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800216 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700217
218 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700219 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700220
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700221 /**
222 * protected by the {@link #cacheLock}
223 *
224 * Caches the previous names associated with an account. Previous names
225 * should be cached because we expect that when an Account is renamed,
226 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
227 * want to know if the accounts they care about have been renamed.
228 *
229 * The previous names are wrapped in an {@link AtomicReference} so that
230 * we can distinguish between those accounts with no previous names and
231 * those whose previous names haven't been cached (yet).
232 */
233 private final HashMap<Account, AtomicReference<String>> previousNameCache =
234 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800235
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700236 private int debugDbInsertionPoint = -1;
237 private SQLiteStatement statementForLogging;
238
Amith Yamasani04e0d262012-02-14 11:50:53 -0800239 UserAccounts(Context context, int userId) {
240 this.userId = userId;
241 synchronized (cacheLock) {
242 openHelper = new DatabaseHelper(context, userId);
243 }
244 }
245 }
246
247 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
248
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700249 private static AtomicReference<AccountManagerService> sThis =
250 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700251 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700252
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700253 /**
254 * This should only be called by system code. One should only call this after the service
255 * has started.
256 * @return a reference to the AccountManagerService instance
257 * @hide
258 */
259 public static AccountManagerService getSingleton() {
260 return sThis.get();
261 }
Fred Quintana60307342009-03-24 22:48:12 -0700262
Fred Quintana56285a62010-12-02 14:20:51 -0800263 public AccountManagerService(Context context) {
264 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700265 }
266
Fred Quintana56285a62010-12-02 14:20:51 -0800267 public AccountManagerService(Context context, PackageManager packageManager,
268 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700269 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800270 mPackageManager = packageManager;
Svetoslavce852dd2015-09-08 14:36:35 -0700271 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700272
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700273 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700274
Fred Quintana56285a62010-12-02 14:20:51 -0800275 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800276 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700277
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700278 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800279
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800280 IntentFilter intentFilter = new IntentFilter();
281 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
282 intentFilter.addDataScheme("package");
283 mContext.registerReceiver(new BroadcastReceiver() {
284 @Override
285 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700286 // Don't delete accounts when updating a authenticator's
287 // package.
288 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700289 /* Purging data requires file io, don't block the main thread. This is probably
290 * less than ideal because we are introducing a race condition where old grants
291 * could be exercised until they are purged. But that race condition existed
292 * anyway with the broadcast receiver.
293 *
294 * Ideally, we would completely clear the cache, purge data from the database,
295 * and then rebuild the cache. All under the cache lock. But that change is too
296 * large at this point.
297 */
298 Runnable r = new Runnable() {
299 @Override
300 public void run() {
301 purgeOldGrantsAll();
302 }
303 };
304 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700305 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800306 }
307 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800308
Amith Yamasani13593602012-03-22 16:16:17 -0700309 IntentFilter userFilter = new IntentFilter();
310 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800311 userFilter.addAction(Intent.ACTION_USER_STARTED);
312 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700313 @Override
314 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800315 String action = intent.getAction();
316 if (Intent.ACTION_USER_REMOVED.equals(action)) {
317 onUserRemoved(intent);
318 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
319 onUserStarted(intent);
320 }
Amith Yamasani13593602012-03-22 16:16:17 -0700321 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800322 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800323 }
324
Dianne Hackborn164371f2013-10-01 19:10:13 -0700325 @Override
326 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
327 throws RemoteException {
328 try {
329 return super.onTransact(code, data, reply, flags);
330 } catch (RuntimeException e) {
331 // The account manager only throws security exceptions, so let's
332 // log all others.
333 if (!(e instanceof SecurityException)) {
334 Slog.wtf(TAG, "Account Manager Crash", e);
335 }
336 throw e;
337 }
338 }
339
Kenny Root26ff6622012-07-30 12:58:03 -0700340 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700341 }
342
Amith Yamasani258848d2012-08-10 17:06:33 -0700343 private UserManager getUserManager() {
344 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700345 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700346 }
347 return mUserManager;
348 }
349
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700350 /**
351 * Validate internal set of accounts against installed authenticators for
352 * given user. Clears cached authenticators before validating.
353 */
354 public void validateAccounts(int userId) {
355 final UserAccounts accounts = getUserAccounts(userId);
356
357 // Invalidate user-specific cache to make sure we catch any
358 // removed authenticators.
359 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
360 }
361
362 /**
363 * Validate internal set of accounts against installed authenticators for
364 * given user. Clear cached authenticators before validating when requested.
365 */
366 private void validateAccountsInternal(
367 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
368 if (invalidateAuthenticatorCache) {
369 mAuthenticatorCache.invalidateCache(accounts.userId);
370 }
371
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700372 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
373 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
374 mAuthenticatorCache.getAllServices(accounts.userId)) {
375 knownAuth.add(service.type);
376 }
377
Amith Yamasani04e0d262012-02-14 11:50:53 -0800378 synchronized (accounts.cacheLock) {
379 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800380 boolean accountDeleted = false;
381 Cursor cursor = db.query(TABLE_ACCOUNTS,
382 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800383 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800384 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800385 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800386 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700387 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800388 while (cursor.moveToNext()) {
389 final long accountId = cursor.getLong(0);
390 final String accountType = cursor.getString(1);
391 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700392
393 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700394 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800395 + accountType + " no longer has a registered authenticator");
396 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
397 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700398
399 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
400 accountId, accounts);
401
Fred Quintana56285a62010-12-02 14:20:51 -0800402 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800403 accounts.userDataCache.remove(account);
404 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700405 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800406 } else {
407 ArrayList<String> accountNames = accountNamesByType.get(accountType);
408 if (accountNames == null) {
409 accountNames = new ArrayList<String>();
410 accountNamesByType.put(accountType, accountNames);
411 }
412 accountNames.add(accountName);
413 }
414 }
Andy McFadden2f362292012-01-20 14:43:38 -0800415 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800416 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800417 final String accountType = cur.getKey();
418 final ArrayList<String> accountNames = cur.getValue();
419 final Account[] accountsForType = new Account[accountNames.size()];
420 int i = 0;
421 for (String accountName : accountNames) {
422 accountsForType[i] = new Account(accountName, accountType);
423 ++i;
424 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800425 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800426 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800427 } finally {
428 cursor.close();
429 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800430 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800431 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800432 }
433 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700434 }
435
Amith Yamasani04e0d262012-02-14 11:50:53 -0800436 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700437 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800438 }
439
440 protected UserAccounts getUserAccounts(int userId) {
441 synchronized (mUsers) {
442 UserAccounts accounts = mUsers.get(userId);
443 if (accounts == null) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700444 accounts = new UserAccounts(mContext, userId);
445 initializeDebugDbSizeAndCompileSqlStatementForLogging(
446 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800447 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700448 purgeOldGrants(accounts);
449 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800450 }
451 return accounts;
452 }
453 }
454
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700455 private void purgeOldGrantsAll() {
456 synchronized (mUsers) {
457 for (int i = 0; i < mUsers.size(); i++) {
458 purgeOldGrants(mUsers.valueAt(i));
459 }
460 }
461 }
462
463 private void purgeOldGrants(UserAccounts accounts) {
464 synchronized (accounts.cacheLock) {
465 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
466 final Cursor cursor = db.query(TABLE_GRANTS,
467 new String[]{GRANTS_GRANTEE_UID},
468 null, null, GRANTS_GRANTEE_UID, null, null);
469 try {
470 while (cursor.moveToNext()) {
471 final int uid = cursor.getInt(0);
472 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
473 if (packageExists) {
474 continue;
475 }
476 Log.d(TAG, "deleting grants for UID " + uid
477 + " because its package is no longer installed");
478 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
479 new String[]{Integer.toString(uid)});
480 }
481 } finally {
482 cursor.close();
483 }
484 }
485 }
486
Amith Yamasani13593602012-03-22 16:16:17 -0700487 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700488 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700489 if (userId < 1) return;
490
491 UserAccounts accounts;
492 synchronized (mUsers) {
493 accounts = mUsers.get(userId);
494 mUsers.remove(userId);
495 }
496 if (accounts == null) {
497 File dbFile = new File(getDatabaseName(userId));
498 dbFile.delete();
499 return;
500 }
501
502 synchronized (accounts.cacheLock) {
503 accounts.openHelper.close();
504 File dbFile = new File(getDatabaseName(userId));
505 dbFile.delete();
506 }
507 }
508
Amith Yamasani67df64b2012-12-14 12:09:36 -0800509 private void onUserStarted(Intent intent) {
510 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
511 if (userId < 1) return;
512
513 // Check if there's a shared account that needs to be created as an account
514 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
515 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavce852dd2015-09-08 14:36:35 -0700516 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Amith Yamasani67df64b2012-12-14 12:09:36 -0800517 for (Account sa : sharedAccounts) {
518 if (ArrayUtils.contains(accounts, sa)) continue;
519 // Account doesn't exist. Copy it now.
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000520 copyAccountToUser(null /*no response*/, sa, UserHandle.USER_OWNER, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800521 }
522 }
523
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700524 @Override
525 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700526 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700527 }
528
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800529 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700530 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700531 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800532 if (Log.isLoggable(TAG, Log.VERBOSE)) {
533 Log.v(TAG, "getPassword: " + account
534 + ", caller's uid " + Binder.getCallingUid()
535 + ", pid " + Binder.getCallingPid());
536 }
Fred Quintana382601f2010-03-25 12:25:10 -0700537 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000538 int userId = UserHandle.getCallingUserId();
539 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700540 String msg = String.format(
541 "uid %s cannot get secrets for accounts of type: %s",
542 callingUid,
543 account.type);
544 throw new SecurityException(msg);
545 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700546 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700547 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700548 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800549 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700550 } finally {
551 restoreCallingIdentity(identityToken);
552 }
553 }
554
Amith Yamasani04e0d262012-02-14 11:50:53 -0800555 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700556 if (account == null) {
557 return null;
558 }
559
Amith Yamasani04e0d262012-02-14 11:50:53 -0800560 synchronized (accounts.cacheLock) {
561 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800562 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
563 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
564 new String[]{account.name, account.type}, null, null, null);
565 try {
566 if (cursor.moveToNext()) {
567 return cursor.getString(0);
568 }
569 return null;
570 } finally {
571 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700572 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700573 }
574 }
575
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800576 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700577 public String getPreviousName(Account account) {
578 if (Log.isLoggable(TAG, Log.VERBOSE)) {
579 Log.v(TAG, "getPreviousName: " + account
580 + ", caller's uid " + Binder.getCallingUid()
581 + ", pid " + Binder.getCallingPid());
582 }
583 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700584 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700585 long identityToken = clearCallingIdentity();
586 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700587 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700588 return readPreviousNameInternal(accounts, account);
589 } finally {
590 restoreCallingIdentity(identityToken);
591 }
592 }
593
594 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
595 if (account == null) {
596 return null;
597 }
598 synchronized (accounts.cacheLock) {
599 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
600 if (previousNameRef == null) {
601 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
602 Cursor cursor = db.query(
603 TABLE_ACCOUNTS,
604 new String[]{ ACCOUNTS_PREVIOUS_NAME },
605 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
606 new String[] { account.name, account.type },
607 null,
608 null,
609 null);
610 try {
611 if (cursor.moveToNext()) {
612 String previousName = cursor.getString(0);
613 previousNameRef = new AtomicReference<String>(previousName);
614 accounts.previousNameCache.put(account, previousNameRef);
615 return previousName;
616 } else {
617 return null;
618 }
619 } finally {
620 cursor.close();
621 }
622 } else {
623 return previousNameRef.get();
624 }
625 }
626 }
627
628 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700629 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700630 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800631 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700632 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
633 account, key, callingUid, Binder.getCallingPid());
634 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800635 }
Fred Quintana382601f2010-03-25 12:25:10 -0700636 if (account == null) throw new IllegalArgumentException("account is null");
637 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000638 int userId = UserHandle.getCallingUserId();
639 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700640 String msg = String.format(
641 "uid %s cannot get user data for accounts of type: %s",
642 callingUid,
643 account.type);
644 throw new SecurityException(msg);
645 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700646 long identityToken = clearCallingIdentity();
647 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700648 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800649 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700650 } finally {
651 restoreCallingIdentity(identityToken);
652 }
653 }
654
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800655 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100656 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700657 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800658 if (Log.isLoggable(TAG, Log.VERBOSE)) {
659 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100660 + "for user id " + userId
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700661 + "caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800662 + ", pid " + Binder.getCallingPid());
663 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100664 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700665 if (isCrossUser(callingUid, userId)) {
666 throw new SecurityException(
667 String.format(
668 "User %s tying to get authenticator types for %s" ,
669 UserHandle.getCallingUserId(),
670 userId));
671 }
672
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700673 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700674 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000675 return getAuthenticatorTypesInternal(userId);
676
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700677 } finally {
678 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700679 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700680 }
681
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000682 /**
683 * Should only be called inside of a clearCallingIdentity block.
684 */
685 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
686 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
687 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
688 AuthenticatorDescription[] types =
689 new AuthenticatorDescription[authenticatorCollection.size()];
690 int i = 0;
691 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
692 : authenticatorCollection) {
693 types[i] = authenticator.type;
694 i++;
695 }
696 return types;
697 }
698
699
700
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700701 private boolean isCrossUser(int callingUid, int userId) {
702 return (userId != UserHandle.getCallingUserId()
703 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100704 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700705 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
706 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100707 }
708
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700709 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700710 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700711 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800712 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700713 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700714 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800715 + ", pid " + Binder.getCallingPid());
716 }
Fred Quintana382601f2010-03-25 12:25:10 -0700717 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000718 int userId = UserHandle.getCallingUserId();
719 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700720 String msg = String.format(
721 "uid %s cannot explicitly add accounts of type: %s",
722 callingUid,
723 account.type);
724 throw new SecurityException(msg);
725 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700726 /*
727 * Child users are not allowed to add accounts. Only the accounts that are
728 * shared by the parent profile can be added to child profile.
729 *
730 * TODO: Only allow accounts that were shared to be added by
731 * a limited user.
732 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700733
Fred Quintana60307342009-03-24 22:48:12 -0700734 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700735 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700736 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700737 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000738 return addAccountInternal(accounts, account, password, extras, false, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700739 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700740 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700741 }
742 }
743
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000744 @Override
745 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
746 int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700747 int callingUid = Binder.getCallingUid();
748 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
749 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000750 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700751 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800752 final UserAccounts fromAccounts = getUserAccounts(userFrom);
753 final UserAccounts toAccounts = getUserAccounts(userTo);
754 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000755 if (response != null) {
756 Bundle result = new Bundle();
757 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
758 try {
759 response.onResult(result);
760 } catch (RemoteException e) {
761 Slog.w(TAG, "Failed to report error back to the client." + e);
762 }
763 }
764 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800765 }
766
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000767 Slog.d(TAG, "Copying account " + account.name
768 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800769 long identityToken = clearCallingIdentity();
770 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000771 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800772 false /* stripAuthTokenFromResult */, account.name,
773 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700774 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800775 protected String toDebugString(long now) {
776 return super.toDebugString(now) + ", getAccountCredentialsForClone"
777 + ", " + account.type;
778 }
779
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700780 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800781 public void run() throws RemoteException {
782 mAuthenticator.getAccountCredentialsForCloning(this, account);
783 }
784
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700785 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800786 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000787 if (result != null
788 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
789 // Create a Session for the target user and pass in the bundle
790 completeCloningAccount(response, result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800791 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800792 super.onResult(result);
793 }
794 }
795 }.bind();
796 } finally {
797 restoreCallingIdentity(identityToken);
798 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800799 }
800
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800801 @Override
802 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700803 final int callingUid = Binder.getCallingUid();
804 if (Log.isLoggable(TAG, Log.VERBOSE)) {
805 String msg = String.format(
806 "accountAuthenticated( account: %s, callerUid: %s)",
807 account,
808 callingUid);
809 Log.v(TAG, msg);
810 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800811 if (account == null) {
812 throw new IllegalArgumentException("account is null");
813 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000814 int userId = UserHandle.getCallingUserId();
815 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700816 String msg = String.format(
817 "uid %s cannot notify authentication for accounts of type: %s",
818 callingUid,
819 account.type);
820 throw new SecurityException(msg);
821 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000822
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800823 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
824 return false;
825 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000826
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700827 long identityToken = clearCallingIdentity();
828 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000829 UserAccounts accounts = getUserAccounts(userId);
830 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700831 } finally {
832 restoreCallingIdentity(identityToken);
833 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -0700834 }
835
836 private boolean updateLastAuthenticatedTime(Account account) {
837 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800838 synchronized (accounts.cacheLock) {
839 final ContentValues values = new ContentValues();
840 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
841 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
842 int i = db.update(
843 TABLE_ACCOUNTS,
844 values,
845 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
846 new String[] {
847 account.name, account.type
848 });
849 if (i > 0) {
850 return true;
851 }
852 }
853 return false;
854 }
855
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000856 private void completeCloningAccount(IAccountManagerResponse response,
857 final Bundle accountCredentials, final Account account, final UserAccounts targetUser) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800858 long id = clearCallingIdentity();
859 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000860 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800861 false /* stripAuthTokenFromResult */, account.name,
862 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700863 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800864 protected String toDebugString(long now) {
865 return super.toDebugString(now) + ", getAccountCredentialsForClone"
866 + ", " + account.type;
867 }
868
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700869 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800870 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700871 // Confirm that the owner's account still exists before this step.
872 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
873 synchronized (owner.cacheLock) {
Svetoslavce852dd2015-09-08 14:36:35 -0700874 for (Account acc : getAccounts(UserHandle.USER_OWNER,
875 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700876 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000877 mAuthenticator.addAccountFromCredentials(
878 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700879 break;
880 }
881 }
882 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800883 }
884
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700885 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800886 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000887 // TODO: Anything to do if if succedded?
888 // TODO: If it failed: Show error notification? Should we remove the shadow
889 // account to avoid retries?
890 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800891 }
892
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700893 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800894 public void onError(int errorCode, String errorMessage) {
895 super.onError(errorCode, errorMessage);
896 // TODO: Show error notification to user
897 // TODO: Should we remove the shadow account so that it doesn't keep trying?
898 }
899
900 }.bind();
901 } finally {
902 restoreCallingIdentity(id);
903 }
904 }
905
Amith Yamasani04e0d262012-02-14 11:50:53 -0800906 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700907 Bundle extras, boolean restricted, int callingUid) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700908 if (account == null) {
909 return false;
910 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800911 synchronized (accounts.cacheLock) {
912 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800913 db.beginTransaction();
914 try {
915 long numMatches = DatabaseUtils.longForQuery(db,
916 "select count(*) from " + TABLE_ACCOUNTS
917 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
918 new String[]{account.name, account.type});
919 if (numMatches > 0) {
920 Log.w(TAG, "insertAccountIntoDatabase: " + account
921 + ", skipping since the account already exists");
922 return false;
923 }
924 ContentValues values = new ContentValues();
925 values.put(ACCOUNTS_NAME, account.name);
926 values.put(ACCOUNTS_TYPE, account.type);
927 values.put(ACCOUNTS_PASSWORD, password);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800928 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800929 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
930 if (accountId < 0) {
931 Log.w(TAG, "insertAccountIntoDatabase: " + account
932 + ", skipping the DB insert failed");
933 return false;
934 }
935 if (extras != null) {
936 for (String key : extras.keySet()) {
937 final String value = extras.getString(key);
938 if (insertExtraLocked(db, accountId, key, value) < 0) {
939 Log.w(TAG, "insertAccountIntoDatabase: " + account
940 + ", skipping since insertExtra failed for key " + key);
941 return false;
942 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700943 }
944 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800945 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700946
947 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
948 accounts, callingUid);
949
Amith Yamasani04e0d262012-02-14 11:50:53 -0800950 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800951 } finally {
952 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700953 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800954 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700955 }
956 if (accounts.userId == UserHandle.USER_OWNER) {
957 addAccountToLimitedUsers(account);
958 }
959 return true;
960 }
961
962 /**
963 * Adds the account to all limited users as shared accounts. If the user is currently
964 * running, then clone the account too.
965 * @param account the account to share with limited users
966 */
967 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700968 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700969 for (UserInfo user : users) {
970 if (user.isRestricted()) {
971 addSharedAccountAsUser(account, user.id);
972 try {
973 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
974 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
975 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
976 account));
977 }
978 } catch (RemoteException re) {
979 // Shouldn't happen
980 }
981 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700982 }
983 }
984
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800985 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700986 ContentValues values = new ContentValues();
987 values.put(EXTRAS_KEY, key);
988 values.put(EXTRAS_ACCOUNTS_ID, accountId);
989 values.put(EXTRAS_VALUE, value);
990 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
991 }
992
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800993 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -0800994 public void hasFeatures(IAccountManagerResponse response,
Svetoslavce852dd2015-09-08 14:36:35 -0700995 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700996 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800997 if (Log.isLoggable(TAG, Log.VERBOSE)) {
998 Log.v(TAG, "hasFeatures: " + account
999 + ", response " + response
1000 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001001 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001002 + ", pid " + Binder.getCallingPid());
1003 }
Fred Quintana382601f2010-03-25 12:25:10 -07001004 if (response == null) throw new IllegalArgumentException("response is null");
1005 if (account == null) throw new IllegalArgumentException("account is null");
1006 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001007 int userId = UserHandle.getCallingUserId();
Svetoslavce852dd2015-09-08 14:36:35 -07001008 checkReadAccountsPermitted(callingUid, account.type, userId,
1009 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001010
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001011 long identityToken = clearCallingIdentity();
1012 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001013 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001014 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001015 } finally {
1016 restoreCallingIdentity(identityToken);
1017 }
1018 }
1019
1020 private class TestFeaturesSession extends Session {
1021 private final String[] mFeatures;
1022 private final Account mAccount;
1023
Amith Yamasani04e0d262012-02-14 11:50:53 -08001024 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001025 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001026 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001027 true /* stripAuthTokenFromResult */, account.name,
1028 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001029 mFeatures = features;
1030 mAccount = account;
1031 }
1032
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001033 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001034 public void run() throws RemoteException {
1035 try {
1036 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1037 } catch (RemoteException e) {
1038 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1039 }
1040 }
1041
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001042 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001043 public void onResult(Bundle result) {
1044 IAccountManagerResponse response = getResponseAndClose();
1045 if (response != null) {
1046 try {
1047 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001048 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001049 return;
1050 }
Fred Quintana56285a62010-12-02 14:20:51 -08001051 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1052 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1053 + response);
1054 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001055 final Bundle newResult = new Bundle();
1056 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1057 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1058 response.onResult(newResult);
1059 } catch (RemoteException e) {
1060 // if the caller is dead then there is no one to care about remote exceptions
1061 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1062 Log.v(TAG, "failure while notifying response", e);
1063 }
1064 }
1065 }
1066 }
1067
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001068 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001069 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001070 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001071 + ", " + mAccount
1072 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1073 }
1074 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001075
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001076 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001077 public void renameAccount(
1078 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001079 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001080 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1081 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001082 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001083 + ", pid " + Binder.getCallingPid());
1084 }
1085 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001086 int userId = UserHandle.getCallingUserId();
1087 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001088 String msg = String.format(
1089 "uid %s cannot rename accounts of type: %s",
1090 callingUid,
1091 accountToRename.type);
1092 throw new SecurityException(msg);
1093 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001094 long identityToken = clearCallingIdentity();
1095 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001096 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001097 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001098 Bundle result = new Bundle();
1099 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1100 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1101 try {
1102 response.onResult(result);
1103 } catch (RemoteException e) {
1104 Log.w(TAG, e.getMessage());
1105 }
1106 } finally {
1107 restoreCallingIdentity(identityToken);
1108 }
1109 }
1110
1111 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001112 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001113 Account resultAccount = null;
1114 /*
1115 * Cancel existing notifications. Let authenticators
1116 * re-post notifications as required. But we don't know if
1117 * the authenticators have bound their notifications to
1118 * now stale account name data.
1119 *
1120 * With a rename api, we might not need to do this anymore but it
1121 * shouldn't hurt.
1122 */
1123 cancelNotification(
1124 getSigninRequiredNotificationId(accounts, accountToRename),
1125 new UserHandle(accounts.userId));
1126 synchronized(accounts.credentialsPermissionNotificationIds) {
1127 for (Pair<Pair<Account, String>, Integer> pair:
1128 accounts.credentialsPermissionNotificationIds.keySet()) {
1129 if (accountToRename.equals(pair.first.first)) {
1130 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1131 cancelNotification(id, new UserHandle(accounts.userId));
1132 }
1133 }
1134 }
1135 synchronized (accounts.cacheLock) {
1136 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1137 db.beginTransaction();
1138 boolean isSuccessful = false;
1139 Account renamedAccount = new Account(newName, accountToRename.type);
1140 try {
1141 final ContentValues values = new ContentValues();
1142 values.put(ACCOUNTS_NAME, newName);
1143 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
1144 final long accountId = getAccountIdLocked(db, accountToRename);
1145 if (accountId >= 0) {
1146 final String[] argsAccountId = { String.valueOf(accountId) };
1147 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1148 db.setTransactionSuccessful();
1149 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001150 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1151 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001152 }
1153 } finally {
1154 db.endTransaction();
1155 if (isSuccessful) {
1156 /*
1157 * Database transaction was successful. Clean up cached
1158 * data associated with the account in the user profile.
1159 */
1160 insertAccountIntoCacheLocked(accounts, renamedAccount);
1161 /*
1162 * Extract the data and token caches before removing the
1163 * old account to preserve the user data associated with
1164 * the account.
1165 */
1166 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1167 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1168 removeAccountFromCacheLocked(accounts, accountToRename);
1169 /*
1170 * Update the cached data associated with the renamed
1171 * account.
1172 */
1173 accounts.userDataCache.put(renamedAccount, tmpData);
1174 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1175 accounts.previousNameCache.put(
1176 renamedAccount,
1177 new AtomicReference<String>(accountToRename.name));
1178 resultAccount = renamedAccount;
1179
1180 if (accounts.userId == UserHandle.USER_OWNER) {
1181 /*
1182 * Owner's account was renamed, rename the account for
1183 * those users with which the account was shared.
1184 */
1185 List<UserInfo> users = mUserManager.getUsers(true);
1186 for (UserInfo user : users) {
1187 if (!user.isPrimary() && user.isRestricted()) {
1188 renameSharedAccountAsUser(accountToRename, newName, user.id);
1189 }
1190 }
1191 }
1192 sendAccountsChangedBroadcast(accounts.userId);
1193 }
1194 }
1195 }
1196 return resultAccount;
1197 }
1198
1199 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001200 public void removeAccount(IAccountManagerResponse response, Account account,
1201 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001202 removeAccountAsUser(
1203 response,
1204 account,
1205 expectActivityLaunch,
1206 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001207 }
1208
1209 @Override
1210 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001211 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001212 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001213 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1214 Log.v(TAG, "removeAccount: " + account
1215 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001216 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001217 + ", pid " + Binder.getCallingPid()
1218 + ", for user id " + userId);
1219 }
1220 if (response == null) throw new IllegalArgumentException("response is null");
1221 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001222 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001223 if (isCrossUser(callingUid, userId)) {
1224 throw new SecurityException(
1225 String.format(
1226 "User %s tying remove account for %s" ,
1227 UserHandle.getCallingUserId(),
1228 userId));
1229 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001230 /*
1231 * Only the system or authenticator should be allowed to remove accounts for that
1232 * authenticator. This will let users remove accounts (via Settings in the system) but not
1233 * arbitrary applications (like competing authenticators).
1234 */
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001235 UserHandle user = new UserHandle(userId);
1236 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1237 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001238 String msg = String.format(
1239 "uid %s cannot remove accounts of type: %s",
1240 callingUid,
1241 account.type);
1242 throw new SecurityException(msg);
1243 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001244 if (!canUserModifyAccounts(userId)) {
1245 try {
1246 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1247 "User cannot modify accounts");
1248 } catch (RemoteException re) {
1249 }
1250 return;
1251 }
1252 if (!canUserModifyAccountsForType(userId, account.type)) {
1253 try {
1254 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1255 "User cannot modify accounts of this type (policy).");
1256 } catch (RemoteException re) {
1257 }
1258 return;
1259 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001260 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001261 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001262 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001263 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001264 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001265 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001266 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001267 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001268 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001269 }
1270 }
1271 }
1272
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001273 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1274
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001275 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001276 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1277 } finally {
1278 restoreCallingIdentity(identityToken);
1279 }
1280 }
1281
1282 @Override
1283 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001284 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001285 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1286 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001287 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001288 + ", pid " + Binder.getCallingPid());
1289 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001290 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001291 if (account == null) {
1292 /*
1293 * Null accounts should result in returning false, as per
1294 * AccountManage.addAccountExplicitly(...) java doc.
1295 */
1296 Log.e(TAG, "account is null");
1297 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001298 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001299 String msg = String.format(
1300 "uid %s cannot explicitly add accounts of type: %s",
1301 callingUid,
1302 account.type);
1303 throw new SecurityException(msg);
1304 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001305 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001306 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
1307 return false;
1308 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001309 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001310 long identityToken = clearCallingIdentity();
1311 try {
1312 return removeAccountInternal(accounts, account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001313 } finally {
1314 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001315 }
Fred Quintana60307342009-03-24 22:48:12 -07001316 }
1317
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001318 private class RemoveAccountSession extends Session {
1319 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001320 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001321 Account account, boolean expectActivityLaunch) {
1322 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001323 true /* stripAuthTokenFromResult */, account.name,
1324 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001325 mAccount = account;
1326 }
1327
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001328 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001329 protected String toDebugString(long now) {
1330 return super.toDebugString(now) + ", removeAccount"
1331 + ", account " + mAccount;
1332 }
1333
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001334 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001335 public void run() throws RemoteException {
1336 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1337 }
1338
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001339 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001340 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001341 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1342 && !result.containsKey(AccountManager.KEY_INTENT)) {
1343 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001344 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001345 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001346 }
1347 IAccountManagerResponse response = getResponseAndClose();
1348 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001349 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1350 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1351 + response);
1352 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001353 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001354 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001355 try {
1356 response.onResult(result2);
1357 } catch (RemoteException e) {
1358 // ignore
1359 }
1360 }
1361 }
1362 super.onResult(result);
1363 }
1364 }
1365
Amith Yamasani04e0d262012-02-14 11:50:53 -08001366 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001367 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001368 removeAccountInternal(getUserAccountsForCaller(), account);
1369 }
1370
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001371 private boolean removeAccountInternal(UserAccounts accounts, Account account) {
1372 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001373 synchronized (accounts.cacheLock) {
1374 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001375 final long accountId = getAccountIdLocked(db, account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001376 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1377 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001378 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001379 removeAccountFromCacheLocked(accounts, account);
1380 sendAccountsChangedBroadcast(accounts.userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001381
1382 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001383 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001384 if (accounts.userId == UserHandle.USER_OWNER) {
1385 // Owner's account was removed, remove from any users that are sharing
1386 // this account.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001387 int callingUid = getCallingUid();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001388 long id = Binder.clearCallingIdentity();
1389 try {
1390 List<UserInfo> users = mUserManager.getUsers(true);
1391 for (UserInfo user : users) {
1392 if (!user.isPrimary() && user.isRestricted()) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001393 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001394 }
1395 }
1396 } finally {
1397 Binder.restoreCallingIdentity(id);
1398 }
1399 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001400 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001401 }
1402
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001403 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001404 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001405 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001406 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1407 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001408 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001409 + ", pid " + Binder.getCallingPid());
1410 }
Fred Quintana382601f2010-03-25 12:25:10 -07001411 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1412 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001413 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001414 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001415 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001416 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001417 synchronized (accounts.cacheLock) {
1418 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001419 db.beginTransaction();
1420 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001421 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001422 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001423 db.setTransactionSuccessful();
1424 } finally {
1425 db.endTransaction();
1426 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001427 }
Fred Quintana60307342009-03-24 22:48:12 -07001428 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001429 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001430 }
1431 }
1432
Carlos Valdivia91979be2015-05-22 14:11:35 -07001433 private void invalidateCustomTokenLocked(
1434 UserAccounts accounts,
1435 String accountType,
1436 String authToken) {
1437 if (authToken == null || accountType == null) {
1438 return;
1439 }
1440 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001441 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001442 }
1443
Amith Yamasani04e0d262012-02-14 11:50:53 -08001444 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1445 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001446 if (authToken == null || accountType == null) {
1447 return;
1448 }
Fred Quintana33269202009-04-20 16:05:10 -07001449 Cursor cursor = db.rawQuery(
1450 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1451 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1452 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1453 + " FROM " + TABLE_ACCOUNTS
1454 + " JOIN " + TABLE_AUTHTOKENS
1455 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1456 + " = " + AUTHTOKENS_ACCOUNTS_ID
1457 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1458 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1459 new String[]{authToken, accountType});
1460 try {
1461 while (cursor.moveToNext()) {
1462 long authTokenId = cursor.getLong(0);
1463 String accountName = cursor.getString(1);
1464 String authTokenType = cursor.getString(2);
1465 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001466 writeAuthTokenIntoCacheLocked(
1467 accounts,
1468 db,
1469 new Account(accountName, accountType),
1470 authTokenType,
1471 null);
Fred Quintana60307342009-03-24 22:48:12 -07001472 }
Fred Quintana33269202009-04-20 16:05:10 -07001473 } finally {
1474 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001475 }
1476 }
1477
Carlos Valdivia91979be2015-05-22 14:11:35 -07001478 private void saveCachedToken(
1479 UserAccounts accounts,
1480 Account account,
1481 String callerPkg,
1482 byte[] callerSigDigest,
1483 String tokenType,
1484 String token,
1485 long expiryMillis) {
1486
1487 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1488 return;
1489 }
1490 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1491 new UserHandle(accounts.userId));
1492 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001493 accounts.accountTokenCaches.put(
1494 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001495 }
1496 }
1497
Amith Yamasani04e0d262012-02-14 11:50:53 -08001498 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1499 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001500 if (account == null || type == null) {
1501 return false;
1502 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001503 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1504 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001505 synchronized (accounts.cacheLock) {
1506 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001507 db.beginTransaction();
1508 try {
1509 long accountId = getAccountIdLocked(db, account);
1510 if (accountId < 0) {
1511 return false;
1512 }
1513 db.delete(TABLE_AUTHTOKENS,
1514 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1515 new String[]{type});
1516 ContentValues values = new ContentValues();
1517 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1518 values.put(AUTHTOKENS_TYPE, type);
1519 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1520 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1521 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001522 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001523 return true;
1524 }
Fred Quintana33269202009-04-20 16:05:10 -07001525 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001526 } finally {
1527 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001528 }
Fred Quintana60307342009-03-24 22:48:12 -07001529 }
1530 }
1531
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001532 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001533 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001534 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001535 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1536 Log.v(TAG, "peekAuthToken: " + account
1537 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001538 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001539 + ", pid " + Binder.getCallingPid());
1540 }
Fred Quintana382601f2010-03-25 12:25:10 -07001541 if (account == null) throw new IllegalArgumentException("account is null");
1542 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001543 int userId = UserHandle.getCallingUserId();
1544 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001545 String msg = String.format(
1546 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1547 callingUid,
1548 account.type);
1549 throw new SecurityException(msg);
1550 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001551 long identityToken = clearCallingIdentity();
1552 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001553 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001554 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001555 } finally {
1556 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001557 }
Fred Quintana60307342009-03-24 22:48:12 -07001558 }
1559
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001560 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001561 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001562 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001563 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1564 Log.v(TAG, "setAuthToken: " + account
1565 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001566 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001567 + ", pid " + Binder.getCallingPid());
1568 }
Fred Quintana382601f2010-03-25 12:25:10 -07001569 if (account == null) throw new IllegalArgumentException("account is null");
1570 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001571 int userId = UserHandle.getCallingUserId();
1572 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001573 String msg = String.format(
1574 "uid %s cannot set auth tokens associated with accounts of type: %s",
1575 callingUid,
1576 account.type);
1577 throw new SecurityException(msg);
1578 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001579 long identityToken = clearCallingIdentity();
1580 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001581 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001582 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001583 } finally {
1584 restoreCallingIdentity(identityToken);
1585 }
Fred Quintana60307342009-03-24 22:48:12 -07001586 }
1587
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001588 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001589 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001590 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001591 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1592 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001593 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001594 + ", pid " + Binder.getCallingPid());
1595 }
Fred Quintana382601f2010-03-25 12:25:10 -07001596 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001597 int userId = UserHandle.getCallingUserId();
1598 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001599 String msg = String.format(
1600 "uid %s cannot set secrets for accounts of type: %s",
1601 callingUid,
1602 account.type);
1603 throw new SecurityException(msg);
1604 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001605 long identityToken = clearCallingIdentity();
1606 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001607 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001608 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001609 } finally {
1610 restoreCallingIdentity(identityToken);
1611 }
Fred Quintana60307342009-03-24 22:48:12 -07001612 }
1613
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001614 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1615 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001616 if (account == null) {
1617 return;
1618 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001619 synchronized (accounts.cacheLock) {
1620 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001621 db.beginTransaction();
1622 try {
1623 final ContentValues values = new ContentValues();
1624 values.put(ACCOUNTS_PASSWORD, password);
1625 final long accountId = getAccountIdLocked(db, account);
1626 if (accountId >= 0) {
1627 final String[] argsAccountId = {String.valueOf(accountId)};
1628 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1629 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001630 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001631 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001632 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001633
1634 String action = (password == null || password.length() == 0) ?
1635 DebugDbHelper.ACTION_CLEAR_PASSWORD
1636 : DebugDbHelper.ACTION_SET_PASSWORD;
1637 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001638 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001639 } finally {
1640 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001641 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001642 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001643 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001644 }
1645
Amith Yamasani04e0d262012-02-14 11:50:53 -08001646 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001647 Log.i(TAG, "the accounts changed, sending broadcast of "
1648 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001649 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001650 }
1651
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001652 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001653 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001654 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001655 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1656 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001657 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001658 + ", pid " + Binder.getCallingPid());
1659 }
Fred Quintana382601f2010-03-25 12:25:10 -07001660 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001661 int userId = UserHandle.getCallingUserId();
1662 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001663 String msg = String.format(
1664 "uid %s cannot clear passwords for accounts of type: %s",
1665 callingUid,
1666 account.type);
1667 throw new SecurityException(msg);
1668 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001669 long identityToken = clearCallingIdentity();
1670 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001671 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001672 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001673 } finally {
1674 restoreCallingIdentity(identityToken);
1675 }
Fred Quintana60307342009-03-24 22:48:12 -07001676 }
1677
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001678 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001679 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001680 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001681 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1682 Log.v(TAG, "setUserData: " + account
1683 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001684 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001685 + ", pid " + Binder.getCallingPid());
1686 }
Fred Quintana382601f2010-03-25 12:25:10 -07001687 if (key == null) throw new IllegalArgumentException("key is null");
1688 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001689 int userId = UserHandle.getCallingUserId();
1690 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001691 String msg = String.format(
1692 "uid %s cannot set user data for accounts of type: %s",
1693 callingUid,
1694 account.type);
1695 throw new SecurityException(msg);
1696 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001697 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001698 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001699 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001700 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001701 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001702 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001703 }
1704 }
1705
Amith Yamasani04e0d262012-02-14 11:50:53 -08001706 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1707 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001708 if (account == null || key == null) {
1709 return;
1710 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001711 synchronized (accounts.cacheLock) {
1712 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001713 db.beginTransaction();
1714 try {
1715 long accountId = getAccountIdLocked(db, account);
1716 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001717 return;
1718 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001719 long extrasId = getExtrasIdLocked(db, accountId, key);
1720 if (extrasId < 0 ) {
1721 extrasId = insertExtraLocked(db, accountId, key, value);
1722 if (extrasId < 0) {
1723 return;
1724 }
1725 } else {
1726 ContentValues values = new ContentValues();
1727 values.put(EXTRAS_VALUE, value);
1728 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1729 return;
1730 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001731
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001732 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001733 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001734 db.setTransactionSuccessful();
1735 } finally {
1736 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001737 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001738 }
1739 }
1740
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001741 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001742 if (result == null) {
1743 Log.e(TAG, "the result is unexpectedly null", new Exception());
1744 }
1745 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1746 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1747 + response);
1748 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001749 try {
1750 response.onResult(result);
1751 } catch (RemoteException e) {
1752 // if the caller is dead then there is no one to care about remote
1753 // exceptions
1754 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1755 Log.v(TAG, "failure while notifying response", e);
1756 }
1757 }
1758 }
1759
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001760 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001761 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1762 final String authTokenType)
1763 throws RemoteException {
1764 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001765 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1766
Fred Quintanad9640ec2012-05-23 12:37:00 -07001767 final int callingUid = getCallingUid();
1768 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001769 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001770 throw new SecurityException("can only call from system");
1771 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001772 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001773 long identityToken = clearCallingIdentity();
1774 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001775 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001776 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1777 false /* stripAuthTokenFromResult */, null /* accountName */,
1778 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001779 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001780 protected String toDebugString(long now) {
1781 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001782 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001783 + ", authTokenType " + authTokenType;
1784 }
1785
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001786 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001787 public void run() throws RemoteException {
1788 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1789 }
1790
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001791 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001792 public void onResult(Bundle result) {
1793 if (result != null) {
1794 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1795 Bundle bundle = new Bundle();
1796 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1797 super.onResult(bundle);
1798 return;
1799 } else {
1800 super.onResult(result);
1801 }
1802 }
1803 }.bind();
1804 } finally {
1805 restoreCallingIdentity(identityToken);
1806 }
1807 }
1808
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001809 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07001810 public void getAuthToken(
1811 IAccountManagerResponse response,
1812 final Account account,
1813 final String authTokenType,
1814 final boolean notifyOnAuthFailure,
1815 final boolean expectActivityLaunch,
1816 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001817 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1818 Log.v(TAG, "getAuthToken: " + account
1819 + ", response " + response
1820 + ", authTokenType " + authTokenType
1821 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1822 + ", expectActivityLaunch " + expectActivityLaunch
1823 + ", caller's uid " + Binder.getCallingUid()
1824 + ", pid " + Binder.getCallingPid());
1825 }
Fred Quintana382601f2010-03-25 12:25:10 -07001826 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001827 try {
1828 if (account == null) {
1829 Slog.w(TAG, "getAuthToken called with null account");
1830 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1831 return;
1832 }
1833 if (authTokenType == null) {
1834 Slog.w(TAG, "getAuthToken called with null authTokenType");
1835 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1836 return;
1837 }
1838 } catch (RemoteException e) {
1839 Slog.w(TAG, "Failed to report error back to the client." + e);
1840 return;
1841 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001842 int userId = UserHandle.getCallingUserId();
1843 long ident = Binder.clearCallingIdentity();
1844 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001845 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001846 try {
1847 accounts = getUserAccounts(userId);
1848 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1849 AuthenticatorDescription.newKey(account.type), accounts.userId);
1850 } finally {
1851 Binder.restoreCallingIdentity(ident);
1852 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001853
Costin Manolachea40c6302010-12-13 14:50:45 -08001854 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07001855 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08001856
1857 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001858 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001859 final boolean permissionGranted =
1860 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001861
Carlos Valdivia91979be2015-05-22 14:11:35 -07001862 // Get the calling package. We will use it for the purpose of caching.
1863 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07001864 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001865 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07001866 try {
1867 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
1868 } finally {
1869 Binder.restoreCallingIdentity(ident);
1870 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001871 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
1872 String msg = String.format(
1873 "Uid %s is attempting to illegally masquerade as package %s!",
1874 callerUid,
1875 callerPkg);
1876 throw new SecurityException(msg);
1877 }
1878
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001879 // let authenticator know the identity of the caller
1880 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1881 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07001882
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001883 if (notifyOnAuthFailure) {
1884 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001885 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001886
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001887 long identityToken = clearCallingIdentity();
1888 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07001889 // Distill the caller's package signatures into a single digest.
1890 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
1891
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001892 // if the caller has permission, do the peek. otherwise go the more expensive
1893 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001894 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001895 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001896 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001897 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001898 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1899 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1900 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001901 onResult(response, result);
1902 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001903 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001904 }
1905
Carlos Valdivia91979be2015-05-22 14:11:35 -07001906 if (customTokens) {
1907 /*
1908 * Look up tokens in the new cache only if the loginOptions don't have parameters
1909 * outside of those expected to be injected by the AccountManager, e.g.
1910 * ANDORID_PACKAGE_NAME.
1911 */
1912 String token = readCachedTokenInternal(
1913 accounts,
1914 account,
1915 authTokenType,
1916 callerPkg,
1917 callerPkgSigDigest);
1918 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001919 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1920 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
1921 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001922 Bundle result = new Bundle();
1923 result.putString(AccountManager.KEY_AUTHTOKEN, token);
1924 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1925 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
1926 onResult(response, result);
1927 return;
1928 }
1929 }
1930
Amith Yamasani04e0d262012-02-14 11:50:53 -08001931 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001932 false /* stripAuthTokenFromResult */, account.name,
1933 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001934 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001935 protected String toDebugString(long now) {
1936 if (loginOptions != null) loginOptions.keySet();
1937 return super.toDebugString(now) + ", getAuthToken"
1938 + ", " + account
1939 + ", authTokenType " + authTokenType
1940 + ", loginOptions " + loginOptions
1941 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1942 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001943
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001944 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001945 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001946 // If the caller doesn't have permission then create and return the
1947 // "grant permission" intent instead of the "getAuthToken" intent.
1948 if (!permissionGranted) {
1949 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1950 } else {
1951 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1952 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001953 }
1954
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001955 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001956 public void onResult(Bundle result) {
1957 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001958 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001959 Intent intent = newGrantCredentialsPermissionIntent(
1960 account,
1961 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001962 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001963 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001964 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001965 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001966 onResult(bundle);
1967 return;
1968 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001969 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001970 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001971 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1972 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001973 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001974 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001975 "the type and name should not be empty");
1976 return;
1977 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001978 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08001979 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001980 saveAuthTokenToDatabase(
1981 mAccounts,
1982 resultAccount,
1983 authTokenType,
1984 authToken);
1985 }
1986 long expiryMillis = result.getLong(
1987 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
1988 if (customTokens
1989 && expiryMillis > System.currentTimeMillis()) {
1990 saveCachedToken(
1991 mAccounts,
1992 account,
1993 callerPkg,
1994 callerPkgSigDigest,
1995 authTokenType,
1996 authToken,
1997 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08001998 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001999 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002000
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002001 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002002 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002003 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002004 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002005 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002006 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002007 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002008 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002009 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002010 }.bind();
2011 } finally {
2012 restoreCallingIdentity(identityToken);
2013 }
Fred Quintana60307342009-03-24 22:48:12 -07002014 }
2015
Carlos Valdivia91979be2015-05-22 14:11:35 -07002016 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2017 MessageDigest digester;
2018 try {
2019 digester = MessageDigest.getInstance("SHA-256");
2020 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2021 callerPkg, PackageManager.GET_SIGNATURES);
2022 for (Signature sig : pkgInfo.signatures) {
2023 digester.update(sig.toByteArray());
2024 }
2025 } catch (NoSuchAlgorithmException x) {
2026 Log.wtf(TAG, "SHA-256 should be available", x);
2027 digester = null;
2028 } catch (NameNotFoundException e) {
2029 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2030 digester = null;
2031 }
2032 return (digester == null) ? null : digester.digest();
2033 }
2034
Dianne Hackborn41203752012-08-31 14:05:51 -07002035 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2036 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002037 int uid = intent.getIntExtra(
2038 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2039 String authTokenType = intent.getStringExtra(
2040 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002041 final String titleAndSubtitle =
2042 mContext.getString(R.string.permission_request_notification_with_subtitle,
2043 account.name);
2044 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002045 String title = titleAndSubtitle;
2046 String subtitle = "";
2047 if (index > 0) {
2048 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002049 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002050 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002051 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002052 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002053 Notification n = new Notification.Builder(contextForUser)
2054 .setSmallIcon(android.R.drawable.stat_sys_warning)
2055 .setWhen(0)
2056 .setColor(contextForUser.getColor(
2057 com.android.internal.R.color.system_notification_accent_color))
2058 .setContentTitle(title)
2059 .setContentText(subtitle)
2060 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2061 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2062 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002063 installNotification(getCredentialPermissionNotificationId(
2064 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002065 }
2066
Costin Manolache5f383ad92010-12-02 16:44:46 -08002067 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002068 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002069
2070 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002071 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002072 // Since it was set in Eclair+ we can't change it without breaking apps using
2073 // the intent from a non-Activity context.
2074 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002075 intent.addCategory(
2076 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002077
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002078 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002079 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2080 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002081 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002082
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002083 return intent;
2084 }
2085
2086 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2087 int uid) {
2088 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002089 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002090 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002091 final Pair<Pair<Account, String>, Integer> key =
2092 new Pair<Pair<Account, String>, Integer>(
2093 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002094 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002095 if (id == null) {
2096 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002097 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002098 }
2099 }
2100 return id;
2101 }
2102
Amith Yamasani04e0d262012-02-14 11:50:53 -08002103 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002104 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002105 synchronized (accounts.signinRequiredNotificationIds) {
2106 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002107 if (id == null) {
2108 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002109 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002110 }
2111 }
2112 return id;
2113 }
2114
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002115 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002116 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002117 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002118 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08002119 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2120 Log.v(TAG, "addAccount: accountType " + accountType
2121 + ", response " + response
2122 + ", authTokenType " + authTokenType
2123 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2124 + ", expectActivityLaunch " + expectActivityLaunch
2125 + ", caller's uid " + Binder.getCallingUid()
2126 + ", pid " + Binder.getCallingPid());
2127 }
Fred Quintana382601f2010-03-25 12:25:10 -07002128 if (response == null) throw new IllegalArgumentException("response is null");
2129 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002130
Amith Yamasani71e6c692013-03-24 17:39:28 -07002131 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002132 int userId = Binder.getCallingUserHandle().getIdentifier();
2133 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002134 try {
2135 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2136 "User is not allowed to add an account!");
2137 } catch (RemoteException re) {
2138 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002139 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002140 return;
2141 }
2142 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002143 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002144 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2145 "User cannot modify accounts of this type (policy).");
2146 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002147 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002148 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2149 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002150 return;
2151 }
2152
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002153 final int pid = Binder.getCallingPid();
2154 final int uid = Binder.getCallingUid();
2155 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2156 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2157 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2158
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002159 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002160 long identityToken = clearCallingIdentity();
2161 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002162 UserAccounts accounts = getUserAccounts(usrId);
2163 logRecordWithUid(
2164 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002165 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002166 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002167 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002168 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002169 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002170 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002171 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002172 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002173
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002174 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002175 protected String toDebugString(long now) {
2176 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002177 + ", accountType " + accountType
2178 + ", requiredFeatures "
2179 + (requiredFeatures != null
2180 ? TextUtils.join(",", requiredFeatures)
2181 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002182 }
2183 }.bind();
2184 } finally {
2185 restoreCallingIdentity(identityToken);
2186 }
Fred Quintana60307342009-03-24 22:48:12 -07002187 }
2188
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002189 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002190 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2191 final String authTokenType, final String[] requiredFeatures,
2192 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002193 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002194 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2195 Log.v(TAG, "addAccount: accountType " + accountType
2196 + ", response " + response
2197 + ", authTokenType " + authTokenType
2198 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2199 + ", expectActivityLaunch " + expectActivityLaunch
2200 + ", caller's uid " + Binder.getCallingUid()
2201 + ", pid " + Binder.getCallingPid()
2202 + ", for user id " + userId);
2203 }
2204 if (response == null) throw new IllegalArgumentException("response is null");
2205 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002206 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002207 if (isCrossUser(callingUid, userId)) {
2208 throw new SecurityException(
2209 String.format(
2210 "User %s trying to add account for %s" ,
2211 UserHandle.getCallingUserId(),
2212 userId));
2213 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002214
2215 // Is user disallowed from modifying accounts?
2216 if (!canUserModifyAccounts(userId)) {
2217 try {
2218 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2219 "User is not allowed to add an account!");
2220 } catch (RemoteException re) {
2221 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002222 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002223 return;
2224 }
2225 if (!canUserModifyAccountsForType(userId, accountType)) {
2226 try {
2227 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2228 "User cannot modify accounts of this type (policy).");
2229 } catch (RemoteException re) {
2230 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002231 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2232 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002233 return;
2234 }
2235
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002236 final int pid = Binder.getCallingPid();
2237 final int uid = Binder.getCallingUid();
2238 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2239 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2240 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2241
2242 long identityToken = clearCallingIdentity();
2243 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002244 UserAccounts accounts = getUserAccounts(userId);
2245 logRecordWithUid(
2246 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002247 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002248 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002249 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002250 @Override
2251 public void run() throws RemoteException {
2252 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2253 options);
2254 }
2255
2256 @Override
2257 protected String toDebugString(long now) {
2258 return super.toDebugString(now) + ", addAccount"
2259 + ", accountType " + accountType
2260 + ", requiredFeatures "
2261 + (requiredFeatures != null
2262 ? TextUtils.join(",", requiredFeatures)
2263 : null);
2264 }
2265 }.bind();
2266 } finally {
2267 restoreCallingIdentity(identityToken);
2268 }
2269 }
2270
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002271 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002272 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2273 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2274 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2275 long identityToken = clearCallingIdentity();
2276 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002277 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002278 } finally {
2279 restoreCallingIdentity(identityToken);
2280 }
2281 }
2282
2283 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002284 public void confirmCredentialsAsUser(
2285 IAccountManagerResponse response,
2286 final Account account,
2287 final Bundle options,
2288 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002289 int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002290 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002291 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2292 Log.v(TAG, "confirmCredentials: " + account
2293 + ", response " + response
2294 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002295 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002296 + ", pid " + Binder.getCallingPid());
2297 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002298 // Only allow the system process to read accounts of other users
2299 if (isCrossUser(callingUid, userId)) {
2300 throw new SecurityException(
2301 String.format(
2302 "User %s trying to confirm account credentials for %s" ,
2303 UserHandle.getCallingUserId(),
2304 userId));
2305 }
Fred Quintana382601f2010-03-25 12:25:10 -07002306 if (response == null) throw new IllegalArgumentException("response is null");
2307 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002308 long identityToken = clearCallingIdentity();
2309 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002310 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002311 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002312 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002313 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002314 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002315 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002316 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002317 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002318 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002319 protected String toDebugString(long now) {
2320 return super.toDebugString(now) + ", confirmCredentials"
2321 + ", " + account;
2322 }
2323 }.bind();
2324 } finally {
2325 restoreCallingIdentity(identityToken);
2326 }
Fred Quintana60307342009-03-24 22:48:12 -07002327 }
2328
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002329 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002330 public void updateCredentials(IAccountManagerResponse response, final Account account,
2331 final String authTokenType, final boolean expectActivityLaunch,
2332 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08002333 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2334 Log.v(TAG, "updateCredentials: " + account
2335 + ", response " + response
2336 + ", authTokenType " + authTokenType
2337 + ", expectActivityLaunch " + expectActivityLaunch
2338 + ", caller's uid " + Binder.getCallingUid()
2339 + ", pid " + Binder.getCallingPid());
2340 }
Fred Quintana382601f2010-03-25 12:25:10 -07002341 if (response == null) throw new IllegalArgumentException("response is null");
2342 if (account == null) throw new IllegalArgumentException("account is null");
2343 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002344 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002345 long identityToken = clearCallingIdentity();
2346 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002347 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002348 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002349 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002350 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002351 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002352 public void run() throws RemoteException {
2353 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2354 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002355 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002356 protected String toDebugString(long now) {
2357 if (loginOptions != null) loginOptions.keySet();
2358 return super.toDebugString(now) + ", updateCredentials"
2359 + ", " + account
2360 + ", authTokenType " + authTokenType
2361 + ", loginOptions " + loginOptions;
2362 }
2363 }.bind();
2364 } finally {
2365 restoreCallingIdentity(identityToken);
2366 }
Fred Quintana60307342009-03-24 22:48:12 -07002367 }
2368
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002369 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002370 public void editProperties(IAccountManagerResponse response, final String accountType,
2371 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002372 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002373 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2374 Log.v(TAG, "editProperties: accountType " + accountType
2375 + ", response " + response
2376 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002377 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002378 + ", pid " + Binder.getCallingPid());
2379 }
Fred Quintana382601f2010-03-25 12:25:10 -07002380 if (response == null) throw new IllegalArgumentException("response is null");
2381 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002382 int userId = UserHandle.getCallingUserId();
2383 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002384 String msg = String.format(
2385 "uid %s cannot edit authenticator properites for account type: %s",
2386 callingUid,
2387 accountType);
2388 throw new SecurityException(msg);
2389 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002390 long identityToken = clearCallingIdentity();
2391 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002392 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002393 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002394 true /* stripAuthTokenFromResult */, null /* accountName */,
2395 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002396 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002397 public void run() throws RemoteException {
2398 mAuthenticator.editProperties(this, mAccountType);
2399 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002400 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002401 protected String toDebugString(long now) {
2402 return super.toDebugString(now) + ", editProperties"
2403 + ", accountType " + accountType;
2404 }
2405 }.bind();
2406 } finally {
2407 restoreCallingIdentity(identityToken);
2408 }
Fred Quintana60307342009-03-24 22:48:12 -07002409 }
2410
Fred Quintana33269202009-04-20 16:05:10 -07002411 private class GetAccountsByTypeAndFeatureSession extends Session {
2412 private final String[] mFeatures;
2413 private volatile Account[] mAccountsOfType = null;
2414 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2415 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002416 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002417
Amith Yamasani04e0d262012-02-14 11:50:53 -08002418 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002419 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002420 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002421 true /* stripAuthTokenFromResult */, null /* accountName */,
2422 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002423 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002424 mFeatures = features;
2425 }
2426
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002427 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002428 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002429 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002430 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2431 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002432 }
Fred Quintana33269202009-04-20 16:05:10 -07002433 // check whether each account matches the requested features
2434 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2435 mCurrentAccount = 0;
2436
2437 checkAccount();
2438 }
2439
2440 public void checkAccount() {
2441 if (mCurrentAccount >= mAccountsOfType.length) {
2442 sendResult();
2443 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002444 }
Fred Quintana33269202009-04-20 16:05:10 -07002445
Fred Quintana29e94b82010-03-10 12:11:51 -08002446 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2447 if (accountAuthenticator == null) {
2448 // It is possible that the authenticator has died, which is indicated by
2449 // mAuthenticator being set to null. If this happens then just abort.
2450 // There is no need to send back a result or error in this case since
2451 // that already happened when mAuthenticator was cleared.
2452 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2453 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2454 + " connected to the authenticator, " + toDebugString());
2455 }
2456 return;
2457 }
Fred Quintana33269202009-04-20 16:05:10 -07002458 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002459 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002460 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002461 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002462 }
2463 }
2464
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002465 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002466 public void onResult(Bundle result) {
2467 mNumResults++;
2468 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002469 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002470 return;
2471 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002472 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002473 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2474 }
2475 mCurrentAccount++;
2476 checkAccount();
2477 }
2478
2479 public void sendResult() {
2480 IAccountManagerResponse response = getResponseAndClose();
2481 if (response != null) {
2482 try {
2483 Account[] accounts = new Account[mAccountsWithFeatures.size()];
2484 for (int i = 0; i < accounts.length; i++) {
2485 accounts[i] = mAccountsWithFeatures.get(i);
2486 }
Fred Quintana56285a62010-12-02 14:20:51 -08002487 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2488 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2489 + response);
2490 }
Fred Quintana33269202009-04-20 16:05:10 -07002491 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002492 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07002493 response.onResult(result);
2494 } catch (RemoteException e) {
2495 // if the caller is dead then there is no one to care about remote exceptions
2496 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2497 Log.v(TAG, "failure while notifying response", e);
2498 }
2499 }
2500 }
2501 }
2502
2503
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002504 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002505 protected String toDebugString(long now) {
2506 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2507 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2508 }
2509 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002510
Amith Yamasani04e0d262012-02-14 11:50:53 -08002511 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002512 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08002513 * @hide
2514 */
Svetoslavce852dd2015-09-08 14:36:35 -07002515 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002516 int callingUid = Binder.getCallingUid();
Svetoslavce852dd2015-09-08 14:36:35 -07002517 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2518 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002519 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002520 return new Account[0];
2521 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002522 long identityToken = clearCallingIdentity();
2523 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002524 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002525 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002526 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002527 callingUid,
2528 null, // packageName
2529 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002530 } finally {
2531 restoreCallingIdentity(identityToken);
2532 }
2533 }
2534
Amith Yamasanif29f2362012-04-05 18:29:52 -07002535 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002536 * Returns accounts for all running users.
2537 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07002538 * @hide
2539 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002540 public AccountAndUser[] getRunningAccounts() {
2541 final int[] runningUserIds;
2542 try {
2543 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2544 } catch (RemoteException e) {
2545 // Running in system_server; should never happen
2546 throw new RuntimeException(e);
2547 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002548 return getAccounts(runningUserIds);
2549 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07002550
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002551 /** {@hide} */
2552 public AccountAndUser[] getAllAccounts() {
2553 final List<UserInfo> users = getUserManager().getUsers();
2554 final int[] userIds = new int[users.size()];
2555 for (int i = 0; i < userIds.length; i++) {
2556 userIds[i] = users.get(i).id;
2557 }
2558 return getAccounts(userIds);
2559 }
2560
2561 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002562 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002563 for (int userId : userIds) {
2564 UserAccounts userAccounts = getUserAccounts(userId);
2565 if (userAccounts == null) continue;
2566 synchronized (userAccounts.cacheLock) {
2567 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2568 Binder.getCallingUid(), null);
2569 for (int a = 0; a < accounts.length; a++) {
2570 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07002571 }
2572 }
2573 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002574
2575 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2576 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002577 }
2578
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002579 @Override
Svetoslavce852dd2015-09-08 14:36:35 -07002580 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
2581 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07002582 }
2583
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002584 private Account[] getAccountsAsUser(
2585 String type,
2586 int userId,
2587 String callingPackage,
Svetoslavce852dd2015-09-08 14:36:35 -07002588 int packageUid,
2589 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002590 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002591 // Only allow the system process to read accounts of other users
2592 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002593 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002594 && mContext.checkCallingOrSelfPermission(
2595 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2596 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002597 throw new SecurityException("User " + UserHandle.getCallingUserId()
2598 + " trying to get account for " + userId);
2599 }
2600
Fred Quintana56285a62010-12-02 14:20:51 -08002601 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2602 Log.v(TAG, "getAccounts: accountType " + type
2603 + ", caller's uid " + Binder.getCallingUid()
2604 + ", pid " + Binder.getCallingPid());
2605 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002606 // If the original calling app was using the framework account chooser activity, we'll
2607 // be passed in the original caller's uid here, which is what should be used for filtering.
2608 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2609 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07002610 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07002611 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002612
Svetoslavce852dd2015-09-08 14:36:35 -07002613 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2614 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002615 if (visibleAccountTypes.isEmpty()
2616 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002617 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002618 } else if (visibleAccountTypes.contains(type)) {
2619 // Prune the list down to just the requested type.
2620 visibleAccountTypes = new ArrayList<>();
2621 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07002622 } // else aggregate all the visible accounts (it won't matter if the
2623 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002624
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002625 long identityToken = clearCallingIdentity();
2626 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002627 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002628 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002629 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002630 callingUid,
2631 callingPackage,
2632 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002633 } finally {
2634 restoreCallingIdentity(identityToken);
2635 }
2636 }
2637
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002638 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002639 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002640 int callingUid,
2641 String callingPackage,
2642 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07002643 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002644 ArrayList<Account> visibleAccounts = new ArrayList<>();
2645 for (String visibleType : visibleAccountTypes) {
2646 Account[] accountsForType = getAccountsFromCacheLocked(
2647 userAccounts, visibleType, callingUid, callingPackage);
2648 if (accountsForType != null) {
2649 visibleAccounts.addAll(Arrays.asList(accountsForType));
2650 }
2651 }
2652 Account[] result = new Account[visibleAccounts.size()];
2653 for (int i = 0; i < visibleAccounts.size(); i++) {
2654 result[i] = visibleAccounts.get(i);
2655 }
2656 return result;
2657 }
2658 }
2659
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002660 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002661 public boolean addSharedAccountAsUser(Account account, int userId) {
2662 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002663 UserAccounts accounts = getUserAccounts(userId);
2664 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002665 ContentValues values = new ContentValues();
2666 values.put(ACCOUNTS_NAME, account.name);
2667 values.put(ACCOUNTS_TYPE, account.type);
2668 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2669 new String[] {account.name, account.type});
2670 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2671 if (accountId < 0) {
2672 Log.w(TAG, "insertAccountIntoDatabase: " + account
2673 + ", skipping the DB insert failed");
2674 return false;
2675 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002676 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002677 return true;
2678 }
2679
2680 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002681 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
2682 userId = handleIncomingUser(userId);
2683 UserAccounts accounts = getUserAccounts(userId);
2684 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002685 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002686 final ContentValues values = new ContentValues();
2687 values.put(ACCOUNTS_NAME, newName);
2688 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
2689 int r = db.update(
2690 TABLE_SHARED_ACCOUNTS,
2691 values,
2692 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2693 new String[] { account.name, account.type });
2694 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002695 int callingUid = getCallingUid();
2696 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
2697 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002698 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002699 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002700 }
2701 return r > 0;
2702 }
2703
2704 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002705 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002706 return removeSharedAccountAsUser(account, userId, getCallingUid());
2707 }
2708
2709 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08002710 userId = handleIncomingUser(userId);
2711 UserAccounts accounts = getUserAccounts(userId);
2712 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002713 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002714 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2715 new String[] {account.name, account.type});
2716 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002717 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
2718 sharedTableAccountId, accounts, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002719 removeAccountInternal(accounts, account);
2720 }
2721 return r > 0;
2722 }
2723
2724 @Override
2725 public Account[] getSharedAccountsAsUser(int userId) {
2726 userId = handleIncomingUser(userId);
2727 UserAccounts accounts = getUserAccounts(userId);
2728 ArrayList<Account> accountList = new ArrayList<Account>();
2729 Cursor cursor = null;
2730 try {
2731 cursor = accounts.openHelper.getReadableDatabase()
2732 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2733 null, null, null, null, null);
2734 if (cursor != null && cursor.moveToFirst()) {
2735 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2736 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2737 do {
2738 accountList.add(new Account(cursor.getString(nameIndex),
2739 cursor.getString(typeIndex)));
2740 } while (cursor.moveToNext());
2741 }
2742 } finally {
2743 if (cursor != null) {
2744 cursor.close();
2745 }
2746 }
2747 Account[] accountArray = new Account[accountList.size()];
2748 accountList.toArray(accountArray);
2749 return accountArray;
2750 }
2751
2752 @Override
Svetoslavce852dd2015-09-08 14:36:35 -07002753 public Account[] getAccounts(String type, String opPackageName) {
2754 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002755 }
2756
Amith Yamasani27db4682013-03-30 17:07:47 -07002757 @Override
Svetoslavce852dd2015-09-08 14:36:35 -07002758 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002759 int callingUid = Binder.getCallingUid();
2760 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2761 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2762 + callingUid + " with uid=" + uid);
2763 }
Svetoslavce852dd2015-09-08 14:36:35 -07002764 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
2765 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07002766 }
2767
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002768 @Override
Svetoslavce852dd2015-09-08 14:36:35 -07002769 public Account[] getAccountsByTypeForPackage(String type, String packageName,
2770 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002771 int packageUid = -1;
2772 try {
2773 packageUid = AppGlobals.getPackageManager().getPackageUid(
2774 packageName, UserHandle.getCallingUserId());
2775 } catch (RemoteException re) {
2776 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2777 return new Account[0];
2778 }
Svetoslavce852dd2015-09-08 14:36:35 -07002779 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
2780 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002781 }
2782
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002783 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002784 public void getAccountsByFeatures(
2785 IAccountManagerResponse response,
2786 String type,
Svetoslavce852dd2015-09-08 14:36:35 -07002787 String[] features,
2788 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002789 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002790 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2791 Log.v(TAG, "getAccounts: accountType " + type
2792 + ", response " + response
2793 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002794 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002795 + ", pid " + Binder.getCallingPid());
2796 }
Fred Quintana382601f2010-03-25 12:25:10 -07002797 if (response == null) throw new IllegalArgumentException("response is null");
2798 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002799 int userId = UserHandle.getCallingUserId();
2800
Svetoslavce852dd2015-09-08 14:36:35 -07002801 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
2802 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002803 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002804 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002805 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002806 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
2807 try {
2808 response.onResult(result);
2809 } catch (RemoteException e) {
2810 Log.e(TAG, "Cannot respond to caller do to exception." , e);
2811 }
2812 return;
2813 }
Fred Quintana33269202009-04-20 16:05:10 -07002814 long identityToken = clearCallingIdentity();
2815 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002816 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002817 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002818 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002819 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002820 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002821 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002822 Bundle result = new Bundle();
2823 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2824 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002825 return;
2826 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002827 new GetAccountsByTypeAndFeatureSession(
2828 userAccounts,
2829 response,
2830 type,
2831 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002832 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002833 } finally {
2834 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002835 }
2836 }
2837
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002838 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
2839 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
2840 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
2841 try {
2842 if (cursor.moveToNext()) {
2843 return cursor.getLong(0);
2844 }
2845 return -1;
2846 } finally {
2847 cursor.close();
2848 }
2849 }
2850
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002851 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002852 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002853 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002854 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 getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002865 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2866 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2867 new String[]{key}, null, null, null);
2868 try {
2869 if (cursor.moveToNext()) {
2870 return cursor.getLong(0);
2871 }
2872 return -1;
2873 } finally {
2874 cursor.close();
2875 }
2876 }
2877
Fred Quintanaa698f422009-04-08 19:14:54 -07002878 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002879 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002880 IAccountManagerResponse mResponse;
2881 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002882 final boolean mExpectActivityLaunch;
2883 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002884 final String mAccountName;
2885 // Indicates if we need to add auth details(like last credential time)
2886 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002887 // If set, we need to update the last authenticated time. This is
2888 // currently
2889 // used on
2890 // successful confirming credentials.
2891 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07002892
Fred Quintana33269202009-04-20 16:05:10 -07002893 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002894 private int mNumRequestContinued = 0;
2895 private int mNumErrors = 0;
2896
Fred Quintana60307342009-03-24 22:48:12 -07002897 IAccountAuthenticator mAuthenticator = null;
2898
Fred Quintana8570f742010-02-18 10:32:54 -08002899 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002900 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002901
Amith Yamasani04e0d262012-02-14 11:50:53 -08002902 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002903 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2904 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002905 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
2906 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
2907 }
2908
2909 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
2910 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2911 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07002912 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002913 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002914 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002915 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002916 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002917 mResponse = response;
2918 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002919 mExpectActivityLaunch = expectActivityLaunch;
2920 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002921 mAccountName = accountName;
2922 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002923 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002924
Fred Quintanaa698f422009-04-08 19:14:54 -07002925 synchronized (mSessions) {
2926 mSessions.put(toString(), this);
2927 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002928 if (response != null) {
2929 try {
2930 response.asBinder().linkToDeath(this, 0 /* flags */);
2931 } catch (RemoteException e) {
2932 mResponse = null;
2933 binderDied();
2934 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002935 }
Fred Quintana60307342009-03-24 22:48:12 -07002936 }
2937
Fred Quintanaa698f422009-04-08 19:14:54 -07002938 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002939 if (mResponse == null) {
2940 // this session has already been closed
2941 return null;
2942 }
Fred Quintana60307342009-03-24 22:48:12 -07002943 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002944 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002945 return response;
2946 }
2947
Fred Quintanaa698f422009-04-08 19:14:54 -07002948 private void close() {
2949 synchronized (mSessions) {
2950 if (mSessions.remove(toString()) == null) {
2951 // the session was already closed, so bail out now
2952 return;
2953 }
2954 }
2955 if (mResponse != null) {
2956 // stop listening for response deaths
2957 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2958
2959 // clear this so that we don't accidentally send any further results
2960 mResponse = null;
2961 }
2962 cancelTimeout();
2963 unbind();
2964 }
2965
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002966 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002967 public void binderDied() {
2968 mResponse = null;
2969 close();
2970 }
2971
2972 protected String toDebugString() {
2973 return toDebugString(SystemClock.elapsedRealtime());
2974 }
2975
2976 protected String toDebugString(long now) {
2977 return "Session: expectLaunch " + mExpectActivityLaunch
2978 + ", connected " + (mAuthenticator != null)
2979 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2980 + "/" + mNumErrors + ")"
2981 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2982 }
2983
Fred Quintana60307342009-03-24 22:48:12 -07002984 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002985 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2986 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2987 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002988 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002989 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002990 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002991 }
2992 }
2993
2994 private void unbind() {
2995 if (mAuthenticator != null) {
2996 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002997 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002998 }
2999 }
3000
Fred Quintana60307342009-03-24 22:48:12 -07003001 public void cancelTimeout() {
3002 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3003 }
3004
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003005 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003006 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003007 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003008 try {
3009 run();
3010 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003011 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003012 "remote exception");
3013 }
Fred Quintana60307342009-03-24 22:48:12 -07003014 }
3015
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003016 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003017 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003018 mAuthenticator = null;
3019 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003020 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003021 try {
3022 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3023 "disconnected");
3024 } catch (RemoteException e) {
3025 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3026 Log.v(TAG, "Session.onServiceDisconnected: "
3027 + "caught RemoteException while responding", e);
3028 }
3029 }
Fred Quintana60307342009-03-24 22:48:12 -07003030 }
3031 }
3032
Fred Quintanab839afc2009-10-14 15:57:28 -07003033 public abstract void run() throws RemoteException;
3034
Fred Quintana60307342009-03-24 22:48:12 -07003035 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003036 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003037 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003038 try {
3039 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3040 "timeout");
3041 } catch (RemoteException e) {
3042 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3043 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3044 e);
3045 }
3046 }
Fred Quintana60307342009-03-24 22:48:12 -07003047 }
3048 }
3049
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003050 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003051 public void onResult(Bundle result) {
3052 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003053 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003054 if (result != null) {
3055 boolean isSuccessfulConfirmCreds = result.getBoolean(
3056 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003057 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003058 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3059 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003060 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003061 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3062 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003063 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003064 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003065 if (needUpdate || mAuthDetailsRequired) {
3066 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3067 if (needUpdate && accountPresent) {
3068 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3069 }
3070 if (mAuthDetailsRequired) {
3071 long lastAuthenticatedTime = -1;
3072 if (accountPresent) {
3073 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3074 mAccounts.openHelper.getReadableDatabase(),
3075 "select " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3076 + " from " +
3077 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3078 + ACCOUNTS_TYPE + "=?",
3079 new String[] {
3080 mAccountName, mAccountType
3081 });
3082 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003083 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003084 lastAuthenticatedTime);
3085 }
3086 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003087 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003088 if (result != null
3089 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
3090 /*
3091 * The Authenticator API allows third party authenticators to
3092 * supply arbitrary intents to other apps that they can run,
3093 * this can be very bad when those apps are in the system like
3094 * the System Settings.
3095 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003096 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07003097 long bid = Binder.clearCallingIdentity();
3098 try {
3099 PackageManager pm = mContext.getPackageManager();
3100 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3101 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
3102 if (PackageManager.SIGNATURE_MATCH !=
3103 pm.checkSignatures(authenticatorUid, targetUid)) {
3104 throw new SecurityException(
3105 "Activity to be started with KEY_INTENT must " +
3106 "share Authenticator's signatures");
3107 }
3108 } finally {
3109 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003110 }
3111 }
3112 if (result != null
3113 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003114 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3115 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003116 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3117 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003118 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3119 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003120 }
Fred Quintana60307342009-03-24 22:48:12 -07003121 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003122 IAccountManagerResponse response;
3123 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003124 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003125 response = mResponse;
3126 } else {
3127 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003128 }
Fred Quintana60307342009-03-24 22:48:12 -07003129 if (response != null) {
3130 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07003131 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08003132 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3133 Log.v(TAG, getClass().getSimpleName()
3134 + " calling onError() on response " + response);
3135 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003136 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07003137 "null bundle returned");
3138 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08003139 if (mStripAuthTokenFromResult) {
3140 result.remove(AccountManager.KEY_AUTHTOKEN);
3141 }
Fred Quintana56285a62010-12-02 14:20:51 -08003142 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3143 Log.v(TAG, getClass().getSimpleName()
3144 + " calling onResult() on response " + response);
3145 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003146 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3147 (intent == null)) {
3148 // All AccountManager error codes are greater than 0
3149 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3150 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3151 } else {
3152 response.onResult(result);
3153 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003154 }
Fred Quintana60307342009-03-24 22:48:12 -07003155 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003156 // if the caller is dead then there is no one to care about remote exceptions
3157 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3158 Log.v(TAG, "failure while notifying response", e);
3159 }
Fred Quintana60307342009-03-24 22:48:12 -07003160 }
3161 }
3162 }
Fred Quintana60307342009-03-24 22:48:12 -07003163
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003164 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003165 public void onRequestContinued() {
3166 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003167 }
3168
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003169 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003170 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003171 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003172 IAccountManagerResponse response = getResponseAndClose();
3173 if (response != null) {
3174 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003175 Log.v(TAG, getClass().getSimpleName()
3176 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003177 }
3178 try {
3179 response.onError(errorCode, errorMessage);
3180 } catch (RemoteException e) {
3181 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3182 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3183 }
3184 }
3185 } else {
3186 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3187 Log.v(TAG, "Session.onError: already closed");
3188 }
Fred Quintana60307342009-03-24 22:48:12 -07003189 }
3190 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003191
3192 /**
3193 * find the component name for the authenticator and initiate a bind
3194 * if no authenticator or the bind fails then return false, otherwise return true
3195 */
3196 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003197 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3198 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3199 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003200 if (authenticatorInfo == null) {
3201 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3202 Log.v(TAG, "there is no authenticator for " + authenticatorType
3203 + ", bailing out");
3204 }
3205 return false;
3206 }
3207
3208 Intent intent = new Intent();
3209 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3210 intent.setComponent(authenticatorInfo.componentName);
3211 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3212 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3213 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003214 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
3215 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003216 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3217 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3218 }
3219 return false;
3220 }
3221
3222
3223 return true;
3224 }
Fred Quintana60307342009-03-24 22:48:12 -07003225 }
3226
3227 private class MessageHandler extends Handler {
3228 MessageHandler(Looper looper) {
3229 super(looper);
3230 }
Costin Manolache3348f142009-09-29 18:58:36 -07003231
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003232 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003233 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07003234 switch (msg.what) {
3235 case MESSAGE_TIMED_OUT:
3236 Session session = (Session)msg.obj;
3237 session.onTimedOut();
3238 break;
3239
Amith Yamasani5be347b2013-03-31 17:44:31 -07003240 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00003241 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07003242 break;
3243
Fred Quintana60307342009-03-24 22:48:12 -07003244 default:
3245 throw new IllegalStateException("unhandled message: " + msg.what);
3246 }
3247 }
3248 }
3249
Amith Yamasani04e0d262012-02-14 11:50:53 -08003250 private static String getDatabaseName(int userId) {
3251 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07003252 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003253 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07003254 // Migrate old file, if it exists, to the new location.
3255 // Make sure the new file doesn't already exist. A dummy file could have been
3256 // accidentally created in the old location, causing the new one to become corrupted
3257 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08003258 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07003259 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07003260 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07003261 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07003262 if (!userDir.exists()) {
3263 if (!userDir.mkdirs()) {
3264 throw new IllegalStateException("User dir cannot be created: " + userDir);
3265 }
3266 }
3267 if (!oldFile.renameTo(databaseFile)) {
3268 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
3269 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003270 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003271 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003272 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08003273 }
3274
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003275 private static class DebugDbHelper{
3276 private DebugDbHelper() {
3277 }
3278
3279 private static String TABLE_DEBUG = "debug_table";
3280
3281 // Columns for the table
3282 private static String ACTION_TYPE = "action_type";
3283 private static String TIMESTAMP = "time";
3284 private static String CALLER_UID = "caller_uid";
3285 private static String TABLE_NAME = "table_name";
3286 private static String KEY = "primary_key";
3287
3288 // These actions correspond to the occurrence of real actions. Since
3289 // these are called by the authenticators, the uid associated will be
3290 // of the authenticator.
3291 private static String ACTION_SET_PASSWORD = "action_set_password";
3292 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
3293 private static String ACTION_ACCOUNT_ADD = "action_account_add";
3294 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
3295 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
3296 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
3297
3298 // These actions don't necessarily correspond to any action on
3299 // accountDb taking place. As an example, there might be a request for
3300 // addingAccount, which might not lead to addition of account on grounds
3301 // of bad authentication. We will still be logging it to keep track of
3302 // who called.
3303 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
3304 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003305
3306 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3307
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003308 private static void createDebugTable(SQLiteDatabase db) {
3309 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
3310 + ACCOUNTS_ID + " INTEGER,"
3311 + ACTION_TYPE + " TEXT NOT NULL, "
3312 + TIMESTAMP + " DATETIME,"
3313 + CALLER_UID + " INTEGER NOT NULL,"
3314 + TABLE_NAME + " TEXT NOT NULL,"
3315 + KEY + " INTEGER PRIMARY KEY)");
3316 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
3317 }
3318 }
3319
3320 private void logRecord(UserAccounts accounts, String action, String tableName) {
3321 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3322 logRecord(db, action, tableName, -1, accounts);
3323 }
3324
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003325 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
3326 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3327 logRecord(db, action, tableName, -1, accounts, uid);
3328 }
3329
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003330 /*
3331 * This function receives an opened writable database.
3332 */
3333 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3334 UserAccounts userAccount) {
3335 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
3336 }
3337
3338 /*
3339 * This function receives an opened writable database.
3340 */
3341 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3342 UserAccounts userAccount, int callingUid) {
3343 SQLiteStatement logStatement = userAccount.statementForLogging;
3344 logStatement.bindLong(1, accountId);
3345 logStatement.bindString(2, action);
3346 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
3347 logStatement.bindLong(4, callingUid);
3348 logStatement.bindString(5, tableName);
3349 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
3350 logStatement.execute();
3351 logStatement.clearBindings();
3352 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
3353 % MAX_DEBUG_DB_SIZE;
3354 }
3355
3356 /*
3357 * This should only be called once to compile the sql statement for logging
3358 * and to find the insertion point.
3359 */
3360 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
3361 UserAccounts userAccount) {
3362 // Initialize the count if not done earlier.
3363 int size = (int) getDebugTableRowCount(db);
3364 if (size >= MAX_DEBUG_DB_SIZE) {
3365 // Table is full, and we need to find the point where to insert.
3366 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
3367 } else {
3368 userAccount.debugDbInsertionPoint = size;
3369 }
3370 compileSqlStatementForLogging(db, userAccount);
3371 }
3372
3373 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
3374 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
3375 + " VALUES (?,?,?,?,?,?)";
3376 userAccount.statementForLogging = db.compileStatement(sql);
3377 }
3378
3379 private long getDebugTableRowCount(SQLiteDatabase db) {
3380 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
3381 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3382 }
3383
3384 /*
3385 * Finds the row key where the next insertion should take place. This should
3386 * be invoked only if the table has reached its full capacity.
3387 */
3388 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
3389 // This query finds the smallest timestamp value (and if 2 records have
3390 // same timestamp, the choose the lower id).
3391 String queryCountDebugDbRows = new StringBuilder()
3392 .append("SELECT ").append(DebugDbHelper.KEY)
3393 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
3394 .append(" ORDER BY ")
3395 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
3396 .append(" LIMIT 1")
3397 .toString();
3398 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3399 }
3400
Amith Yamasani04e0d262012-02-14 11:50:53 -08003401 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003402
Amith Yamasani04e0d262012-02-14 11:50:53 -08003403 public DatabaseHelper(Context context, int userId) {
3404 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07003405 }
3406
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003407 /**
3408 * This call needs to be made while the mCacheLock is held. The way to
3409 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
3410 * @param db The database.
3411 */
Fred Quintana60307342009-03-24 22:48:12 -07003412 @Override
3413 public void onCreate(SQLiteDatabase db) {
3414 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
3415 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3416 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3417 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3418 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003419 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003420 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
Fred Quintana60307342009-03-24 22:48:12 -07003421 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3422
3423 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
3424 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3425 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3426 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
3427 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
3428 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
3429
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003430 createGrantsTable(db);
3431
Fred Quintana60307342009-03-24 22:48:12 -07003432 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
3433 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3434 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
3435 + EXTRAS_KEY + " TEXT NOT NULL, "
3436 + EXTRAS_VALUE + " TEXT, "
3437 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
3438
3439 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
3440 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
3441 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07003442
Amith Yamasani67df64b2012-12-14 12:09:36 -08003443 createSharedAccountsTable(db);
3444
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003445 createAccountsDeletionTrigger(db);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003446
3447 DebugDbHelper.createDebugTable(db);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003448 }
3449
Amith Yamasani67df64b2012-12-14 12:09:36 -08003450 private void createSharedAccountsTable(SQLiteDatabase db) {
3451 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
3452 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3453 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3454 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3455 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3456 }
3457
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003458 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
3459 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
3460 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
3461 }
3462
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003463 private void addOldAccountNameColumn(SQLiteDatabase db) {
3464 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
3465 }
3466
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003467 private void addDebugTable(SQLiteDatabase db) {
3468 DebugDbHelper.createDebugTable(db);
3469 }
3470
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003471 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003472 db.execSQL(""
3473 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
3474 + " BEGIN"
3475 + " DELETE FROM " + TABLE_AUTHTOKENS
3476 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
3477 + " DELETE FROM " + TABLE_EXTRAS
3478 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003479 + " DELETE FROM " + TABLE_GRANTS
3480 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07003481 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07003482 }
3483
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003484 private void createGrantsTable(SQLiteDatabase db) {
3485 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
3486 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3487 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
3488 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
3489 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
3490 + "," + GRANTS_GRANTEE_UID + "))");
3491 }
3492
Fred Quintana60307342009-03-24 22:48:12 -07003493 @Override
3494 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003495 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07003496
Fred Quintanaa698f422009-04-08 19:14:54 -07003497 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003498 // no longer need to do anything since the work is done
3499 // when upgrading from version 2
3500 oldVersion++;
3501 }
3502
3503 if (oldVersion == 2) {
3504 createGrantsTable(db);
3505 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
3506 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07003507 oldVersion++;
3508 }
Costin Manolache3348f142009-09-29 18:58:36 -07003509
3510 if (oldVersion == 3) {
3511 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
3512 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
3513 oldVersion++;
3514 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003515
3516 if (oldVersion == 4) {
3517 createSharedAccountsTable(db);
3518 oldVersion++;
3519 }
3520
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003521 if (oldVersion == 5) {
3522 addOldAccountNameColumn(db);
3523 oldVersion++;
3524 }
3525
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003526 if (oldVersion == 6) {
3527 addLastSuccessfullAuthenticatedTimeColumn(db);
3528 oldVersion++;
3529 }
3530
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003531 if (oldVersion == 7) {
3532 addDebugTable(db);
3533 oldVersion++;
3534 }
3535
Amith Yamasani67df64b2012-12-14 12:09:36 -08003536 if (oldVersion != newVersion) {
3537 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
3538 }
Fred Quintana60307342009-03-24 22:48:12 -07003539 }
3540
3541 @Override
3542 public void onOpen(SQLiteDatabase db) {
3543 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
3544 }
3545 }
3546
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003547 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07003548 return asBinder();
3549 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003550
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003551 /**
3552 * Searches array of arguments for the specified string
3553 * @param args array of argument strings
3554 * @param value value to search for
3555 * @return true if the value is contained in the array
3556 */
3557 private static boolean scanArgs(String[] args, String value) {
3558 if (args != null) {
3559 for (String arg : args) {
3560 if (value.equals(arg)) {
3561 return true;
3562 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003563 }
3564 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003565 return false;
3566 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003567
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003568 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003569 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07003570 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3571 != PackageManager.PERMISSION_GRANTED) {
3572 fout.println("Permission Denial: can't dump AccountsManager from from pid="
3573 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3574 + " without permission " + android.Manifest.permission.DUMP);
3575 return;
3576 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003577 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003578 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07003579
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003580 final List<UserInfo> users = getUserManager().getUsers();
3581 for (UserInfo user : users) {
3582 ipw.println("User " + user + ":");
3583 ipw.increaseIndent();
3584 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
3585 ipw.println();
3586 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08003587 }
3588 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003589
Amith Yamasani04e0d262012-02-14 11:50:53 -08003590 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
3591 String[] args, boolean isCheckinRequest) {
3592 synchronized (userAccounts.cacheLock) {
3593 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003594
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003595 if (isCheckinRequest) {
3596 // This is a checkin request. *Only* upload the account types and the count of each.
3597 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
3598 null, null, ACCOUNTS_TYPE, null, null);
3599 try {
3600 while (cursor.moveToNext()) {
3601 // print type,count
3602 fout.println(cursor.getString(0) + "," + cursor.getString(1));
3603 }
3604 } finally {
3605 if (cursor != null) {
3606 cursor.close();
3607 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003608 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003609 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003610 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07003611 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003612 fout.println("Accounts: " + accounts.length);
3613 for (Account account : accounts) {
3614 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003615 }
Fred Quintana307da1a2010-01-21 14:24:20 -08003616
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003617 // Add debug information.
3618 fout.println();
3619 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
3620 null, null, null, null, DebugDbHelper.TIMESTAMP);
3621 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
3622 fout.println("Accounts History");
3623 try {
3624 while (cursor.moveToNext()) {
3625 // print type,count
3626 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
3627 cursor.getString(2) + "," + cursor.getString(3) + ","
3628 + cursor.getString(4) + "," + cursor.getString(5));
3629 }
3630 } finally {
3631 cursor.close();
3632 }
3633
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003634 fout.println();
3635 synchronized (mSessions) {
3636 final long now = SystemClock.elapsedRealtime();
3637 fout.println("Active Sessions: " + mSessions.size());
3638 for (Session session : mSessions.values()) {
3639 fout.println(" " + session.toDebugString(now));
3640 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003641 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003642
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003643 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003644 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003645 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003646 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003647 }
3648
Amith Yamasani04e0d262012-02-14 11:50:53 -08003649 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07003650 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003651 long identityToken = clearCallingIdentity();
3652 try {
3653 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3654 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
3655 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003656
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003657 if (intent.getComponent() != null &&
3658 GrantCredentialsPermissionActivity.class.getName().equals(
3659 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003660 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003661 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003662 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07003663 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003664 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003665 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07003666 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003667 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003668 Notification n = new Notification.Builder(contextForUser)
3669 .setWhen(0)
3670 .setSmallIcon(android.R.drawable.stat_sys_warning)
3671 .setColor(contextForUser.getColor(
3672 com.android.internal.R.color.system_notification_accent_color))
3673 .setContentTitle(String.format(notificationTitleFormat, account.name))
3674 .setContentText(message)
3675 .setContentIntent(PendingIntent.getActivityAsUser(
3676 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
3677 null, user))
3678 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003679 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003680 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003681 } finally {
3682 restoreCallingIdentity(identityToken);
3683 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003684 }
3685
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003686 protected void installNotification(final int notificationId, final Notification n,
3687 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08003688 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003689 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08003690 }
3691
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003692 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003693 long identityToken = clearCallingIdentity();
3694 try {
3695 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003696 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003697 } finally {
3698 restoreCallingIdentity(identityToken);
3699 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003700 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003701
Svetoslavce852dd2015-09-08 14:36:35 -07003702 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
Fred Quintanab38eb142010-02-24 13:40:54 -08003703 for (String perm : permissions) {
3704 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
3705 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003706 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08003707 }
Svetoslavce852dd2015-09-08 14:36:35 -07003708 final int opCode = AppOpsManager.permissionToOpCode(perm);
3709 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
3710 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
3711 return true;
3712 }
Fred Quintanab38eb142010-02-24 13:40:54 -08003713 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003714 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003715 return false;
3716 }
3717
Amith Yamasani67df64b2012-12-14 12:09:36 -08003718 private int handleIncomingUser(int userId) {
3719 try {
3720 return ActivityManagerNative.getDefault().handleIncomingUser(
3721 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
3722 } catch (RemoteException re) {
3723 // Shouldn't happen, local.
3724 }
3725 return userId;
3726 }
3727
Christopher Tateccbf84f2013-05-08 15:25:41 -07003728 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003729 final int callingUserId = UserHandle.getUserId(callingUid);
3730
3731 final PackageManager userPackageManager;
3732 try {
3733 userPackageManager = mContext.createPackageContextAsUser(
3734 "android", 0, new UserHandle(callingUserId)).getPackageManager();
3735 } catch (NameNotFoundException e) {
3736 return false;
3737 }
3738
3739 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07003740 for (String name : packages) {
3741 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003742 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08003743 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003744 && (packageInfo.applicationInfo.privateFlags
3745 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07003746 return true;
3747 }
3748 } catch (PackageManager.NameNotFoundException e) {
3749 return false;
3750 }
3751 }
3752 return false;
3753 }
3754
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003755 private boolean permissionIsGranted(
3756 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07003757 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07003758 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003759 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07003760 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08003761 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003762 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3763 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08003764 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003765 + ": is authenticator? " + fromAuthenticator
3766 + ", has explicit permission? " + hasExplicitGrants);
3767 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07003768 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003769 }
3770
Svetoslavce852dd2015-09-08 14:36:35 -07003771 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
3772 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003773 if (accountType == null) {
3774 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003775 } else {
Svetoslavce852dd2015-09-08 14:36:35 -07003776 return getTypesVisibleToCaller(callingUid, userId,
3777 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003778 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003779 }
3780
3781 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
3782 if (accountType == null) {
3783 return false;
3784 } else {
3785 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
3786 }
3787 }
3788
Svetoslavce852dd2015-09-08 14:36:35 -07003789 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
3790 String opPackageName) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003791 boolean isPermitted =
Svetoslavce852dd2015-09-08 14:36:35 -07003792 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003793 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
3794 Log.i(TAG, String.format("getTypesVisibleToCaller: isPermitted? %s", isPermitted));
3795 return getTypesForCaller(callingUid, userId, isPermitted);
3796 }
3797
3798 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
3799 return getTypesForCaller(callingUid, userId, false);
3800 }
3801
3802 private List<String> getTypesForCaller(
3803 int callingUid, int userId, boolean isOtherwisePermitted) {
3804 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003805 long identityToken = Binder.clearCallingIdentity();
3806 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
3807 try {
3808 serviceInfos = mAuthenticatorCache.getAllServices(userId);
3809 } finally {
3810 Binder.restoreCallingIdentity(identityToken);
3811 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003812 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003813 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003814 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
3815 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
3816 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003817 }
3818 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003819 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003820 }
3821
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003822 private boolean isAccountPresentForCaller(String accountName, String accountType) {
3823 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
3824 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
3825 if (account.name.equals(accountName)) {
3826 return true;
3827 }
3828 }
3829 }
3830 return false;
3831 }
3832
Amith Yamasani04e0d262012-02-14 11:50:53 -08003833 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
3834 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003835 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003836 return true;
3837 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003838 UserAccounts accounts = getUserAccountsForCaller();
3839 synchronized (accounts.cacheLock) {
3840 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3841 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003842 account.name, account.type};
3843 final boolean permissionGranted =
3844 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
3845 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
3846 // TODO: Skip this check when running automated tests. Replace this
3847 // with a more general solution.
3848 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08003849 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003850 + " but ignoring since device is in test harness.");
3851 return true;
3852 }
3853 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003854 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003855 }
3856
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003857 private boolean isSystemUid(int callingUid) {
3858 String[] packages = null;
3859 long ident = Binder.clearCallingIdentity();
3860 try {
3861 packages = mPackageManager.getPackagesForUid(callingUid);
3862 } finally {
3863 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07003864 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003865 if (packages != null) {
3866 for (String name : packages) {
3867 try {
3868 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
3869 if (packageInfo != null
3870 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
3871 != 0) {
3872 return true;
3873 }
3874 } catch (PackageManager.NameNotFoundException e) {
3875 Log.w(TAG, String.format("Could not find package [%s]", name), e);
3876 }
3877 }
3878 } else {
3879 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07003880 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003881 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003882 }
3883
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003884 /** Succeeds if any of the specified permissions are granted. */
3885 private void checkReadAccountsPermitted(
3886 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003887 String accountType,
Svetoslavce852dd2015-09-08 14:36:35 -07003888 int userId,
3889 String opPackageName) {
3890 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003891 String msg = String.format(
3892 "caller uid %s cannot access %s accounts",
3893 callingUid,
3894 accountType);
3895 Log.w(TAG, " " + msg);
3896 throw new SecurityException(msg);
3897 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003898 }
3899
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003900 private boolean canUserModifyAccounts(int userId) {
3901 if (getUserManager().getUserRestrictions(new UserHandle(userId))
3902 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
3903 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003904 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003905 return true;
3906 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003907
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003908 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003909 DevicePolicyManager dpm = (DevicePolicyManager) mContext
3910 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003911 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02003912 if (typesArray == null) {
3913 return true;
3914 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003915 for (String forbiddenType : typesArray) {
3916 if (forbiddenType.equals(accountType)) {
3917 return false;
3918 }
3919 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003920 return true;
3921 }
3922
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003923 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07003924 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
3925 throws RemoteException {
3926 final int callingUid = getCallingUid();
3927
Amith Yamasani27db4682013-03-30 17:07:47 -07003928 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07003929 throw new SecurityException();
3930 }
3931
3932 if (value) {
3933 grantAppPermission(account, authTokenType, uid);
3934 } else {
3935 revokeAppPermission(account, authTokenType, uid);
3936 }
3937 }
3938
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003939 /**
3940 * Allow callers with the given uid permission to get credentials for account/authTokenType.
3941 * <p>
3942 * Although this is public it can only be accessed via the AccountManagerService object
3943 * which is in the system. This means we don't need to protect it with permissions.
3944 * @hide
3945 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003946 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003947 if (account == null || authTokenType == null) {
3948 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003949 return;
3950 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003951 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003952 synchronized (accounts.cacheLock) {
3953 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003954 db.beginTransaction();
3955 try {
3956 long accountId = getAccountIdLocked(db, account);
3957 if (accountId >= 0) {
3958 ContentValues values = new ContentValues();
3959 values.put(GRANTS_ACCOUNTS_ID, accountId);
3960 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
3961 values.put(GRANTS_GRANTEE_UID, uid);
3962 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
3963 db.setTransactionSuccessful();
3964 }
3965 } finally {
3966 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003967 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003968 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3969 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003970 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003971 }
3972
3973 /**
3974 * Don't allow callers with the given uid permission to get credentials for
3975 * account/authTokenType.
3976 * <p>
3977 * Although this is public it can only be accessed via the AccountManagerService object
3978 * which is in the system. This means we don't need to protect it with permissions.
3979 * @hide
3980 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003981 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003982 if (account == null || authTokenType == null) {
3983 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003984 return;
3985 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003986 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003987 synchronized (accounts.cacheLock) {
3988 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003989 db.beginTransaction();
3990 try {
3991 long accountId = getAccountIdLocked(db, account);
3992 if (accountId >= 0) {
3993 db.delete(TABLE_GRANTS,
3994 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
3995 + GRANTS_GRANTEE_UID + "=?",
3996 new String[]{String.valueOf(accountId), authTokenType,
3997 String.valueOf(uid)});
3998 db.setTransactionSuccessful();
3999 }
4000 } finally {
4001 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004002 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004003 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
4004 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004005 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004006 }
Fred Quintana56285a62010-12-02 14:20:51 -08004007
4008 static final private String stringArrayToString(String[] value) {
4009 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
4010 }
4011
Amith Yamasani04e0d262012-02-14 11:50:53 -08004012 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
4013 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004014 if (oldAccountsForType != null) {
4015 ArrayList<Account> newAccountsList = new ArrayList<Account>();
4016 for (Account curAccount : oldAccountsForType) {
4017 if (!curAccount.equals(account)) {
4018 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004019 }
4020 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004021 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004022 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004023 } else {
4024 Account[] newAccountsForType = new Account[newAccountsList.size()];
4025 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004026 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004027 }
Fred Quintana56285a62010-12-02 14:20:51 -08004028 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004029 accounts.userDataCache.remove(account);
4030 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004031 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004032 }
4033
4034 /**
4035 * This assumes that the caller has already checked that the account is not already present.
4036 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08004037 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
4038 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004039 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
4040 Account[] newAccountsForType = new Account[oldLength + 1];
4041 if (accountsForType != null) {
4042 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08004043 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004044 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004045 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08004046 }
4047
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004048 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07004049 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004050 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07004051 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004052 return unfiltered;
4053 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004054 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
4055 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004056 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004057 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004058 // otherwise return non-shared accounts only.
4059 // This might be a temporary way to specify a whitelist
4060 String whiteList = mContext.getResources().getString(
4061 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
4062 for (String packageName : packages) {
4063 if (whiteList.contains(";" + packageName + ";")) {
4064 return unfiltered;
4065 }
4066 }
4067 ArrayList<Account> allowed = new ArrayList<Account>();
4068 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
4069 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004070 String requiredAccountType = "";
4071 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07004072 // If there's an explicit callingPackage specified, check if that package
4073 // opted in to see restricted accounts.
4074 if (callingPackage != null) {
4075 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004076 if (pi != null && pi.restrictedAccountType != null) {
4077 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07004078 }
4079 } else {
4080 // Otherwise check if the callingUid has a package that has opted in
4081 for (String packageName : packages) {
4082 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
4083 if (pi != null && pi.restrictedAccountType != null) {
4084 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07004085 break;
4086 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004087 }
4088 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004089 } catch (NameNotFoundException nnfe) {
4090 }
4091 for (Account account : unfiltered) {
4092 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004093 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004094 } else {
4095 boolean found = false;
4096 for (Account shared : sharedAccounts) {
4097 if (shared.equals(account)) {
4098 found = true;
4099 break;
4100 }
4101 }
4102 if (!found) {
4103 allowed.add(account);
4104 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004105 }
4106 }
4107 Account[] filtered = new Account[allowed.size()];
4108 allowed.toArray(filtered);
4109 return filtered;
4110 } else {
4111 return unfiltered;
4112 }
4113 }
4114
Amith Yamasani27db4682013-03-30 17:07:47 -07004115 /*
4116 * packageName can be null. If not null, it should be used to filter out restricted accounts
4117 * that the package is not allowed to access.
4118 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004119 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07004120 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004121 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004122 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004123 if (accounts == null) {
4124 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08004125 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004126 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07004127 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004128 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004129 } else {
4130 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004131 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004132 totalLength += accounts.length;
4133 }
4134 if (totalLength == 0) {
4135 return EMPTY_ACCOUNT_ARRAY;
4136 }
4137 Account[] accounts = new Account[totalLength];
4138 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004139 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004140 System.arraycopy(accountsOfType, 0, accounts, totalLength,
4141 accountsOfType.length);
4142 totalLength += accountsOfType.length;
4143 }
Amith Yamasani27db4682013-03-30 17:07:47 -07004144 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004145 }
4146 }
4147
Amith Yamasani04e0d262012-02-14 11:50:53 -08004148 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4149 Account account, String key, String value) {
4150 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004151 if (userDataForAccount == null) {
4152 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004153 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004154 }
4155 if (value == null) {
4156 userDataForAccount.remove(key);
4157 } else {
4158 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004159 }
4160 }
4161
Carlos Valdivia91979be2015-05-22 14:11:35 -07004162 protected String readCachedTokenInternal(
4163 UserAccounts accounts,
4164 Account account,
4165 String tokenType,
4166 String callingPackage,
4167 byte[] pkgSigDigest) {
4168 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004169 return accounts.accountTokenCaches.get(
4170 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004171 }
4172 }
4173
Amith Yamasani04e0d262012-02-14 11:50:53 -08004174 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4175 Account account, String key, String value) {
4176 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004177 if (authTokensForAccount == null) {
4178 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004179 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004180 }
4181 if (value == null) {
4182 authTokensForAccount.remove(key);
4183 } else {
4184 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004185 }
4186 }
4187
Amith Yamasani04e0d262012-02-14 11:50:53 -08004188 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
4189 String authTokenType) {
4190 synchronized (accounts.cacheLock) {
4191 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004192 if (authTokensForAccount == null) {
4193 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004194 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004195 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004196 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004197 }
4198 return authTokensForAccount.get(authTokenType);
4199 }
4200 }
4201
Amith Yamasani04e0d262012-02-14 11:50:53 -08004202 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
4203 synchronized (accounts.cacheLock) {
4204 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004205 if (userDataForAccount == 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 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004209 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004210 }
4211 return userDataForAccount.get(key);
4212 }
4213 }
4214
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004215 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
4216 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004217 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004218 Cursor cursor = db.query(TABLE_EXTRAS,
4219 COLUMNS_EXTRAS_KEY_AND_VALUE,
4220 SELECTION_USERDATA_BY_ACCOUNT,
4221 new String[]{account.name, account.type},
4222 null, null, null);
4223 try {
4224 while (cursor.moveToNext()) {
4225 final String tmpkey = cursor.getString(0);
4226 final String value = cursor.getString(1);
4227 userDataForAccount.put(tmpkey, value);
4228 }
4229 } finally {
4230 cursor.close();
4231 }
4232 return userDataForAccount;
4233 }
4234
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004235 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
4236 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004237 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004238 Cursor cursor = db.query(TABLE_AUTHTOKENS,
4239 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
4240 SELECTION_AUTHTOKENS_BY_ACCOUNT,
4241 new String[]{account.name, account.type},
4242 null, null, null);
4243 try {
4244 while (cursor.moveToNext()) {
4245 final String type = cursor.getString(0);
4246 final String authToken = cursor.getString(1);
4247 authTokensForAccount.put(type, authToken);
4248 }
4249 } finally {
4250 cursor.close();
4251 }
4252 return authTokensForAccount;
4253 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004254
4255 private Context getContextForUser(UserHandle user) {
4256 try {
4257 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
4258 } catch (NameNotFoundException e) {
4259 // Default to mContext, not finding the package system is running as is unlikely.
4260 return mContext;
4261 }
4262 }
Fred Quintana60307342009-03-24 22:48:12 -07004263}