blob: 888fa1adfe3847b114e284a4981ecc948b433e27 [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;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080020import android.accounts.Account;
21import android.accounts.AccountAndUser;
22import android.accounts.AccountAuthenticatorResponse;
23import android.accounts.AccountManager;
24import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070025import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080026import android.accounts.GrantCredentialsPermissionActivity;
27import android.accounts.IAccountAuthenticator;
28import android.accounts.IAccountAuthenticatorResponse;
29import android.accounts.IAccountManager;
30import android.accounts.IAccountManagerResponse;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080031import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070032import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070033import android.app.AppGlobals;
Doug Zongker885cfc232009-10-21 16:52:44 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010037import android.app.admin.DevicePolicyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070038import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070039import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070040import android.content.ContentValues;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070044import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070045import android.content.pm.ApplicationInfo;
46import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070047import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070048import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070049import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070050import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070051import android.content.pm.ResolveInfo;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070052import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070053import android.database.Cursor;
54import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070055import android.database.sqlite.SQLiteDatabase;
56import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070057import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070058import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080059import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070060import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070061import android.os.IBinder;
62import android.os.Looper;
63import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070064import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070065import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import android.os.RemoteException;
67import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070069import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.text.TextUtils;
71import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070072import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070073import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080074import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070075
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070076import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080077import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080078import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070079import com.android.server.FgThread;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -070080
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070081import com.google.android.collect.Lists;
82import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070083
Oscar Montemayora8529f62009-11-18 10:14:20 -080084import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070085import java.io.FileDescriptor;
86import java.io.PrintWriter;
87import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080088import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070089import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070090import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070091import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080092import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070093import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080094import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070095import java.util.concurrent.atomic.AtomicInteger;
96import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070097
Fred Quintana60307342009-03-24 22:48:12 -070098/**
99 * A system service that provides account, password, and authtoken management for all
100 * accounts on the device. Some of these calls are implemented with the help of the corresponding
101 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
102 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700103 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700104 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700105 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700106public class AccountManagerService
107 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800108 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700109 private static final String TAG = "AccountManagerService";
110
111 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
112 private static final String DATABASE_NAME = "accounts.db";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700113 private static final int DATABASE_VERSION = 6;
Fred Quintana60307342009-03-24 22:48:12 -0700114
115 private final Context mContext;
116
Fred Quintana56285a62010-12-02 14:20:51 -0800117 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700118 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800119
Fred Quintana60307342009-03-24 22:48:12 -0700120 private final MessageHandler mMessageHandler;
121
122 // Messages that can be sent on mHandler
123 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700124 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700125
Fred Quintana56285a62010-12-02 14:20:51 -0800126 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700127
128 private static final String TABLE_ACCOUNTS = "accounts";
129 private static final String ACCOUNTS_ID = "_id";
130 private static final String ACCOUNTS_NAME = "name";
131 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700132 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700133 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700134 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Fred Quintana60307342009-03-24 22:48:12 -0700135
136 private static final String TABLE_AUTHTOKENS = "authtokens";
137 private static final String AUTHTOKENS_ID = "_id";
138 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
139 private static final String AUTHTOKENS_TYPE = "type";
140 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
141
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700142 private static final String TABLE_GRANTS = "grants";
143 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
144 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
145 private static final String GRANTS_GRANTEE_UID = "uid";
146
Fred Quintana60307342009-03-24 22:48:12 -0700147 private static final String TABLE_EXTRAS = "extras";
148 private static final String EXTRAS_ID = "_id";
149 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
150 private static final String EXTRAS_KEY = "key";
151 private static final String EXTRAS_VALUE = "value";
152
153 private static final String TABLE_META = "meta";
154 private static final String META_KEY = "key";
155 private static final String META_VALUE = "value";
156
Amith Yamasani67df64b2012-12-14 12:09:36 -0800157 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
158
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700159 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
160 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700161 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700162
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700163 private static final String COUNT_OF_MATCHING_GRANTS = ""
164 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
165 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
166 + " AND " + GRANTS_GRANTEE_UID + "=?"
167 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
168 + " AND " + ACCOUNTS_NAME + "=?"
169 + " AND " + ACCOUNTS_TYPE + "=?";
170
Fred Quintana56285a62010-12-02 14:20:51 -0800171 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
172 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
173 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
174 AUTHTOKENS_AUTHTOKEN};
175
176 private static final String SELECTION_USERDATA_BY_ACCOUNT =
177 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
178 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
179
Fred Quintanaa698f422009-04-08 19:14:54 -0700180 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700181 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
182
Amith Yamasani04e0d262012-02-14 11:50:53 -0800183 static class UserAccounts {
184 private final int userId;
185 private final DatabaseHelper openHelper;
186 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
187 credentialsPermissionNotificationIds =
188 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
189 private final HashMap<Account, Integer> signinRequiredNotificationIds =
190 new HashMap<Account, Integer>();
191 private final Object cacheLock = new Object();
192 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700193 private final HashMap<String, Account[]> accountCache =
194 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800195 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800196 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800197 new HashMap<Account, HashMap<String, String>>();
198 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800199 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800200 new HashMap<Account, HashMap<String, String>>();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700201 /**
202 * protected by the {@link #cacheLock}
203 *
204 * Caches the previous names associated with an account. Previous names
205 * should be cached because we expect that when an Account is renamed,
206 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
207 * want to know if the accounts they care about have been renamed.
208 *
209 * The previous names are wrapped in an {@link AtomicReference} so that
210 * we can distinguish between those accounts with no previous names and
211 * those whose previous names haven't been cached (yet).
212 */
213 private final HashMap<Account, AtomicReference<String>> previousNameCache =
214 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800215
216 UserAccounts(Context context, int userId) {
217 this.userId = userId;
218 synchronized (cacheLock) {
219 openHelper = new DatabaseHelper(context, userId);
220 }
221 }
222 }
223
224 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
225
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700226 private static AtomicReference<AccountManagerService> sThis =
227 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700228 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700229
230 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700231 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700232 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
233 }
234
Fred Quintana56285a62010-12-02 14:20:51 -0800235
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700236 /**
237 * This should only be called by system code. One should only call this after the service
238 * has started.
239 * @return a reference to the AccountManagerService instance
240 * @hide
241 */
242 public static AccountManagerService getSingleton() {
243 return sThis.get();
244 }
Fred Quintana60307342009-03-24 22:48:12 -0700245
Fred Quintana56285a62010-12-02 14:20:51 -0800246 public AccountManagerService(Context context) {
247 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700248 }
249
Fred Quintana56285a62010-12-02 14:20:51 -0800250 public AccountManagerService(Context context, PackageManager packageManager,
251 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700252 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800253 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700254
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700255 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700256
Fred Quintana56285a62010-12-02 14:20:51 -0800257 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800258 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700259
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700260 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800261
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800262 IntentFilter intentFilter = new IntentFilter();
263 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
264 intentFilter.addDataScheme("package");
265 mContext.registerReceiver(new BroadcastReceiver() {
266 @Override
267 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700268 // Don't delete accounts when updating a authenticator's
269 // package.
270 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
271 purgeOldGrantsAll();
272 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800273 }
274 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800275
Amith Yamasani13593602012-03-22 16:16:17 -0700276 IntentFilter userFilter = new IntentFilter();
277 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800278 userFilter.addAction(Intent.ACTION_USER_STARTED);
279 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700280 @Override
281 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800282 String action = intent.getAction();
283 if (Intent.ACTION_USER_REMOVED.equals(action)) {
284 onUserRemoved(intent);
285 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
286 onUserStarted(intent);
287 }
Amith Yamasani13593602012-03-22 16:16:17 -0700288 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800289 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800290 }
291
Dianne Hackborn164371f2013-10-01 19:10:13 -0700292 @Override
293 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
294 throws RemoteException {
295 try {
296 return super.onTransact(code, data, reply, flags);
297 } catch (RuntimeException e) {
298 // The account manager only throws security exceptions, so let's
299 // log all others.
300 if (!(e instanceof SecurityException)) {
301 Slog.wtf(TAG, "Account Manager Crash", e);
302 }
303 throw e;
304 }
305 }
306
Kenny Root26ff6622012-07-30 12:58:03 -0700307 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700308 }
309
Amith Yamasani258848d2012-08-10 17:06:33 -0700310 private UserManager getUserManager() {
311 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700312 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700313 }
314 return mUserManager;
315 }
316
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700317 /* Caller should lock mUsers */
318 private UserAccounts initUserLocked(int userId) {
319 UserAccounts accounts = mUsers.get(userId);
320 if (accounts == null) {
321 accounts = new UserAccounts(mContext, userId);
322 mUsers.append(userId, accounts);
323 purgeOldGrants(accounts);
324 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800325 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700326 return accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800327 }
328
329 private void purgeOldGrantsAll() {
330 synchronized (mUsers) {
331 for (int i = 0; i < mUsers.size(); i++) {
332 purgeOldGrants(mUsers.valueAt(i));
333 }
334 }
335 }
336
337 private void purgeOldGrants(UserAccounts accounts) {
338 synchronized (accounts.cacheLock) {
339 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800340 final Cursor cursor = db.query(TABLE_GRANTS,
341 new String[]{GRANTS_GRANTEE_UID},
342 null, null, GRANTS_GRANTEE_UID, null, null);
343 try {
344 while (cursor.moveToNext()) {
345 final int uid = cursor.getInt(0);
346 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
347 if (packageExists) {
348 continue;
349 }
350 Log.d(TAG, "deleting grants for UID " + uid
351 + " because its package is no longer installed");
352 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
353 new String[]{Integer.toString(uid)});
354 }
355 } finally {
356 cursor.close();
357 }
358 }
359 }
360
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700361 /**
362 * Validate internal set of accounts against installed authenticators for
363 * given user. Clears cached authenticators before validating.
364 */
365 public void validateAccounts(int userId) {
366 final UserAccounts accounts = getUserAccounts(userId);
367
368 // Invalidate user-specific cache to make sure we catch any
369 // removed authenticators.
370 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
371 }
372
373 /**
374 * Validate internal set of accounts against installed authenticators for
375 * given user. Clear cached authenticators before validating when requested.
376 */
377 private void validateAccountsInternal(
378 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
379 if (invalidateAuthenticatorCache) {
380 mAuthenticatorCache.invalidateCache(accounts.userId);
381 }
382
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700383 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
384 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
385 mAuthenticatorCache.getAllServices(accounts.userId)) {
386 knownAuth.add(service.type);
387 }
388
Amith Yamasani04e0d262012-02-14 11:50:53 -0800389 synchronized (accounts.cacheLock) {
390 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800391 boolean accountDeleted = false;
392 Cursor cursor = db.query(TABLE_ACCOUNTS,
393 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
394 null, null, null, null, null);
395 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800396 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800397 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700398 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800399 while (cursor.moveToNext()) {
400 final long accountId = cursor.getLong(0);
401 final String accountType = cursor.getString(1);
402 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700403
404 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700405 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800406 + accountType + " no longer has a registered authenticator");
407 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
408 accountDeleted = true;
409 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800410 accounts.userDataCache.remove(account);
411 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800412 } else {
413 ArrayList<String> accountNames = accountNamesByType.get(accountType);
414 if (accountNames == null) {
415 accountNames = new ArrayList<String>();
416 accountNamesByType.put(accountType, accountNames);
417 }
418 accountNames.add(accountName);
419 }
420 }
Andy McFadden2f362292012-01-20 14:43:38 -0800421 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800422 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800423 final String accountType = cur.getKey();
424 final ArrayList<String> accountNames = cur.getValue();
425 final Account[] accountsForType = new Account[accountNames.size()];
426 int i = 0;
427 for (String accountName : accountNames) {
428 accountsForType[i] = new Account(accountName, accountType);
429 ++i;
430 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800431 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800432 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800433 } finally {
434 cursor.close();
435 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800436 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800437 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800438 }
439 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700440 }
441
Amith Yamasani04e0d262012-02-14 11:50:53 -0800442 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700443 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800444 }
445
446 protected UserAccounts getUserAccounts(int userId) {
447 synchronized (mUsers) {
448 UserAccounts accounts = mUsers.get(userId);
449 if (accounts == null) {
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700450 accounts = initUserLocked(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800451 mUsers.append(userId, accounts);
452 }
453 return accounts;
454 }
455 }
456
Amith Yamasani13593602012-03-22 16:16:17 -0700457 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700458 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700459 if (userId < 1) return;
460
461 UserAccounts accounts;
462 synchronized (mUsers) {
463 accounts = mUsers.get(userId);
464 mUsers.remove(userId);
465 }
466 if (accounts == null) {
467 File dbFile = new File(getDatabaseName(userId));
468 dbFile.delete();
469 return;
470 }
471
472 synchronized (accounts.cacheLock) {
473 accounts.openHelper.close();
474 File dbFile = new File(getDatabaseName(userId));
475 dbFile.delete();
476 }
477 }
478
Amith Yamasani67df64b2012-12-14 12:09:36 -0800479 private void onUserStarted(Intent intent) {
480 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
481 if (userId < 1) return;
482
483 // Check if there's a shared account that needs to be created as an account
484 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
485 if (sharedAccounts == null || sharedAccounts.length == 0) return;
486 Account[] accounts = getAccountsAsUser(null, userId);
487 for (Account sa : sharedAccounts) {
488 if (ArrayUtils.contains(accounts, sa)) continue;
489 // Account doesn't exist. Copy it now.
490 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
491 }
492 }
493
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700494 @Override
495 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700496 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700497 }
498
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800499 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700500 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800501 if (Log.isLoggable(TAG, Log.VERBOSE)) {
502 Log.v(TAG, "getPassword: " + account
503 + ", caller's uid " + Binder.getCallingUid()
504 + ", pid " + Binder.getCallingPid());
505 }
Fred Quintana382601f2010-03-25 12:25:10 -0700506 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700507 checkAuthenticateAccountsPermission(account);
508
Amith Yamasani04e0d262012-02-14 11:50:53 -0800509 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700510 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700511 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800512 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700513 } finally {
514 restoreCallingIdentity(identityToken);
515 }
516 }
517
Amith Yamasani04e0d262012-02-14 11:50:53 -0800518 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700519 if (account == null) {
520 return null;
521 }
522
Amith Yamasani04e0d262012-02-14 11:50:53 -0800523 synchronized (accounts.cacheLock) {
524 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800525 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
526 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
527 new String[]{account.name, account.type}, null, null, null);
528 try {
529 if (cursor.moveToNext()) {
530 return cursor.getString(0);
531 }
532 return null;
533 } finally {
534 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700535 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700536 }
537 }
538
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800539 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700540 public String getPreviousName(Account account) {
541 if (Log.isLoggable(TAG, Log.VERBOSE)) {
542 Log.v(TAG, "getPreviousName: " + account
543 + ", caller's uid " + Binder.getCallingUid()
544 + ", pid " + Binder.getCallingPid());
545 }
546 if (account == null) throw new IllegalArgumentException("account is null");
547 UserAccounts accounts = getUserAccountsForCaller();
548 long identityToken = clearCallingIdentity();
549 try {
550 return readPreviousNameInternal(accounts, account);
551 } finally {
552 restoreCallingIdentity(identityToken);
553 }
554 }
555
556 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
557 if (account == null) {
558 return null;
559 }
560 synchronized (accounts.cacheLock) {
561 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
562 if (previousNameRef == null) {
563 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
564 Cursor cursor = db.query(
565 TABLE_ACCOUNTS,
566 new String[]{ ACCOUNTS_PREVIOUS_NAME },
567 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
568 new String[] { account.name, account.type },
569 null,
570 null,
571 null);
572 try {
573 if (cursor.moveToNext()) {
574 String previousName = cursor.getString(0);
575 previousNameRef = new AtomicReference<String>(previousName);
576 accounts.previousNameCache.put(account, previousNameRef);
577 return previousName;
578 } else {
579 return null;
580 }
581 } finally {
582 cursor.close();
583 }
584 } else {
585 return previousNameRef.get();
586 }
587 }
588 }
589
590 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700591 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800592 if (Log.isLoggable(TAG, Log.VERBOSE)) {
593 Log.v(TAG, "getUserData: " + account
594 + ", key " + key
595 + ", caller's uid " + Binder.getCallingUid()
596 + ", pid " + Binder.getCallingPid());
597 }
Fred Quintana382601f2010-03-25 12:25:10 -0700598 if (account == null) throw new IllegalArgumentException("account is null");
599 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700600 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800601 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700602 long identityToken = clearCallingIdentity();
603 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800604 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700605 } finally {
606 restoreCallingIdentity(identityToken);
607 }
608 }
609
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800610 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100611 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800612 if (Log.isLoggable(TAG, Log.VERBOSE)) {
613 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100614 + "for user id " + userId
Fred Quintana56285a62010-12-02 14:20:51 -0800615 + "caller's uid " + Binder.getCallingUid()
616 + ", pid " + Binder.getCallingPid());
617 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100618 // Only allow the system process to read accounts of other users
619 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
620 + " trying get authenticator types for " + userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700621 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700622 try {
Fred Quintana97889762009-06-15 12:29:24 -0700623 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700624 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700625 AuthenticatorDescription[] types =
626 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700627 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700628 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700629 : authenticatorCollection) {
630 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700631 i++;
632 }
633 return types;
634 } finally {
635 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700636 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700637 }
638
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100639 private void enforceCrossUserPermission(int userId, String errorMessage) {
640 if (userId != UserHandle.getCallingUserId()
641 && Binder.getCallingUid() != Process.myUid()
642 && mContext.checkCallingOrSelfPermission(
643 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
644 != PackageManager.PERMISSION_GRANTED) {
645 throw new SecurityException(errorMessage);
646 }
647 }
648
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700649 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700650 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800651 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700652 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800653 + ", caller's uid " + Binder.getCallingUid()
654 + ", pid " + Binder.getCallingPid());
655 }
Fred Quintana382601f2010-03-25 12:25:10 -0700656 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700657 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700658 /*
659 * Child users are not allowed to add accounts. Only the accounts that are
660 * shared by the parent profile can be added to child profile.
661 *
662 * TODO: Only allow accounts that were shared to be added by
663 * a limited user.
664 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700665
Amith Yamasani04e0d262012-02-14 11:50:53 -0800666 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700667 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700668 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700669 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800670 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700671 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700672 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700673 }
674 }
675
Amith Yamasani67df64b2012-12-14 12:09:36 -0800676 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
677 final UserAccounts fromAccounts = getUserAccounts(userFrom);
678 final UserAccounts toAccounts = getUserAccounts(userTo);
679 if (fromAccounts == null || toAccounts == null) {
680 return false;
681 }
682
683 long identityToken = clearCallingIdentity();
684 try {
685 new Session(fromAccounts, null, account.type, false,
686 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700687 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800688 protected String toDebugString(long now) {
689 return super.toDebugString(now) + ", getAccountCredentialsForClone"
690 + ", " + account.type;
691 }
692
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700693 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800694 public void run() throws RemoteException {
695 mAuthenticator.getAccountCredentialsForCloning(this, account);
696 }
697
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700698 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800699 public void onResult(Bundle result) {
700 if (result != null) {
701 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
702 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800703 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800704 }
705 return;
706 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800707 super.onResult(result);
708 }
709 }
710 }.bind();
711 } finally {
712 restoreCallingIdentity(identityToken);
713 }
714 return true;
715 }
716
Amith Yamasani67df64b2012-12-14 12:09:36 -0800717 void completeCloningAccount(final Bundle result, final Account account,
718 final UserAccounts targetUser) {
719 long id = clearCallingIdentity();
720 try {
721 new Session(targetUser, null, account.type, false,
722 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700723 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800724 protected String toDebugString(long now) {
725 return super.toDebugString(now) + ", getAccountCredentialsForClone"
726 + ", " + account.type;
727 }
728
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700729 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800730 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700731 // Confirm that the owner's account still exists before this step.
732 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
733 synchronized (owner.cacheLock) {
734 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
735 for (Account acc : ownerAccounts) {
736 if (acc.equals(account)) {
737 mAuthenticator.addAccountFromCredentials(this, account, result);
738 break;
739 }
740 }
741 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800742 }
743
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700744 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800745 public void onResult(Bundle result) {
746 if (result != null) {
747 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
748 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800749 } else {
750 // TODO: Show error notification
751 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800752 }
753 return;
754 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800755 super.onResult(result);
756 }
757 }
758
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700759 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800760 public void onError(int errorCode, String errorMessage) {
761 super.onError(errorCode, errorMessage);
762 // TODO: Show error notification to user
763 // TODO: Should we remove the shadow account so that it doesn't keep trying?
764 }
765
766 }.bind();
767 } finally {
768 restoreCallingIdentity(id);
769 }
770 }
771
Amith Yamasani04e0d262012-02-14 11:50:53 -0800772 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800773 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700774 if (account == null) {
775 return false;
776 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800777 synchronized (accounts.cacheLock) {
778 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800779 db.beginTransaction();
780 try {
781 long numMatches = DatabaseUtils.longForQuery(db,
782 "select count(*) from " + TABLE_ACCOUNTS
783 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
784 new String[]{account.name, account.type});
785 if (numMatches > 0) {
786 Log.w(TAG, "insertAccountIntoDatabase: " + account
787 + ", skipping since the account already exists");
788 return false;
789 }
790 ContentValues values = new ContentValues();
791 values.put(ACCOUNTS_NAME, account.name);
792 values.put(ACCOUNTS_TYPE, account.type);
793 values.put(ACCOUNTS_PASSWORD, password);
794 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
795 if (accountId < 0) {
796 Log.w(TAG, "insertAccountIntoDatabase: " + account
797 + ", skipping the DB insert failed");
798 return false;
799 }
800 if (extras != null) {
801 for (String key : extras.keySet()) {
802 final String value = extras.getString(key);
803 if (insertExtraLocked(db, accountId, key, value) < 0) {
804 Log.w(TAG, "insertAccountIntoDatabase: " + account
805 + ", skipping since insertExtra failed for key " + key);
806 return false;
807 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700808 }
809 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800810 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800811 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800812 } finally {
813 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700814 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800815 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700816 }
817 if (accounts.userId == UserHandle.USER_OWNER) {
818 addAccountToLimitedUsers(account);
819 }
820 return true;
821 }
822
823 /**
824 * Adds the account to all limited users as shared accounts. If the user is currently
825 * running, then clone the account too.
826 * @param account the account to share with limited users
827 */
828 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700829 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700830 for (UserInfo user : users) {
831 if (user.isRestricted()) {
832 addSharedAccountAsUser(account, user.id);
833 try {
834 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
835 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
836 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
837 account));
838 }
839 } catch (RemoteException re) {
840 // Shouldn't happen
841 }
842 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700843 }
844 }
845
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800846 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700847 ContentValues values = new ContentValues();
848 values.put(EXTRAS_KEY, key);
849 values.put(EXTRAS_ACCOUNTS_ID, accountId);
850 values.put(EXTRAS_VALUE, value);
851 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
852 }
853
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800854 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -0800855 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800856 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800857 if (Log.isLoggable(TAG, Log.VERBOSE)) {
858 Log.v(TAG, "hasFeatures: " + account
859 + ", response " + response
860 + ", features " + stringArrayToString(features)
861 + ", caller's uid " + Binder.getCallingUid()
862 + ", pid " + Binder.getCallingPid());
863 }
Fred Quintana382601f2010-03-25 12:25:10 -0700864 if (response == null) throw new IllegalArgumentException("response is null");
865 if (account == null) throw new IllegalArgumentException("account is null");
866 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800867 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800868 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800869 long identityToken = clearCallingIdentity();
870 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800871 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800872 } finally {
873 restoreCallingIdentity(identityToken);
874 }
875 }
876
877 private class TestFeaturesSession extends Session {
878 private final String[] mFeatures;
879 private final Account mAccount;
880
Amith Yamasani04e0d262012-02-14 11:50:53 -0800881 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800882 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800883 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800884 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800885 mFeatures = features;
886 mAccount = account;
887 }
888
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700889 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800890 public void run() throws RemoteException {
891 try {
892 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
893 } catch (RemoteException e) {
894 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
895 }
896 }
897
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700898 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800899 public void onResult(Bundle result) {
900 IAccountManagerResponse response = getResponseAndClose();
901 if (response != null) {
902 try {
903 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700904 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800905 return;
906 }
Fred Quintana56285a62010-12-02 14:20:51 -0800907 if (Log.isLoggable(TAG, Log.VERBOSE)) {
908 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
909 + response);
910 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800911 final Bundle newResult = new Bundle();
912 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
913 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
914 response.onResult(newResult);
915 } catch (RemoteException e) {
916 // if the caller is dead then there is no one to care about remote exceptions
917 if (Log.isLoggable(TAG, Log.VERBOSE)) {
918 Log.v(TAG, "failure while notifying response", e);
919 }
920 }
921 }
922 }
923
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700924 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800925 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800926 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800927 + ", " + mAccount
928 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
929 }
930 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800931
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800932 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700933 public void renameAccount(
934 IAccountManagerResponse response, Account accountToRename, String newName) {
935 if (Log.isLoggable(TAG, Log.VERBOSE)) {
936 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
937 + ", caller's uid " + Binder.getCallingUid()
938 + ", pid " + Binder.getCallingPid());
939 }
940 if (accountToRename == null) throw new IllegalArgumentException("account is null");
941 checkAuthenticateAccountsPermission(accountToRename);
942 UserAccounts accounts = getUserAccountsForCaller();
943 long identityToken = clearCallingIdentity();
944 try {
945 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
946 Bundle result = new Bundle();
947 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
948 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
949 try {
950 response.onResult(result);
951 } catch (RemoteException e) {
952 Log.w(TAG, e.getMessage());
953 }
954 } finally {
955 restoreCallingIdentity(identityToken);
956 }
957 }
958
959 private Account renameAccountInternal(
960 UserAccounts accounts, Account accountToRename, String newName) {
961 Account resultAccount = null;
962 /*
963 * Cancel existing notifications. Let authenticators
964 * re-post notifications as required. But we don't know if
965 * the authenticators have bound their notifications to
966 * now stale account name data.
967 *
968 * With a rename api, we might not need to do this anymore but it
969 * shouldn't hurt.
970 */
971 cancelNotification(
972 getSigninRequiredNotificationId(accounts, accountToRename),
973 new UserHandle(accounts.userId));
974 synchronized(accounts.credentialsPermissionNotificationIds) {
975 for (Pair<Pair<Account, String>, Integer> pair:
976 accounts.credentialsPermissionNotificationIds.keySet()) {
977 if (accountToRename.equals(pair.first.first)) {
978 int id = accounts.credentialsPermissionNotificationIds.get(pair);
979 cancelNotification(id, new UserHandle(accounts.userId));
980 }
981 }
982 }
983 synchronized (accounts.cacheLock) {
984 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
985 db.beginTransaction();
986 boolean isSuccessful = false;
987 Account renamedAccount = new Account(newName, accountToRename.type);
988 try {
989 final ContentValues values = new ContentValues();
990 values.put(ACCOUNTS_NAME, newName);
991 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
992 final long accountId = getAccountIdLocked(db, accountToRename);
993 if (accountId >= 0) {
994 final String[] argsAccountId = { String.valueOf(accountId) };
995 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
996 db.setTransactionSuccessful();
997 isSuccessful = true;
998 }
999 } finally {
1000 db.endTransaction();
1001 if (isSuccessful) {
1002 /*
1003 * Database transaction was successful. Clean up cached
1004 * data associated with the account in the user profile.
1005 */
1006 insertAccountIntoCacheLocked(accounts, renamedAccount);
1007 /*
1008 * Extract the data and token caches before removing the
1009 * old account to preserve the user data associated with
1010 * the account.
1011 */
1012 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1013 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1014 removeAccountFromCacheLocked(accounts, accountToRename);
1015 /*
1016 * Update the cached data associated with the renamed
1017 * account.
1018 */
1019 accounts.userDataCache.put(renamedAccount, tmpData);
1020 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1021 accounts.previousNameCache.put(
1022 renamedAccount,
1023 new AtomicReference<String>(accountToRename.name));
1024 resultAccount = renamedAccount;
1025
1026 if (accounts.userId == UserHandle.USER_OWNER) {
1027 /*
1028 * Owner's account was renamed, rename the account for
1029 * those users with which the account was shared.
1030 */
1031 List<UserInfo> users = mUserManager.getUsers(true);
1032 for (UserInfo user : users) {
1033 if (!user.isPrimary() && user.isRestricted()) {
1034 renameSharedAccountAsUser(accountToRename, newName, user.id);
1035 }
1036 }
1037 }
1038 sendAccountsChangedBroadcast(accounts.userId);
1039 }
1040 }
1041 }
1042 return resultAccount;
1043 }
1044
1045 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001046 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001047 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1048 Log.v(TAG, "removeAccount: " + account
1049 + ", response " + response
1050 + ", caller's uid " + Binder.getCallingUid()
1051 + ", pid " + Binder.getCallingPid());
1052 }
Fred Quintana382601f2010-03-25 12:25:10 -07001053 if (response == null) throw new IllegalArgumentException("response is null");
1054 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001055 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001056 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001057 UserAccounts accounts = getUserAccountsForCaller();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001058 int userId = Binder.getCallingUserHandle().getIdentifier();
1059 if (!canUserModifyAccounts(userId)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001060 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001061 // TODO: This should be ERROR_CODE_USER_RESTRICTED instead. See http://b/16322768
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001062 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
1063 "User cannot modify accounts");
1064 } catch (RemoteException re) {
1065 }
Amith Yamasani5934dbc2014-02-20 15:23:36 -08001066 return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001067 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001068 if (!canUserModifyAccountsForType(userId, account.type)) {
1069 try {
1070 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1071 "User cannot modify accounts of this type (policy).");
1072 } catch (RemoteException re) {
1073 }
1074 return;
1075 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001076
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001077 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001078
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001079 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001080 synchronized (accounts.credentialsPermissionNotificationIds) {
1081 for (Pair<Pair<Account, String>, Integer> pair:
1082 accounts.credentialsPermissionNotificationIds.keySet()) {
1083 if (account.equals(pair.first.first)) {
1084 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1085 cancelNotification(id, user);
1086 }
1087 }
1088 }
1089
1090 try {
1091 new RemoveAccountSession(accounts, response, account).bind();
1092 } finally {
1093 restoreCallingIdentity(identityToken);
1094 }
1095 }
1096
1097 @Override
1098 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
1099 int userId) {
1100 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1101 Log.v(TAG, "removeAccount: " + account
1102 + ", response " + response
1103 + ", caller's uid " + Binder.getCallingUid()
1104 + ", pid " + Binder.getCallingPid()
1105 + ", for user id " + userId);
1106 }
1107 if (response == null) throw new IllegalArgumentException("response is null");
1108 if (account == null) throw new IllegalArgumentException("account is null");
1109
1110 // Only allow the system process to modify accounts of other users
1111 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1112 + " trying to remove account for " + userId);
1113 checkManageAccountsPermission();
1114
1115 UserAccounts accounts = getUserAccounts(userId);
1116 if (!canUserModifyAccounts(userId)) {
1117 try {
1118 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1119 "User cannot modify accounts");
1120 } catch (RemoteException re) {
1121 }
1122 return;
1123 }
1124 if (!canUserModifyAccountsForType(userId, account.type)) {
1125 try {
1126 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1127 "User cannot modify accounts of this type (policy).");
1128 } catch (RemoteException re) {
1129 }
1130 return;
1131 }
1132
1133 UserHandle user = new UserHandle(userId);
1134 long identityToken = clearCallingIdentity();
1135
1136 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001137 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001138 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001139 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001140 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001141 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001142 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001143 }
1144 }
1145 }
1146
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001147 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001148 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001149 } finally {
1150 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001151 }
Fred Quintana60307342009-03-24 22:48:12 -07001152 }
1153
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001154 private class RemoveAccountSession extends Session {
1155 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001156 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
1157 Account account) {
1158 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001159 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001160 mAccount = account;
1161 }
1162
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001163 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001164 protected String toDebugString(long now) {
1165 return super.toDebugString(now) + ", removeAccount"
1166 + ", account " + mAccount;
1167 }
1168
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001169 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001170 public void run() throws RemoteException {
1171 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1172 }
1173
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001174 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001175 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001176 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1177 && !result.containsKey(AccountManager.KEY_INTENT)) {
1178 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001179 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001180 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001181 }
1182 IAccountManagerResponse response = getResponseAndClose();
1183 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001184 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1185 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1186 + response);
1187 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001188 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001189 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001190 try {
1191 response.onResult(result2);
1192 } catch (RemoteException e) {
1193 // ignore
1194 }
1195 }
1196 }
1197 super.onResult(result);
1198 }
1199 }
1200
Amith Yamasani04e0d262012-02-14 11:50:53 -08001201 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001202 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001203 removeAccountInternal(getUserAccountsForCaller(), account);
1204 }
1205
1206 private void removeAccountInternal(UserAccounts accounts, Account account) {
1207 synchronized (accounts.cacheLock) {
1208 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001209 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1210 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001211 removeAccountFromCacheLocked(accounts, account);
1212 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001213 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001214 if (accounts.userId == UserHandle.USER_OWNER) {
1215 // Owner's account was removed, remove from any users that are sharing
1216 // this account.
1217 long id = Binder.clearCallingIdentity();
1218 try {
1219 List<UserInfo> users = mUserManager.getUsers(true);
1220 for (UserInfo user : users) {
1221 if (!user.isPrimary() && user.isRestricted()) {
1222 removeSharedAccountAsUser(account, user.id);
1223 }
1224 }
1225 } finally {
1226 Binder.restoreCallingIdentity(id);
1227 }
1228 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001229 }
1230
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001231 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001232 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001233 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1234 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
1235 + ", caller's uid " + Binder.getCallingUid()
1236 + ", pid " + Binder.getCallingPid());
1237 }
Fred Quintana382601f2010-03-25 12:25:10 -07001238 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1239 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -08001240 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001241 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001242 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001243 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001244 synchronized (accounts.cacheLock) {
1245 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001246 db.beginTransaction();
1247 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001248 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001249 db.setTransactionSuccessful();
1250 } finally {
1251 db.endTransaction();
1252 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001253 }
Fred Quintana60307342009-03-24 22:48:12 -07001254 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001255 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001256 }
1257 }
1258
Amith Yamasani04e0d262012-02-14 11:50:53 -08001259 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1260 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001261 if (authToken == null || accountType == null) {
1262 return;
1263 }
Fred Quintana33269202009-04-20 16:05:10 -07001264 Cursor cursor = db.rawQuery(
1265 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1266 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1267 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1268 + " FROM " + TABLE_ACCOUNTS
1269 + " JOIN " + TABLE_AUTHTOKENS
1270 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1271 + " = " + AUTHTOKENS_ACCOUNTS_ID
1272 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1273 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1274 new String[]{authToken, accountType});
1275 try {
1276 while (cursor.moveToNext()) {
1277 long authTokenId = cursor.getLong(0);
1278 String accountName = cursor.getString(1);
1279 String authTokenType = cursor.getString(2);
1280 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001281 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001282 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -07001283 }
Fred Quintana33269202009-04-20 16:05:10 -07001284 } finally {
1285 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001286 }
1287 }
1288
Amith Yamasani04e0d262012-02-14 11:50:53 -08001289 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1290 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001291 if (account == null || type == null) {
1292 return false;
1293 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001294 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1295 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001296 synchronized (accounts.cacheLock) {
1297 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001298 db.beginTransaction();
1299 try {
1300 long accountId = getAccountIdLocked(db, account);
1301 if (accountId < 0) {
1302 return false;
1303 }
1304 db.delete(TABLE_AUTHTOKENS,
1305 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1306 new String[]{type});
1307 ContentValues values = new ContentValues();
1308 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1309 values.put(AUTHTOKENS_TYPE, type);
1310 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1311 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1312 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001313 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001314 return true;
1315 }
Fred Quintana33269202009-04-20 16:05:10 -07001316 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001317 } finally {
1318 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001319 }
Fred Quintana60307342009-03-24 22:48:12 -07001320 }
1321 }
1322
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001323 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001324 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001325 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1326 Log.v(TAG, "peekAuthToken: " + account
1327 + ", authTokenType " + authTokenType
1328 + ", caller's uid " + Binder.getCallingUid()
1329 + ", pid " + Binder.getCallingPid());
1330 }
Fred Quintana382601f2010-03-25 12:25:10 -07001331 if (account == null) throw new IllegalArgumentException("account is null");
1332 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001333 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001334 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001335 long identityToken = clearCallingIdentity();
1336 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001337 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001338 } finally {
1339 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001340 }
Fred Quintana60307342009-03-24 22:48:12 -07001341 }
1342
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001343 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001344 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001345 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1346 Log.v(TAG, "setAuthToken: " + account
1347 + ", authTokenType " + authTokenType
1348 + ", caller's uid " + Binder.getCallingUid()
1349 + ", pid " + Binder.getCallingPid());
1350 }
Fred Quintana382601f2010-03-25 12:25:10 -07001351 if (account == null) throw new IllegalArgumentException("account is null");
1352 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001353 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001354 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001355 long identityToken = clearCallingIdentity();
1356 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001357 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001358 } finally {
1359 restoreCallingIdentity(identityToken);
1360 }
Fred Quintana60307342009-03-24 22:48:12 -07001361 }
1362
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001363 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001364 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001365 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1366 Log.v(TAG, "setAuthToken: " + account
1367 + ", caller's uid " + Binder.getCallingUid()
1368 + ", pid " + Binder.getCallingPid());
1369 }
Fred Quintana382601f2010-03-25 12:25:10 -07001370 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001371 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001372 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001373 long identityToken = clearCallingIdentity();
1374 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001375 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001376 } finally {
1377 restoreCallingIdentity(identityToken);
1378 }
Fred Quintana60307342009-03-24 22:48:12 -07001379 }
1380
Amith Yamasani04e0d262012-02-14 11:50:53 -08001381 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001382 if (account == null) {
1383 return;
1384 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001385 synchronized (accounts.cacheLock) {
1386 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001387 db.beginTransaction();
1388 try {
1389 final ContentValues values = new ContentValues();
1390 values.put(ACCOUNTS_PASSWORD, password);
1391 final long accountId = getAccountIdLocked(db, account);
1392 if (accountId >= 0) {
1393 final String[] argsAccountId = {String.valueOf(accountId)};
1394 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1395 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001396 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001397 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001398 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001399 } finally {
1400 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001401 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001402 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001403 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001404 }
1405
Amith Yamasani04e0d262012-02-14 11:50:53 -08001406 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001407 Log.i(TAG, "the accounts changed, sending broadcast of "
1408 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001409 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001410 }
1411
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001412 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001413 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001414 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1415 Log.v(TAG, "clearPassword: " + account
1416 + ", caller's uid " + Binder.getCallingUid()
1417 + ", pid " + Binder.getCallingPid());
1418 }
Fred Quintana382601f2010-03-25 12:25:10 -07001419 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001420 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001421 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001422 long identityToken = clearCallingIdentity();
1423 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001424 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001425 } finally {
1426 restoreCallingIdentity(identityToken);
1427 }
Fred Quintana60307342009-03-24 22:48:12 -07001428 }
1429
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001430 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001431 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001432 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1433 Log.v(TAG, "setUserData: " + account
1434 + ", key " + key
1435 + ", caller's uid " + Binder.getCallingUid()
1436 + ", pid " + Binder.getCallingPid());
1437 }
Fred Quintana382601f2010-03-25 12:25:10 -07001438 if (key == null) throw new IllegalArgumentException("key is null");
1439 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001440 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001441 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001442 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001443 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001444 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001445 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001446 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001447 }
1448 }
1449
Amith Yamasani04e0d262012-02-14 11:50:53 -08001450 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1451 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001452 if (account == null || key == null) {
1453 return;
1454 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001455 synchronized (accounts.cacheLock) {
1456 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001457 db.beginTransaction();
1458 try {
1459 long accountId = getAccountIdLocked(db, account);
1460 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001461 return;
1462 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001463 long extrasId = getExtrasIdLocked(db, accountId, key);
1464 if (extrasId < 0 ) {
1465 extrasId = insertExtraLocked(db, accountId, key, value);
1466 if (extrasId < 0) {
1467 return;
1468 }
1469 } else {
1470 ContentValues values = new ContentValues();
1471 values.put(EXTRAS_VALUE, value);
1472 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1473 return;
1474 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001475
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001476 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001477 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001478 db.setTransactionSuccessful();
1479 } finally {
1480 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001481 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001482 }
1483 }
1484
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001485 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001486 if (result == null) {
1487 Log.e(TAG, "the result is unexpectedly null", new Exception());
1488 }
1489 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1490 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1491 + response);
1492 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001493 try {
1494 response.onResult(result);
1495 } catch (RemoteException e) {
1496 // if the caller is dead then there is no one to care about remote
1497 // exceptions
1498 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1499 Log.v(TAG, "failure while notifying response", e);
1500 }
1501 }
1502 }
1503
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001504 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001505 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1506 final String authTokenType)
1507 throws RemoteException {
1508 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001509 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1510
Fred Quintanad9640ec2012-05-23 12:37:00 -07001511 final int callingUid = getCallingUid();
1512 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001513 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001514 throw new SecurityException("can only call from system");
1515 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001516 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001517 long identityToken = clearCallingIdentity();
1518 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001519 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001520 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001521 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001522 protected String toDebugString(long now) {
1523 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001524 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001525 + ", authTokenType " + authTokenType;
1526 }
1527
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001528 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001529 public void run() throws RemoteException {
1530 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1531 }
1532
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001533 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001534 public void onResult(Bundle result) {
1535 if (result != null) {
1536 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1537 Bundle bundle = new Bundle();
1538 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1539 super.onResult(bundle);
1540 return;
1541 } else {
1542 super.onResult(result);
1543 }
1544 }
1545 }.bind();
1546 } finally {
1547 restoreCallingIdentity(identityToken);
1548 }
1549 }
1550
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001551 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001552 public void getAuthToken(IAccountManagerResponse response, final Account account,
1553 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001554 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001555 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1556 Log.v(TAG, "getAuthToken: " + account
1557 + ", response " + response
1558 + ", authTokenType " + authTokenType
1559 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1560 + ", expectActivityLaunch " + expectActivityLaunch
1561 + ", caller's uid " + Binder.getCallingUid()
1562 + ", pid " + Binder.getCallingPid());
1563 }
Fred Quintana382601f2010-03-25 12:25:10 -07001564 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001565 try {
1566 if (account == null) {
1567 Slog.w(TAG, "getAuthToken called with null account");
1568 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1569 return;
1570 }
1571 if (authTokenType == null) {
1572 Slog.w(TAG, "getAuthToken called with null authTokenType");
1573 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1574 return;
1575 }
1576 } catch (RemoteException e) {
1577 Slog.w(TAG, "Failed to report error back to the client." + e);
1578 return;
1579 }
1580
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001581 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001582 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001583 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1584 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1585 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001586 final boolean customTokens =
1587 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1588
1589 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001590 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001591 final boolean permissionGranted = customTokens ||
1592 permissionIsGranted(account, authTokenType, callerUid);
1593
Costin Manolachec6684f92011-01-14 11:25:39 -08001594 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1595 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001596 // let authenticator know the identity of the caller
1597 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1598 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1599 if (notifyOnAuthFailure) {
1600 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001601 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001602
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001603 long identityToken = clearCallingIdentity();
1604 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001605 // if the caller has permission, do the peek. otherwise go the more expensive
1606 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001607 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001608 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001609 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001610 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001611 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1612 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1613 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001614 onResult(response, result);
1615 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001616 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001617 }
1618
Amith Yamasani04e0d262012-02-14 11:50:53 -08001619 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001620 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001621 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001622 protected String toDebugString(long now) {
1623 if (loginOptions != null) loginOptions.keySet();
1624 return super.toDebugString(now) + ", getAuthToken"
1625 + ", " + account
1626 + ", authTokenType " + authTokenType
1627 + ", loginOptions " + loginOptions
1628 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1629 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001630
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001631 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001632 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001633 // If the caller doesn't have permission then create and return the
1634 // "grant permission" intent instead of the "getAuthToken" intent.
1635 if (!permissionGranted) {
1636 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1637 } else {
1638 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1639 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001640 }
1641
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001642 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001643 public void onResult(Bundle result) {
1644 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001645 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001646 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1647 new AccountAuthenticatorResponse(this),
1648 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001649 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001650 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001651 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001652 onResult(bundle);
1653 return;
1654 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001655 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001656 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001657 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1658 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001659 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001660 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001661 "the type and name should not be empty");
1662 return;
1663 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001664 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001665 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001666 authTokenType, authToken);
1667 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001668 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001669
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001670 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001671 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001672 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001673 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001674 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001675 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001676 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001677 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001678 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001679 }.bind();
1680 } finally {
1681 restoreCallingIdentity(identityToken);
1682 }
Fred Quintana60307342009-03-24 22:48:12 -07001683 }
1684
Dianne Hackborn41203752012-08-31 14:05:51 -07001685 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1686 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001687 int uid = intent.getIntExtra(
1688 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1689 String authTokenType = intent.getStringExtra(
1690 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1691 String authTokenLabel = intent.getStringExtra(
1692 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1693
1694 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1695 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001696 final String titleAndSubtitle =
1697 mContext.getString(R.string.permission_request_notification_with_subtitle,
1698 account.name);
1699 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001700 String title = titleAndSubtitle;
1701 String subtitle = "";
1702 if (index > 0) {
1703 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001704 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001705 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001706 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01001707 Context contextForUser = getContextForUser(user);
1708 n.color = contextForUser.getResources().getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001709 com.android.internal.R.color.system_notification_accent_color);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01001710 n.setLatestEventInfo(contextForUser, title, subtitle,
Dianne Hackborn41203752012-08-31 14:05:51 -07001711 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001712 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1713 installNotification(getCredentialPermissionNotificationId(
1714 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001715 }
1716
Costin Manolache5f383ad92010-12-02 16:44:46 -08001717 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1718 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001719
1720 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001721 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001722 // Since it was set in Eclair+ we can't change it without breaking apps using
1723 // the intent from a non-Activity context.
1724 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001725 intent.addCategory(
1726 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001727
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001728 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001729 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1730 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001731 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001732
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001733 return intent;
1734 }
1735
1736 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1737 int uid) {
1738 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001739 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001740 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001741 final Pair<Pair<Account, String>, Integer> key =
1742 new Pair<Pair<Account, String>, Integer>(
1743 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001744 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001745 if (id == null) {
1746 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001747 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001748 }
1749 }
1750 return id;
1751 }
1752
Amith Yamasani04e0d262012-02-14 11:50:53 -08001753 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001754 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001755 synchronized (accounts.signinRequiredNotificationIds) {
1756 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001757 if (id == null) {
1758 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001759 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001760 }
1761 }
1762 return id;
1763 }
1764
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001765 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001766 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001767 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001768 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001769 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1770 Log.v(TAG, "addAccount: accountType " + accountType
1771 + ", response " + response
1772 + ", authTokenType " + authTokenType
1773 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1774 + ", expectActivityLaunch " + expectActivityLaunch
1775 + ", caller's uid " + Binder.getCallingUid()
1776 + ", pid " + Binder.getCallingPid());
1777 }
Fred Quintana382601f2010-03-25 12:25:10 -07001778 if (response == null) throw new IllegalArgumentException("response is null");
1779 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001780 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001781
Amith Yamasani71e6c692013-03-24 17:39:28 -07001782 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001783 int userId = Binder.getCallingUserHandle().getIdentifier();
1784 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001785 try {
1786 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1787 "User is not allowed to add an account!");
1788 } catch (RemoteException re) {
1789 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001790 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED);
1791 return;
1792 }
1793 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07001794 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001795 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1796 "User cannot modify accounts of this type (policy).");
1797 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07001798 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001799 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001800 return;
1801 }
1802
Amith Yamasani04e0d262012-02-14 11:50:53 -08001803 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001804 final int pid = Binder.getCallingPid();
1805 final int uid = Binder.getCallingUid();
1806 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1807 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1808 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1809
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001810 long identityToken = clearCallingIdentity();
1811 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001812 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001813 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001814 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001815 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001816 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001817 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001818 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001819
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001820 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001821 protected String toDebugString(long now) {
1822 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001823 + ", accountType " + accountType
1824 + ", requiredFeatures "
1825 + (requiredFeatures != null
1826 ? TextUtils.join(",", requiredFeatures)
1827 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001828 }
1829 }.bind();
1830 } finally {
1831 restoreCallingIdentity(identityToken);
1832 }
Fred Quintana60307342009-03-24 22:48:12 -07001833 }
1834
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001835 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001836 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
1837 final String authTokenType, final String[] requiredFeatures,
1838 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
1839 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1840 Log.v(TAG, "addAccount: accountType " + accountType
1841 + ", response " + response
1842 + ", authTokenType " + authTokenType
1843 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1844 + ", expectActivityLaunch " + expectActivityLaunch
1845 + ", caller's uid " + Binder.getCallingUid()
1846 + ", pid " + Binder.getCallingPid()
1847 + ", for user id " + userId);
1848 }
1849 if (response == null) throw new IllegalArgumentException("response is null");
1850 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1851 checkManageAccountsPermission();
1852
1853 // Only allow the system process to add accounts of other users
1854 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1855 + " trying to add account for " + userId);
1856
1857 // Is user disallowed from modifying accounts?
1858 if (!canUserModifyAccounts(userId)) {
1859 try {
1860 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1861 "User is not allowed to add an account!");
1862 } catch (RemoteException re) {
1863 }
1864 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED);
1865 return;
1866 }
1867 if (!canUserModifyAccountsForType(userId, accountType)) {
1868 try {
1869 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1870 "User cannot modify accounts of this type (policy).");
1871 } catch (RemoteException re) {
1872 }
1873 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
1874 return;
1875 }
1876
1877 UserAccounts accounts = getUserAccounts(userId);
1878 final int pid = Binder.getCallingPid();
1879 final int uid = Binder.getCallingUid();
1880 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1881 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1882 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1883
1884 long identityToken = clearCallingIdentity();
1885 try {
1886 new Session(accounts, response, accountType, expectActivityLaunch,
1887 true /* stripAuthTokenFromResult */) {
1888 @Override
1889 public void run() throws RemoteException {
1890 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
1891 options);
1892 }
1893
1894 @Override
1895 protected String toDebugString(long now) {
1896 return super.toDebugString(now) + ", addAccount"
1897 + ", accountType " + accountType
1898 + ", requiredFeatures "
1899 + (requiredFeatures != null
1900 ? TextUtils.join(",", requiredFeatures)
1901 : null);
1902 }
1903 }.bind();
1904 } finally {
1905 restoreCallingIdentity(identityToken);
1906 }
1907 }
1908
1909 private void showCantAddAccount(int errorCode) {
1910 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1911 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
1912 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1913 long identityToken = clearCallingIdentity();
1914 try {
1915 mContext.startActivity(cantAddAccount);
1916 } finally {
1917 restoreCallingIdentity(identityToken);
1918 }
1919 }
1920
1921 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001922 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1923 final Account account, final Bundle options, final boolean expectActivityLaunch,
1924 int userId) {
1925 // Only allow the system process to read accounts of other users
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001926 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001927 + " trying to confirm account credentials for " + userId);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001928
Fred Quintana56285a62010-12-02 14:20:51 -08001929 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1930 Log.v(TAG, "confirmCredentials: " + account
1931 + ", response " + response
1932 + ", expectActivityLaunch " + expectActivityLaunch
1933 + ", caller's uid " + Binder.getCallingUid()
1934 + ", pid " + Binder.getCallingPid());
1935 }
Fred Quintana382601f2010-03-25 12:25:10 -07001936 if (response == null) throw new IllegalArgumentException("response is null");
1937 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001938 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001939 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001940 long identityToken = clearCallingIdentity();
1941 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001942 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001943 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001944 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001945 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001946 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001947 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001948 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001949 protected String toDebugString(long now) {
1950 return super.toDebugString(now) + ", confirmCredentials"
1951 + ", " + account;
1952 }
1953 }.bind();
1954 } finally {
1955 restoreCallingIdentity(identityToken);
1956 }
Fred Quintana60307342009-03-24 22:48:12 -07001957 }
1958
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001959 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001960 public void updateCredentials(IAccountManagerResponse response, final Account account,
1961 final String authTokenType, final boolean expectActivityLaunch,
1962 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001963 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1964 Log.v(TAG, "updateCredentials: " + account
1965 + ", response " + response
1966 + ", authTokenType " + authTokenType
1967 + ", expectActivityLaunch " + expectActivityLaunch
1968 + ", caller's uid " + Binder.getCallingUid()
1969 + ", pid " + Binder.getCallingPid());
1970 }
Fred Quintana382601f2010-03-25 12:25:10 -07001971 if (response == null) throw new IllegalArgumentException("response is null");
1972 if (account == null) throw new IllegalArgumentException("account is null");
1973 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001974 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001975 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001976 long identityToken = clearCallingIdentity();
1977 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001978 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001979 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001980 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001981 public void run() throws RemoteException {
1982 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1983 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001984 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001985 protected String toDebugString(long now) {
1986 if (loginOptions != null) loginOptions.keySet();
1987 return super.toDebugString(now) + ", updateCredentials"
1988 + ", " + account
1989 + ", authTokenType " + authTokenType
1990 + ", loginOptions " + loginOptions;
1991 }
1992 }.bind();
1993 } finally {
1994 restoreCallingIdentity(identityToken);
1995 }
Fred Quintana60307342009-03-24 22:48:12 -07001996 }
1997
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001998 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001999 public void editProperties(IAccountManagerResponse response, final String accountType,
2000 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08002001 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2002 Log.v(TAG, "editProperties: accountType " + accountType
2003 + ", response " + response
2004 + ", expectActivityLaunch " + expectActivityLaunch
2005 + ", caller's uid " + Binder.getCallingUid()
2006 + ", pid " + Binder.getCallingPid());
2007 }
Fred Quintana382601f2010-03-25 12:25:10 -07002008 if (response == null) throw new IllegalArgumentException("response is null");
2009 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002010 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002011 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002012 long identityToken = clearCallingIdentity();
2013 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002014 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08002015 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002016 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002017 public void run() throws RemoteException {
2018 mAuthenticator.editProperties(this, mAccountType);
2019 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002020 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002021 protected String toDebugString(long now) {
2022 return super.toDebugString(now) + ", editProperties"
2023 + ", accountType " + accountType;
2024 }
2025 }.bind();
2026 } finally {
2027 restoreCallingIdentity(identityToken);
2028 }
Fred Quintana60307342009-03-24 22:48:12 -07002029 }
2030
Fred Quintana33269202009-04-20 16:05:10 -07002031 private class GetAccountsByTypeAndFeatureSession extends Session {
2032 private final String[] mFeatures;
2033 private volatile Account[] mAccountsOfType = null;
2034 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2035 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002036 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002037
Amith Yamasani04e0d262012-02-14 11:50:53 -08002038 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002039 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002040 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08002041 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002042 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002043 mFeatures = features;
2044 }
2045
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002046 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002047 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002048 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002049 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2050 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002051 }
Fred Quintana33269202009-04-20 16:05:10 -07002052 // check whether each account matches the requested features
2053 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2054 mCurrentAccount = 0;
2055
2056 checkAccount();
2057 }
2058
2059 public void checkAccount() {
2060 if (mCurrentAccount >= mAccountsOfType.length) {
2061 sendResult();
2062 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002063 }
Fred Quintana33269202009-04-20 16:05:10 -07002064
Fred Quintana29e94b82010-03-10 12:11:51 -08002065 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2066 if (accountAuthenticator == null) {
2067 // It is possible that the authenticator has died, which is indicated by
2068 // mAuthenticator being set to null. If this happens then just abort.
2069 // There is no need to send back a result or error in this case since
2070 // that already happened when mAuthenticator was cleared.
2071 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2072 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2073 + " connected to the authenticator, " + toDebugString());
2074 }
2075 return;
2076 }
Fred Quintana33269202009-04-20 16:05:10 -07002077 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002078 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002079 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002080 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002081 }
2082 }
2083
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002084 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002085 public void onResult(Bundle result) {
2086 mNumResults++;
2087 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002088 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002089 return;
2090 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002091 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002092 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2093 }
2094 mCurrentAccount++;
2095 checkAccount();
2096 }
2097
2098 public void sendResult() {
2099 IAccountManagerResponse response = getResponseAndClose();
2100 if (response != null) {
2101 try {
2102 Account[] accounts = new Account[mAccountsWithFeatures.size()];
2103 for (int i = 0; i < accounts.length; i++) {
2104 accounts[i] = mAccountsWithFeatures.get(i);
2105 }
Fred Quintana56285a62010-12-02 14:20:51 -08002106 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2107 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2108 + response);
2109 }
Fred Quintana33269202009-04-20 16:05:10 -07002110 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002111 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07002112 response.onResult(result);
2113 } catch (RemoteException e) {
2114 // if the caller is dead then there is no one to care about remote exceptions
2115 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2116 Log.v(TAG, "failure while notifying response", e);
2117 }
2118 }
2119 }
2120 }
2121
2122
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002123 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002124 protected String toDebugString(long now) {
2125 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2126 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2127 }
2128 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002129
Amith Yamasani04e0d262012-02-14 11:50:53 -08002130 /**
2131 * Returns the accounts for a specific user
2132 * @hide
2133 */
2134 public Account[] getAccounts(int userId) {
2135 checkReadAccountsPermission();
2136 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002137 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002138 long identityToken = clearCallingIdentity();
2139 try {
2140 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002141 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002142 }
2143 } finally {
2144 restoreCallingIdentity(identityToken);
2145 }
2146 }
2147
Amith Yamasanif29f2362012-04-05 18:29:52 -07002148 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002149 * Returns accounts for all running users.
2150 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07002151 * @hide
2152 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002153 public AccountAndUser[] getRunningAccounts() {
2154 final int[] runningUserIds;
2155 try {
2156 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2157 } catch (RemoteException e) {
2158 // Running in system_server; should never happen
2159 throw new RuntimeException(e);
2160 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002161 return getAccounts(runningUserIds);
2162 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07002163
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002164 /** {@hide} */
2165 public AccountAndUser[] getAllAccounts() {
2166 final List<UserInfo> users = getUserManager().getUsers();
2167 final int[] userIds = new int[users.size()];
2168 for (int i = 0; i < userIds.length; i++) {
2169 userIds[i] = users.get(i).id;
2170 }
2171 return getAccounts(userIds);
2172 }
2173
2174 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002175 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002176 for (int userId : userIds) {
2177 UserAccounts userAccounts = getUserAccounts(userId);
2178 if (userAccounts == null) continue;
2179 synchronized (userAccounts.cacheLock) {
2180 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2181 Binder.getCallingUid(), null);
2182 for (int a = 0; a < accounts.length; a++) {
2183 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07002184 }
2185 }
2186 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002187
2188 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2189 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002190 }
2191
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002192 @Override
2193 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002194 return getAccountsAsUser(type, userId, null, -1);
2195 }
2196
2197 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
2198 int packageUid) {
2199 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002200 // Only allow the system process to read accounts of other users
2201 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002202 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002203 && mContext.checkCallingOrSelfPermission(
2204 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2205 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002206 throw new SecurityException("User " + UserHandle.getCallingUserId()
2207 + " trying to get account for " + userId);
2208 }
2209
Fred Quintana56285a62010-12-02 14:20:51 -08002210 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2211 Log.v(TAG, "getAccounts: accountType " + type
2212 + ", caller's uid " + Binder.getCallingUid()
2213 + ", pid " + Binder.getCallingPid());
2214 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002215 // If the original calling app was using the framework account chooser activity, we'll
2216 // be passed in the original caller's uid here, which is what should be used for filtering.
2217 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2218 callingUid = packageUid;
2219 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002220 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002221 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002222 long identityToken = clearCallingIdentity();
2223 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002224 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002225 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002226 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002227 } finally {
2228 restoreCallingIdentity(identityToken);
2229 }
2230 }
2231
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002232 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002233 public boolean addSharedAccountAsUser(Account account, int userId) {
2234 userId = handleIncomingUser(userId);
2235 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
2236 ContentValues values = new ContentValues();
2237 values.put(ACCOUNTS_NAME, account.name);
2238 values.put(ACCOUNTS_TYPE, account.type);
2239 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2240 new String[] {account.name, account.type});
2241 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2242 if (accountId < 0) {
2243 Log.w(TAG, "insertAccountIntoDatabase: " + account
2244 + ", skipping the DB insert failed");
2245 return false;
2246 }
2247 return true;
2248 }
2249
2250 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002251 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
2252 userId = handleIncomingUser(userId);
2253 UserAccounts accounts = getUserAccounts(userId);
2254 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2255 final ContentValues values = new ContentValues();
2256 values.put(ACCOUNTS_NAME, newName);
2257 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
2258 int r = db.update(
2259 TABLE_SHARED_ACCOUNTS,
2260 values,
2261 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2262 new String[] { account.name, account.type });
2263 if (r > 0) {
2264 // Recursively rename the account.
2265 renameAccountInternal(accounts, account, newName);
2266 }
2267 return r > 0;
2268 }
2269
2270 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002271 public boolean removeSharedAccountAsUser(Account account, int userId) {
2272 userId = handleIncomingUser(userId);
2273 UserAccounts accounts = getUserAccounts(userId);
2274 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2275 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2276 new String[] {account.name, account.type});
2277 if (r > 0) {
2278 removeAccountInternal(accounts, account);
2279 }
2280 return r > 0;
2281 }
2282
2283 @Override
2284 public Account[] getSharedAccountsAsUser(int userId) {
2285 userId = handleIncomingUser(userId);
2286 UserAccounts accounts = getUserAccounts(userId);
2287 ArrayList<Account> accountList = new ArrayList<Account>();
2288 Cursor cursor = null;
2289 try {
2290 cursor = accounts.openHelper.getReadableDatabase()
2291 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2292 null, null, null, null, null);
2293 if (cursor != null && cursor.moveToFirst()) {
2294 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2295 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2296 do {
2297 accountList.add(new Account(cursor.getString(nameIndex),
2298 cursor.getString(typeIndex)));
2299 } while (cursor.moveToNext());
2300 }
2301 } finally {
2302 if (cursor != null) {
2303 cursor.close();
2304 }
2305 }
2306 Account[] accountArray = new Account[accountList.size()];
2307 accountList.toArray(accountArray);
2308 return accountArray;
2309 }
2310
2311 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002312 public Account[] getAccounts(String type) {
2313 return getAccountsAsUser(type, UserHandle.getCallingUserId());
2314 }
2315
Amith Yamasani27db4682013-03-30 17:07:47 -07002316 @Override
2317 public Account[] getAccountsForPackage(String packageName, int uid) {
2318 int callingUid = Binder.getCallingUid();
2319 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2320 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2321 + callingUid + " with uid=" + uid);
2322 }
2323 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
2324 }
2325
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002326 @Override
2327 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
2328 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
2329 int packageUid = -1;
2330 try {
2331 packageUid = AppGlobals.getPackageManager().getPackageUid(
2332 packageName, UserHandle.getCallingUserId());
2333 } catch (RemoteException re) {
2334 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2335 return new Account[0];
2336 }
2337 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
2338 }
2339
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002340 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002341 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07002342 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08002343 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2344 Log.v(TAG, "getAccounts: accountType " + type
2345 + ", response " + response
2346 + ", features " + stringArrayToString(features)
2347 + ", caller's uid " + Binder.getCallingUid()
2348 + ", pid " + Binder.getCallingPid());
2349 }
Fred Quintana382601f2010-03-25 12:25:10 -07002350 if (response == null) throw new IllegalArgumentException("response is null");
2351 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002352 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002353 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002354 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07002355 long identityToken = clearCallingIdentity();
2356 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002357 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002358 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002359 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002360 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002361 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002362 Bundle result = new Bundle();
2363 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2364 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002365 return;
2366 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002367 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
2368 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002369 } finally {
2370 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002371 }
2372 }
2373
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002374 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002375 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002376 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002377 try {
2378 if (cursor.moveToNext()) {
2379 return cursor.getLong(0);
2380 }
2381 return -1;
2382 } finally {
2383 cursor.close();
2384 }
2385 }
2386
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002387 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002388 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2389 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2390 new String[]{key}, null, null, null);
2391 try {
2392 if (cursor.moveToNext()) {
2393 return cursor.getLong(0);
2394 }
2395 return -1;
2396 } finally {
2397 cursor.close();
2398 }
2399 }
2400
Fred Quintanaa698f422009-04-08 19:14:54 -07002401 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002402 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002403 IAccountManagerResponse mResponse;
2404 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002405 final boolean mExpectActivityLaunch;
2406 final long mCreationTime;
2407
Fred Quintana33269202009-04-20 16:05:10 -07002408 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002409 private int mNumRequestContinued = 0;
2410 private int mNumErrors = 0;
2411
Fred Quintana60307342009-03-24 22:48:12 -07002412 IAccountAuthenticator mAuthenticator = null;
2413
Fred Quintana8570f742010-02-18 10:32:54 -08002414 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002415 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002416
Amith Yamasani04e0d262012-02-14 11:50:53 -08002417 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08002418 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07002419 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002420 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002421 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002422 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002423 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002424 mResponse = response;
2425 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002426 mExpectActivityLaunch = expectActivityLaunch;
2427 mCreationTime = SystemClock.elapsedRealtime();
2428 synchronized (mSessions) {
2429 mSessions.put(toString(), this);
2430 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002431 if (response != null) {
2432 try {
2433 response.asBinder().linkToDeath(this, 0 /* flags */);
2434 } catch (RemoteException e) {
2435 mResponse = null;
2436 binderDied();
2437 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002438 }
Fred Quintana60307342009-03-24 22:48:12 -07002439 }
2440
Fred Quintanaa698f422009-04-08 19:14:54 -07002441 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002442 if (mResponse == null) {
2443 // this session has already been closed
2444 return null;
2445 }
Fred Quintana60307342009-03-24 22:48:12 -07002446 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002447 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002448 return response;
2449 }
2450
Fred Quintanaa698f422009-04-08 19:14:54 -07002451 private void close() {
2452 synchronized (mSessions) {
2453 if (mSessions.remove(toString()) == null) {
2454 // the session was already closed, so bail out now
2455 return;
2456 }
2457 }
2458 if (mResponse != null) {
2459 // stop listening for response deaths
2460 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2461
2462 // clear this so that we don't accidentally send any further results
2463 mResponse = null;
2464 }
2465 cancelTimeout();
2466 unbind();
2467 }
2468
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002469 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002470 public void binderDied() {
2471 mResponse = null;
2472 close();
2473 }
2474
2475 protected String toDebugString() {
2476 return toDebugString(SystemClock.elapsedRealtime());
2477 }
2478
2479 protected String toDebugString(long now) {
2480 return "Session: expectLaunch " + mExpectActivityLaunch
2481 + ", connected " + (mAuthenticator != null)
2482 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2483 + "/" + mNumErrors + ")"
2484 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2485 }
2486
Fred Quintana60307342009-03-24 22:48:12 -07002487 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002488 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2489 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2490 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002491 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002492 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002493 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002494 }
2495 }
2496
2497 private void unbind() {
2498 if (mAuthenticator != null) {
2499 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002500 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002501 }
2502 }
2503
2504 public void scheduleTimeout() {
2505 mMessageHandler.sendMessageDelayed(
2506 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2507 }
2508
2509 public void cancelTimeout() {
2510 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2511 }
2512
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002513 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002514 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002515 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002516 try {
2517 run();
2518 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002519 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002520 "remote exception");
2521 }
Fred Quintana60307342009-03-24 22:48:12 -07002522 }
2523
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002524 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002525 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002526 mAuthenticator = null;
2527 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002528 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002529 try {
2530 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2531 "disconnected");
2532 } catch (RemoteException e) {
2533 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2534 Log.v(TAG, "Session.onServiceDisconnected: "
2535 + "caught RemoteException while responding", e);
2536 }
2537 }
Fred Quintana60307342009-03-24 22:48:12 -07002538 }
2539 }
2540
Fred Quintanab839afc2009-10-14 15:57:28 -07002541 public abstract void run() throws RemoteException;
2542
Fred Quintana60307342009-03-24 22:48:12 -07002543 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002544 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002545 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002546 try {
2547 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2548 "timeout");
2549 } catch (RemoteException e) {
2550 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2551 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2552 e);
2553 }
2554 }
Fred Quintana60307342009-03-24 22:48:12 -07002555 }
2556 }
2557
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002558 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002559 public void onResult(Bundle result) {
2560 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002561 Intent intent = null;
2562 if (result != null
2563 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2564 /*
2565 * The Authenticator API allows third party authenticators to
2566 * supply arbitrary intents to other apps that they can run,
2567 * this can be very bad when those apps are in the system like
2568 * the System Settings.
2569 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002570 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07002571 long bid = Binder.clearCallingIdentity();
2572 try {
2573 PackageManager pm = mContext.getPackageManager();
2574 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2575 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2576 if (PackageManager.SIGNATURE_MATCH !=
2577 pm.checkSignatures(authenticatorUid, targetUid)) {
2578 throw new SecurityException(
2579 "Activity to be started with KEY_INTENT must " +
2580 "share Authenticator's signatures");
2581 }
2582 } finally {
2583 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002584 }
2585 }
2586 if (result != null
2587 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002588 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2589 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002590 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2591 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002592 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2593 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002594 }
Fred Quintana60307342009-03-24 22:48:12 -07002595 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002596 IAccountManagerResponse response;
2597 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002598 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002599 response = mResponse;
2600 } else {
2601 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002602 }
Fred Quintana60307342009-03-24 22:48:12 -07002603 if (response != null) {
2604 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002605 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002606 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2607 Log.v(TAG, getClass().getSimpleName()
2608 + " calling onError() on response " + response);
2609 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002610 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002611 "null bundle returned");
2612 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002613 if (mStripAuthTokenFromResult) {
2614 result.remove(AccountManager.KEY_AUTHTOKEN);
2615 }
Fred Quintana56285a62010-12-02 14:20:51 -08002616 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2617 Log.v(TAG, getClass().getSimpleName()
2618 + " calling onResult() on response " + response);
2619 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002620 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
2621 (intent == null)) {
2622 // All AccountManager error codes are greater than 0
2623 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
2624 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2625 } else {
2626 response.onResult(result);
2627 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002628 }
Fred Quintana60307342009-03-24 22:48:12 -07002629 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002630 // if the caller is dead then there is no one to care about remote exceptions
2631 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2632 Log.v(TAG, "failure while notifying response", e);
2633 }
Fred Quintana60307342009-03-24 22:48:12 -07002634 }
2635 }
2636 }
Fred Quintana60307342009-03-24 22:48:12 -07002637
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002638 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002639 public void onRequestContinued() {
2640 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002641 }
2642
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002643 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002644 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002645 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002646 IAccountManagerResponse response = getResponseAndClose();
2647 if (response != null) {
2648 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002649 Log.v(TAG, getClass().getSimpleName()
2650 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002651 }
2652 try {
2653 response.onError(errorCode, errorMessage);
2654 } catch (RemoteException e) {
2655 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2656 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2657 }
2658 }
2659 } else {
2660 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2661 Log.v(TAG, "Session.onError: already closed");
2662 }
Fred Quintana60307342009-03-24 22:48:12 -07002663 }
2664 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002665
2666 /**
2667 * find the component name for the authenticator and initiate a bind
2668 * if no authenticator or the bind fails then return false, otherwise return true
2669 */
2670 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002671 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2672 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2673 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002674 if (authenticatorInfo == null) {
2675 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2676 Log.v(TAG, "there is no authenticator for " + authenticatorType
2677 + ", bailing out");
2678 }
2679 return false;
2680 }
2681
2682 Intent intent = new Intent();
2683 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2684 intent.setComponent(authenticatorInfo.componentName);
2685 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2686 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2687 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002688 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2689 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002690 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2691 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2692 }
2693 return false;
2694 }
2695
2696
2697 return true;
2698 }
Fred Quintana60307342009-03-24 22:48:12 -07002699 }
2700
2701 private class MessageHandler extends Handler {
2702 MessageHandler(Looper looper) {
2703 super(looper);
2704 }
Costin Manolache3348f142009-09-29 18:58:36 -07002705
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002706 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002707 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002708 switch (msg.what) {
2709 case MESSAGE_TIMED_OUT:
2710 Session session = (Session)msg.obj;
2711 session.onTimedOut();
2712 break;
2713
Amith Yamasani5be347b2013-03-31 17:44:31 -07002714 case MESSAGE_COPY_SHARED_ACCOUNT:
2715 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2716 break;
2717
Fred Quintana60307342009-03-24 22:48:12 -07002718 default:
2719 throw new IllegalStateException("unhandled message: " + msg.what);
2720 }
2721 }
2722 }
2723
Amith Yamasani04e0d262012-02-14 11:50:53 -08002724 private static String getDatabaseName(int userId) {
2725 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002726 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002727 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002728 // Migrate old file, if it exists, to the new location.
2729 // Make sure the new file doesn't already exist. A dummy file could have been
2730 // accidentally created in the old location, causing the new one to become corrupted
2731 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002732 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002733 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002734 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002735 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002736 if (!userDir.exists()) {
2737 if (!userDir.mkdirs()) {
2738 throw new IllegalStateException("User dir cannot be created: " + userDir);
2739 }
2740 }
2741 if (!oldFile.renameTo(databaseFile)) {
2742 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2743 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002744 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002745 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002746 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002747 }
2748
Amith Yamasani04e0d262012-02-14 11:50:53 -08002749 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002750
Amith Yamasani04e0d262012-02-14 11:50:53 -08002751 public DatabaseHelper(Context context, int userId) {
2752 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002753 }
2754
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002755 /**
2756 * This call needs to be made while the mCacheLock is held. The way to
2757 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2758 * @param db The database.
2759 */
Fred Quintana60307342009-03-24 22:48:12 -07002760 @Override
2761 public void onCreate(SQLiteDatabase db) {
2762 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2763 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2764 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2765 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2766 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002767 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Fred Quintana60307342009-03-24 22:48:12 -07002768 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2769
2770 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2771 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2772 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2773 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2774 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2775 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2776
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002777 createGrantsTable(db);
2778
Fred Quintana60307342009-03-24 22:48:12 -07002779 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2780 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2781 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2782 + EXTRAS_KEY + " TEXT NOT NULL, "
2783 + EXTRAS_VALUE + " TEXT, "
2784 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2785
2786 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2787 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2788 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002789
Amith Yamasani67df64b2012-12-14 12:09:36 -08002790 createSharedAccountsTable(db);
2791
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002792 createAccountsDeletionTrigger(db);
2793 }
2794
Amith Yamasani67df64b2012-12-14 12:09:36 -08002795 private void createSharedAccountsTable(SQLiteDatabase db) {
2796 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2797 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2798 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2799 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2800 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2801 }
2802
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002803 private void addOldAccountNameColumn(SQLiteDatabase db) {
2804 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
2805 }
2806
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002807 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002808 db.execSQL(""
2809 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2810 + " BEGIN"
2811 + " DELETE FROM " + TABLE_AUTHTOKENS
2812 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2813 + " DELETE FROM " + TABLE_EXTRAS
2814 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002815 + " DELETE FROM " + TABLE_GRANTS
2816 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002817 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002818 }
2819
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002820 private void createGrantsTable(SQLiteDatabase db) {
2821 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2822 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2823 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2824 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2825 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2826 + "," + GRANTS_GRANTEE_UID + "))");
2827 }
2828
Fred Quintana60307342009-03-24 22:48:12 -07002829 @Override
2830 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002831 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002832
Fred Quintanaa698f422009-04-08 19:14:54 -07002833 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002834 // no longer need to do anything since the work is done
2835 // when upgrading from version 2
2836 oldVersion++;
2837 }
2838
2839 if (oldVersion == 2) {
2840 createGrantsTable(db);
2841 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2842 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002843 oldVersion++;
2844 }
Costin Manolache3348f142009-09-29 18:58:36 -07002845
2846 if (oldVersion == 3) {
2847 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2848 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2849 oldVersion++;
2850 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002851
2852 if (oldVersion == 4) {
2853 createSharedAccountsTable(db);
2854 oldVersion++;
2855 }
2856
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002857 if (oldVersion == 5) {
2858 addOldAccountNameColumn(db);
2859 oldVersion++;
2860 }
2861
Amith Yamasani67df64b2012-12-14 12:09:36 -08002862 if (oldVersion != newVersion) {
2863 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2864 }
Fred Quintana60307342009-03-24 22:48:12 -07002865 }
2866
2867 @Override
2868 public void onOpen(SQLiteDatabase db) {
2869 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2870 }
2871 }
2872
Fred Quintana60307342009-03-24 22:48:12 -07002873 public IBinder onBind(Intent intent) {
2874 return asBinder();
2875 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002876
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002877 /**
2878 * Searches array of arguments for the specified string
2879 * @param args array of argument strings
2880 * @param value value to search for
2881 * @return true if the value is contained in the array
2882 */
2883 private static boolean scanArgs(String[] args, String value) {
2884 if (args != null) {
2885 for (String arg : args) {
2886 if (value.equals(arg)) {
2887 return true;
2888 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002889 }
2890 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002891 return false;
2892 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002893
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002894 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002895 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002896 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2897 != PackageManager.PERMISSION_GRANTED) {
2898 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2899 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2900 + " without permission " + android.Manifest.permission.DUMP);
2901 return;
2902 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002903 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002904 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002905
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002906 final List<UserInfo> users = getUserManager().getUsers();
2907 for (UserInfo user : users) {
2908 ipw.println("User " + user + ":");
2909 ipw.increaseIndent();
2910 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2911 ipw.println();
2912 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002913 }
2914 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002915
Amith Yamasani04e0d262012-02-14 11:50:53 -08002916 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2917 String[] args, boolean isCheckinRequest) {
2918 synchronized (userAccounts.cacheLock) {
2919 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002920
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002921 if (isCheckinRequest) {
2922 // This is a checkin request. *Only* upload the account types and the count of each.
2923 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2924 null, null, ACCOUNTS_TYPE, null, null);
2925 try {
2926 while (cursor.moveToNext()) {
2927 // print type,count
2928 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2929 }
2930 } finally {
2931 if (cursor != null) {
2932 cursor.close();
2933 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002934 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002935 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002936 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002937 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002938 fout.println("Accounts: " + accounts.length);
2939 for (Account account : accounts) {
2940 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002941 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002942
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002943 fout.println();
2944 synchronized (mSessions) {
2945 final long now = SystemClock.elapsedRealtime();
2946 fout.println("Active Sessions: " + mSessions.size());
2947 for (Session session : mSessions.values()) {
2948 fout.println(" " + session.toDebugString(now));
2949 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002950 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002951
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002952 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002953 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002954 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002955 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002956 }
2957
Amith Yamasani04e0d262012-02-14 11:50:53 -08002958 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002959 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002960 long identityToken = clearCallingIdentity();
2961 try {
2962 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2963 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2964 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002965
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002966 if (intent.getComponent() != null &&
2967 GrantCredentialsPermissionActivity.class.getName().equals(
2968 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002969 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002970 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002971 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002972 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002973 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2974 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002975 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002976 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07002977 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002978 contextForUser.getText(R.string.notification_title).toString();
2979 n.color = contextForUser.getResources().getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02002980 com.android.internal.R.color.system_notification_accent_color);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002981 n.setLatestEventInfo(contextForUser,
Fred Quintana33f889a2009-09-14 17:31:26 -07002982 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002983 message, PendingIntent.getActivityAsUser(
2984 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002985 null, user));
2986 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002987 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002988 } finally {
2989 restoreCallingIdentity(identityToken);
2990 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002991 }
2992
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002993 protected void installNotification(final int notificationId, final Notification n,
2994 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002995 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002996 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002997 }
2998
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002999 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003000 long identityToken = clearCallingIdentity();
3001 try {
3002 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003003 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003004 } finally {
3005 restoreCallingIdentity(identityToken);
3006 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003007 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003008
Fred Quintanab38eb142010-02-24 13:40:54 -08003009 /** Succeeds if any of the specified permissions are granted. */
3010 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003011 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08003012
3013 for (String perm : permissions) {
3014 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
3015 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003016 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08003017 }
3018 return;
3019 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003020 }
Fred Quintanab38eb142010-02-24 13:40:54 -08003021
3022 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08003023 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08003024 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003025 }
3026
Amith Yamasani67df64b2012-12-14 12:09:36 -08003027 private int handleIncomingUser(int userId) {
3028 try {
3029 return ActivityManagerNative.getDefault().handleIncomingUser(
3030 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
3031 } catch (RemoteException re) {
3032 // Shouldn't happen, local.
3033 }
3034 return userId;
3035 }
3036
Christopher Tateccbf84f2013-05-08 15:25:41 -07003037 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003038 final int callingUserId = UserHandle.getUserId(callingUid);
3039
3040 final PackageManager userPackageManager;
3041 try {
3042 userPackageManager = mContext.createPackageContextAsUser(
3043 "android", 0, new UserHandle(callingUserId)).getPackageManager();
3044 } catch (NameNotFoundException e) {
3045 return false;
3046 }
3047
3048 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07003049 for (String name : packages) {
3050 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003051 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08003052 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07003053 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07003054 return true;
3055 }
3056 } catch (PackageManager.NameNotFoundException e) {
3057 return false;
3058 }
3059 }
3060 return false;
3061 }
3062
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003063 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07003064 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07003065 final boolean fromAuthenticator = account != null
3066 && hasAuthenticatorUid(account.type, callerUid);
3067 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08003068 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003069 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3070 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08003071 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003072 + ": is authenticator? " + fromAuthenticator
3073 + ", has explicit permission? " + hasExplicitGrants);
3074 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07003075 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003076 }
3077
Fred Quintana1a231912009-10-15 11:31:30 -07003078 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003079 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003080 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003081 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003082 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003083 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08003084 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003085 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003086 }
3087 }
3088 return false;
3089 }
3090
Amith Yamasani04e0d262012-02-14 11:50:53 -08003091 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
3092 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003093 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003094 return true;
3095 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003096 UserAccounts accounts = getUserAccountsForCaller();
3097 synchronized (accounts.cacheLock) {
3098 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3099 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003100 account.name, account.type};
3101 final boolean permissionGranted =
3102 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
3103 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
3104 // TODO: Skip this check when running automated tests. Replace this
3105 // with a more general solution.
3106 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08003107 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003108 + " but ignoring since device is in test harness.");
3109 return true;
3110 }
3111 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003112 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003113 }
3114
3115 private void checkCallingUidAgainstAuthenticator(Account account) {
3116 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07003117 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003118 String msg = "caller uid " + uid + " is different than the authenticator's uid";
3119 Log.w(TAG, msg);
3120 throw new SecurityException(msg);
3121 }
3122 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3123 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
3124 }
3125 }
3126
3127 private void checkAuthenticateAccountsPermission(Account account) {
3128 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
3129 checkCallingUidAgainstAuthenticator(account);
3130 }
3131
3132 private void checkReadAccountsPermission() {
3133 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
3134 }
3135
3136 private void checkManageAccountsPermission() {
3137 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
3138 }
3139
Fred Quintanab38eb142010-02-24 13:40:54 -08003140 private void checkManageAccountsOrUseCredentialsPermissions() {
3141 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
3142 Manifest.permission.USE_CREDENTIALS);
3143 }
3144
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003145 private boolean canUserModifyAccounts(int userId) {
3146 if (getUserManager().getUserRestrictions(new UserHandle(userId))
3147 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
3148 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003149 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003150 return true;
3151 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003152
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003153 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003154 DevicePolicyManager dpm = (DevicePolicyManager) mContext
3155 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003156 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02003157 if (typesArray == null) {
3158 return true;
3159 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003160 for (String forbiddenType : typesArray) {
3161 if (forbiddenType.equals(accountType)) {
3162 return false;
3163 }
3164 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003165 return true;
3166 }
3167
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003168 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07003169 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
3170 throws RemoteException {
3171 final int callingUid = getCallingUid();
3172
Amith Yamasani27db4682013-03-30 17:07:47 -07003173 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07003174 throw new SecurityException();
3175 }
3176
3177 if (value) {
3178 grantAppPermission(account, authTokenType, uid);
3179 } else {
3180 revokeAppPermission(account, authTokenType, uid);
3181 }
3182 }
3183
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003184 /**
3185 * Allow callers with the given uid permission to get credentials for account/authTokenType.
3186 * <p>
3187 * Although this is public it can only be accessed via the AccountManagerService object
3188 * which is in the system. This means we don't need to protect it with permissions.
3189 * @hide
3190 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003191 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003192 if (account == null || authTokenType == null) {
3193 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003194 return;
3195 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003196 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003197 synchronized (accounts.cacheLock) {
3198 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003199 db.beginTransaction();
3200 try {
3201 long accountId = getAccountIdLocked(db, account);
3202 if (accountId >= 0) {
3203 ContentValues values = new ContentValues();
3204 values.put(GRANTS_ACCOUNTS_ID, accountId);
3205 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
3206 values.put(GRANTS_GRANTEE_UID, uid);
3207 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
3208 db.setTransactionSuccessful();
3209 }
3210 } finally {
3211 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003212 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003213 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3214 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003215 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003216 }
3217
3218 /**
3219 * Don't allow callers with the given uid permission to get credentials for
3220 * account/authTokenType.
3221 * <p>
3222 * Although this is public it can only be accessed via the AccountManagerService object
3223 * which is in the system. This means we don't need to protect it with permissions.
3224 * @hide
3225 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003226 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003227 if (account == null || authTokenType == null) {
3228 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003229 return;
3230 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003231 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003232 synchronized (accounts.cacheLock) {
3233 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003234 db.beginTransaction();
3235 try {
3236 long accountId = getAccountIdLocked(db, account);
3237 if (accountId >= 0) {
3238 db.delete(TABLE_GRANTS,
3239 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
3240 + GRANTS_GRANTEE_UID + "=?",
3241 new String[]{String.valueOf(accountId), authTokenType,
3242 String.valueOf(uid)});
3243 db.setTransactionSuccessful();
3244 }
3245 } finally {
3246 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003247 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003248 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3249 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003250 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003251 }
Fred Quintana56285a62010-12-02 14:20:51 -08003252
3253 static final private String stringArrayToString(String[] value) {
3254 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
3255 }
3256
Amith Yamasani04e0d262012-02-14 11:50:53 -08003257 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
3258 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003259 if (oldAccountsForType != null) {
3260 ArrayList<Account> newAccountsList = new ArrayList<Account>();
3261 for (Account curAccount : oldAccountsForType) {
3262 if (!curAccount.equals(account)) {
3263 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003264 }
3265 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003266 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003267 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003268 } else {
3269 Account[] newAccountsForType = new Account[newAccountsList.size()];
3270 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003271 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003272 }
Fred Quintana56285a62010-12-02 14:20:51 -08003273 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003274 accounts.userDataCache.remove(account);
3275 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003276 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003277 }
3278
3279 /**
3280 * This assumes that the caller has already checked that the account is not already present.
3281 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08003282 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
3283 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003284 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
3285 Account[] newAccountsForType = new Account[oldLength + 1];
3286 if (accountsForType != null) {
3287 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08003288 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003289 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003290 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08003291 }
3292
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003293 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07003294 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003295 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07003296 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003297 return unfiltered;
3298 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003299 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
3300 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003301 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003302 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003303 // otherwise return non-shared accounts only.
3304 // This might be a temporary way to specify a whitelist
3305 String whiteList = mContext.getResources().getString(
3306 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
3307 for (String packageName : packages) {
3308 if (whiteList.contains(";" + packageName + ";")) {
3309 return unfiltered;
3310 }
3311 }
3312 ArrayList<Account> allowed = new ArrayList<Account>();
3313 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
3314 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003315 String requiredAccountType = "";
3316 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07003317 // If there's an explicit callingPackage specified, check if that package
3318 // opted in to see restricted accounts.
3319 if (callingPackage != null) {
3320 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003321 if (pi != null && pi.restrictedAccountType != null) {
3322 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07003323 }
3324 } else {
3325 // Otherwise check if the callingUid has a package that has opted in
3326 for (String packageName : packages) {
3327 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
3328 if (pi != null && pi.restrictedAccountType != null) {
3329 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07003330 break;
3331 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003332 }
3333 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003334 } catch (NameNotFoundException nnfe) {
3335 }
3336 for (Account account : unfiltered) {
3337 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003338 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003339 } else {
3340 boolean found = false;
3341 for (Account shared : sharedAccounts) {
3342 if (shared.equals(account)) {
3343 found = true;
3344 break;
3345 }
3346 }
3347 if (!found) {
3348 allowed.add(account);
3349 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003350 }
3351 }
3352 Account[] filtered = new Account[allowed.size()];
3353 allowed.toArray(filtered);
3354 return filtered;
3355 } else {
3356 return unfiltered;
3357 }
3358 }
3359
Amith Yamasani27db4682013-03-30 17:07:47 -07003360 /*
3361 * packageName can be null. If not null, it should be used to filter out restricted accounts
3362 * that the package is not allowed to access.
3363 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003364 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07003365 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003366 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003367 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003368 if (accounts == null) {
3369 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08003370 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003371 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07003372 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003373 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003374 } else {
3375 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003376 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003377 totalLength += accounts.length;
3378 }
3379 if (totalLength == 0) {
3380 return EMPTY_ACCOUNT_ARRAY;
3381 }
3382 Account[] accounts = new Account[totalLength];
3383 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003384 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003385 System.arraycopy(accountsOfType, 0, accounts, totalLength,
3386 accountsOfType.length);
3387 totalLength += accountsOfType.length;
3388 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003389 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003390 }
3391 }
3392
Amith Yamasani04e0d262012-02-14 11:50:53 -08003393 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3394 Account account, String key, String value) {
3395 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003396 if (userDataForAccount == null) {
3397 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003398 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003399 }
3400 if (value == null) {
3401 userDataForAccount.remove(key);
3402 } else {
3403 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003404 }
3405 }
3406
Amith Yamasani04e0d262012-02-14 11:50:53 -08003407 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3408 Account account, String key, String value) {
3409 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003410 if (authTokensForAccount == null) {
3411 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003412 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003413 }
3414 if (value == null) {
3415 authTokensForAccount.remove(key);
3416 } else {
3417 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003418 }
3419 }
3420
Amith Yamasani04e0d262012-02-14 11:50:53 -08003421 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
3422 String authTokenType) {
3423 synchronized (accounts.cacheLock) {
3424 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003425 if (authTokensForAccount == null) {
3426 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003427 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003428 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003429 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003430 }
3431 return authTokensForAccount.get(authTokenType);
3432 }
3433 }
3434
Amith Yamasani04e0d262012-02-14 11:50:53 -08003435 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
3436 synchronized (accounts.cacheLock) {
3437 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003438 if (userDataForAccount == null) {
3439 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003440 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003441 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003442 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003443 }
3444 return userDataForAccount.get(key);
3445 }
3446 }
3447
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003448 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3449 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003450 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003451 Cursor cursor = db.query(TABLE_EXTRAS,
3452 COLUMNS_EXTRAS_KEY_AND_VALUE,
3453 SELECTION_USERDATA_BY_ACCOUNT,
3454 new String[]{account.name, account.type},
3455 null, null, null);
3456 try {
3457 while (cursor.moveToNext()) {
3458 final String tmpkey = cursor.getString(0);
3459 final String value = cursor.getString(1);
3460 userDataForAccount.put(tmpkey, value);
3461 }
3462 } finally {
3463 cursor.close();
3464 }
3465 return userDataForAccount;
3466 }
3467
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003468 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3469 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003470 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003471 Cursor cursor = db.query(TABLE_AUTHTOKENS,
3472 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3473 SELECTION_AUTHTOKENS_BY_ACCOUNT,
3474 new String[]{account.name, account.type},
3475 null, null, null);
3476 try {
3477 while (cursor.moveToNext()) {
3478 final String type = cursor.getString(0);
3479 final String authToken = cursor.getString(1);
3480 authTokensForAccount.put(type, authToken);
3481 }
3482 } finally {
3483 cursor.close();
3484 }
3485 return authTokensForAccount;
3486 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003487
3488 private Context getContextForUser(UserHandle user) {
3489 try {
3490 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
3491 } catch (NameNotFoundException e) {
3492 // Default to mContext, not finding the package system is running as is unlikely.
3493 return mContext;
3494 }
3495 }
Fred Quintana60307342009-03-24 22:48:12 -07003496}