blob: 2a66baf45690e040a98af1031a10f10b40544302 [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) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800268 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800269 }
270 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800271
Amith Yamasani13593602012-03-22 16:16:17 -0700272 IntentFilter userFilter = new IntentFilter();
273 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800274 userFilter.addAction(Intent.ACTION_USER_STARTED);
275 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700276 @Override
277 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800278 String action = intent.getAction();
279 if (Intent.ACTION_USER_REMOVED.equals(action)) {
280 onUserRemoved(intent);
281 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
282 onUserStarted(intent);
283 }
Amith Yamasani13593602012-03-22 16:16:17 -0700284 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800285 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800286 }
287
Dianne Hackborn164371f2013-10-01 19:10:13 -0700288 @Override
289 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
290 throws RemoteException {
291 try {
292 return super.onTransact(code, data, reply, flags);
293 } catch (RuntimeException e) {
294 // The account manager only throws security exceptions, so let's
295 // log all others.
296 if (!(e instanceof SecurityException)) {
297 Slog.wtf(TAG, "Account Manager Crash", e);
298 }
299 throw e;
300 }
301 }
302
Kenny Root26ff6622012-07-30 12:58:03 -0700303 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700304 }
305
Amith Yamasani258848d2012-08-10 17:06:33 -0700306 private UserManager getUserManager() {
307 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700308 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700309 }
310 return mUserManager;
311 }
312
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700313 /* Caller should lock mUsers */
314 private UserAccounts initUserLocked(int userId) {
315 UserAccounts accounts = mUsers.get(userId);
316 if (accounts == null) {
317 accounts = new UserAccounts(mContext, userId);
318 mUsers.append(userId, accounts);
319 purgeOldGrants(accounts);
320 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800321 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700322 return accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800323 }
324
325 private void purgeOldGrantsAll() {
326 synchronized (mUsers) {
327 for (int i = 0; i < mUsers.size(); i++) {
328 purgeOldGrants(mUsers.valueAt(i));
329 }
330 }
331 }
332
333 private void purgeOldGrants(UserAccounts accounts) {
334 synchronized (accounts.cacheLock) {
335 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800336 final Cursor cursor = db.query(TABLE_GRANTS,
337 new String[]{GRANTS_GRANTEE_UID},
338 null, null, GRANTS_GRANTEE_UID, null, null);
339 try {
340 while (cursor.moveToNext()) {
341 final int uid = cursor.getInt(0);
342 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
343 if (packageExists) {
344 continue;
345 }
346 Log.d(TAG, "deleting grants for UID " + uid
347 + " because its package is no longer installed");
348 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
349 new String[]{Integer.toString(uid)});
350 }
351 } finally {
352 cursor.close();
353 }
354 }
355 }
356
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700357 /**
358 * Validate internal set of accounts against installed authenticators for
359 * given user. Clears cached authenticators before validating.
360 */
361 public void validateAccounts(int userId) {
362 final UserAccounts accounts = getUserAccounts(userId);
363
364 // Invalidate user-specific cache to make sure we catch any
365 // removed authenticators.
366 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
367 }
368
369 /**
370 * Validate internal set of accounts against installed authenticators for
371 * given user. Clear cached authenticators before validating when requested.
372 */
373 private void validateAccountsInternal(
374 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
375 if (invalidateAuthenticatorCache) {
376 mAuthenticatorCache.invalidateCache(accounts.userId);
377 }
378
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700379 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
380 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
381 mAuthenticatorCache.getAllServices(accounts.userId)) {
382 knownAuth.add(service.type);
383 }
384
Amith Yamasani04e0d262012-02-14 11:50:53 -0800385 synchronized (accounts.cacheLock) {
386 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800387 boolean accountDeleted = false;
388 Cursor cursor = db.query(TABLE_ACCOUNTS,
389 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
390 null, null, null, null, null);
391 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800392 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800393 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700394 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800395 while (cursor.moveToNext()) {
396 final long accountId = cursor.getLong(0);
397 final String accountType = cursor.getString(1);
398 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700399
400 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700401 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800402 + accountType + " no longer has a registered authenticator");
403 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
404 accountDeleted = true;
405 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800406 accounts.userDataCache.remove(account);
407 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800408 } else {
409 ArrayList<String> accountNames = accountNamesByType.get(accountType);
410 if (accountNames == null) {
411 accountNames = new ArrayList<String>();
412 accountNamesByType.put(accountType, accountNames);
413 }
414 accountNames.add(accountName);
415 }
416 }
Andy McFadden2f362292012-01-20 14:43:38 -0800417 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800418 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800419 final String accountType = cur.getKey();
420 final ArrayList<String> accountNames = cur.getValue();
421 final Account[] accountsForType = new Account[accountNames.size()];
422 int i = 0;
423 for (String accountName : accountNames) {
424 accountsForType[i] = new Account(accountName, accountType);
425 ++i;
426 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800427 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800428 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800429 } finally {
430 cursor.close();
431 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800432 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800433 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800434 }
435 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700436 }
437
Amith Yamasani04e0d262012-02-14 11:50:53 -0800438 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700439 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800440 }
441
442 protected UserAccounts getUserAccounts(int userId) {
443 synchronized (mUsers) {
444 UserAccounts accounts = mUsers.get(userId);
445 if (accounts == null) {
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700446 accounts = initUserLocked(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800447 mUsers.append(userId, accounts);
448 }
449 return accounts;
450 }
451 }
452
Amith Yamasani13593602012-03-22 16:16:17 -0700453 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700454 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700455 if (userId < 1) return;
456
457 UserAccounts accounts;
458 synchronized (mUsers) {
459 accounts = mUsers.get(userId);
460 mUsers.remove(userId);
461 }
462 if (accounts == null) {
463 File dbFile = new File(getDatabaseName(userId));
464 dbFile.delete();
465 return;
466 }
467
468 synchronized (accounts.cacheLock) {
469 accounts.openHelper.close();
470 File dbFile = new File(getDatabaseName(userId));
471 dbFile.delete();
472 }
473 }
474
Amith Yamasani67df64b2012-12-14 12:09:36 -0800475 private void onUserStarted(Intent intent) {
476 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
477 if (userId < 1) return;
478
479 // Check if there's a shared account that needs to be created as an account
480 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
481 if (sharedAccounts == null || sharedAccounts.length == 0) return;
482 Account[] accounts = getAccountsAsUser(null, userId);
483 for (Account sa : sharedAccounts) {
484 if (ArrayUtils.contains(accounts, sa)) continue;
485 // Account doesn't exist. Copy it now.
486 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
487 }
488 }
489
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700490 @Override
491 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700492 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700493 }
494
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800495 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700496 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800497 if (Log.isLoggable(TAG, Log.VERBOSE)) {
498 Log.v(TAG, "getPassword: " + account
499 + ", caller's uid " + Binder.getCallingUid()
500 + ", pid " + Binder.getCallingPid());
501 }
Fred Quintana382601f2010-03-25 12:25:10 -0700502 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700503 checkAuthenticateAccountsPermission(account);
504
Amith Yamasani04e0d262012-02-14 11:50:53 -0800505 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700506 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700507 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800508 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700509 } finally {
510 restoreCallingIdentity(identityToken);
511 }
512 }
513
Amith Yamasani04e0d262012-02-14 11:50:53 -0800514 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700515 if (account == null) {
516 return null;
517 }
518
Amith Yamasani04e0d262012-02-14 11:50:53 -0800519 synchronized (accounts.cacheLock) {
520 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800521 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
522 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
523 new String[]{account.name, account.type}, null, null, null);
524 try {
525 if (cursor.moveToNext()) {
526 return cursor.getString(0);
527 }
528 return null;
529 } finally {
530 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700531 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700532 }
533 }
534
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800535 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700536 public String getPreviousName(Account account) {
537 if (Log.isLoggable(TAG, Log.VERBOSE)) {
538 Log.v(TAG, "getPreviousName: " + account
539 + ", caller's uid " + Binder.getCallingUid()
540 + ", pid " + Binder.getCallingPid());
541 }
542 if (account == null) throw new IllegalArgumentException("account is null");
543 UserAccounts accounts = getUserAccountsForCaller();
544 long identityToken = clearCallingIdentity();
545 try {
546 return readPreviousNameInternal(accounts, account);
547 } finally {
548 restoreCallingIdentity(identityToken);
549 }
550 }
551
552 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
553 if (account == null) {
554 return null;
555 }
556 synchronized (accounts.cacheLock) {
557 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
558 if (previousNameRef == null) {
559 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
560 Cursor cursor = db.query(
561 TABLE_ACCOUNTS,
562 new String[]{ ACCOUNTS_PREVIOUS_NAME },
563 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
564 new String[] { account.name, account.type },
565 null,
566 null,
567 null);
568 try {
569 if (cursor.moveToNext()) {
570 String previousName = cursor.getString(0);
571 previousNameRef = new AtomicReference<String>(previousName);
572 accounts.previousNameCache.put(account, previousNameRef);
573 return previousName;
574 } else {
575 return null;
576 }
577 } finally {
578 cursor.close();
579 }
580 } else {
581 return previousNameRef.get();
582 }
583 }
584 }
585
586 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700587 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800588 if (Log.isLoggable(TAG, Log.VERBOSE)) {
589 Log.v(TAG, "getUserData: " + account
590 + ", key " + key
591 + ", caller's uid " + Binder.getCallingUid()
592 + ", pid " + Binder.getCallingPid());
593 }
Fred Quintana382601f2010-03-25 12:25:10 -0700594 if (account == null) throw new IllegalArgumentException("account is null");
595 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700596 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800597 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700598 long identityToken = clearCallingIdentity();
599 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800600 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700601 } finally {
602 restoreCallingIdentity(identityToken);
603 }
604 }
605
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800606 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100607 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800608 if (Log.isLoggable(TAG, Log.VERBOSE)) {
609 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100610 + "for user id " + userId
Fred Quintana56285a62010-12-02 14:20:51 -0800611 + "caller's uid " + Binder.getCallingUid()
612 + ", pid " + Binder.getCallingPid());
613 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100614 // Only allow the system process to read accounts of other users
615 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
616 + " trying get authenticator types for " + userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700617 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700618 try {
Fred Quintana97889762009-06-15 12:29:24 -0700619 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700620 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700621 AuthenticatorDescription[] types =
622 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700623 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700624 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700625 : authenticatorCollection) {
626 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700627 i++;
628 }
629 return types;
630 } finally {
631 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700632 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700633 }
634
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100635 private void enforceCrossUserPermission(int userId, String errorMessage) {
636 if (userId != UserHandle.getCallingUserId()
637 && Binder.getCallingUid() != Process.myUid()
638 && mContext.checkCallingOrSelfPermission(
639 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
640 != PackageManager.PERMISSION_GRANTED) {
641 throw new SecurityException(errorMessage);
642 }
643 }
644
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700645 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700646 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800647 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700648 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800649 + ", caller's uid " + Binder.getCallingUid()
650 + ", pid " + Binder.getCallingPid());
651 }
Fred Quintana382601f2010-03-25 12:25:10 -0700652 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700653 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700654 /*
655 * Child users are not allowed to add accounts. Only the accounts that are
656 * shared by the parent profile can be added to child profile.
657 *
658 * TODO: Only allow accounts that were shared to be added by
659 * a limited user.
660 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700661
Amith Yamasani04e0d262012-02-14 11:50:53 -0800662 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700663 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700664 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700665 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800666 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700667 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700668 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700669 }
670 }
671
Amith Yamasani67df64b2012-12-14 12:09:36 -0800672 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
673 final UserAccounts fromAccounts = getUserAccounts(userFrom);
674 final UserAccounts toAccounts = getUserAccounts(userTo);
675 if (fromAccounts == null || toAccounts == null) {
676 return false;
677 }
678
679 long identityToken = clearCallingIdentity();
680 try {
681 new Session(fromAccounts, null, account.type, false,
682 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700683 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800684 protected String toDebugString(long now) {
685 return super.toDebugString(now) + ", getAccountCredentialsForClone"
686 + ", " + account.type;
687 }
688
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700689 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800690 public void run() throws RemoteException {
691 mAuthenticator.getAccountCredentialsForCloning(this, account);
692 }
693
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700694 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800695 public void onResult(Bundle result) {
696 if (result != null) {
697 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
698 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800699 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800700 }
701 return;
702 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800703 super.onResult(result);
704 }
705 }
706 }.bind();
707 } finally {
708 restoreCallingIdentity(identityToken);
709 }
710 return true;
711 }
712
Amith Yamasani67df64b2012-12-14 12:09:36 -0800713 void completeCloningAccount(final Bundle result, final Account account,
714 final UserAccounts targetUser) {
715 long id = clearCallingIdentity();
716 try {
717 new Session(targetUser, null, account.type, false,
718 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700719 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800720 protected String toDebugString(long now) {
721 return super.toDebugString(now) + ", getAccountCredentialsForClone"
722 + ", " + account.type;
723 }
724
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700725 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800726 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700727 // Confirm that the owner's account still exists before this step.
728 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
729 synchronized (owner.cacheLock) {
730 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
731 for (Account acc : ownerAccounts) {
732 if (acc.equals(account)) {
733 mAuthenticator.addAccountFromCredentials(this, account, result);
734 break;
735 }
736 }
737 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800738 }
739
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700740 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800741 public void onResult(Bundle result) {
742 if (result != null) {
743 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
744 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800745 } else {
746 // TODO: Show error notification
747 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800748 }
749 return;
750 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800751 super.onResult(result);
752 }
753 }
754
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700755 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800756 public void onError(int errorCode, String errorMessage) {
757 super.onError(errorCode, errorMessage);
758 // TODO: Show error notification to user
759 // TODO: Should we remove the shadow account so that it doesn't keep trying?
760 }
761
762 }.bind();
763 } finally {
764 restoreCallingIdentity(id);
765 }
766 }
767
Amith Yamasani04e0d262012-02-14 11:50:53 -0800768 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800769 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700770 if (account == null) {
771 return false;
772 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800773 synchronized (accounts.cacheLock) {
774 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800775 db.beginTransaction();
776 try {
777 long numMatches = DatabaseUtils.longForQuery(db,
778 "select count(*) from " + TABLE_ACCOUNTS
779 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
780 new String[]{account.name, account.type});
781 if (numMatches > 0) {
782 Log.w(TAG, "insertAccountIntoDatabase: " + account
783 + ", skipping since the account already exists");
784 return false;
785 }
786 ContentValues values = new ContentValues();
787 values.put(ACCOUNTS_NAME, account.name);
788 values.put(ACCOUNTS_TYPE, account.type);
789 values.put(ACCOUNTS_PASSWORD, password);
790 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
791 if (accountId < 0) {
792 Log.w(TAG, "insertAccountIntoDatabase: " + account
793 + ", skipping the DB insert failed");
794 return false;
795 }
796 if (extras != null) {
797 for (String key : extras.keySet()) {
798 final String value = extras.getString(key);
799 if (insertExtraLocked(db, accountId, key, value) < 0) {
800 Log.w(TAG, "insertAccountIntoDatabase: " + account
801 + ", skipping since insertExtra failed for key " + key);
802 return false;
803 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700804 }
805 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800806 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800807 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800808 } finally {
809 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700810 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800811 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700812 }
813 if (accounts.userId == UserHandle.USER_OWNER) {
814 addAccountToLimitedUsers(account);
815 }
816 return true;
817 }
818
819 /**
820 * Adds the account to all limited users as shared accounts. If the user is currently
821 * running, then clone the account too.
822 * @param account the account to share with limited users
823 */
824 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700825 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700826 for (UserInfo user : users) {
827 if (user.isRestricted()) {
828 addSharedAccountAsUser(account, user.id);
829 try {
830 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
831 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
832 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
833 account));
834 }
835 } catch (RemoteException re) {
836 // Shouldn't happen
837 }
838 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700839 }
840 }
841
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800842 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700843 ContentValues values = new ContentValues();
844 values.put(EXTRAS_KEY, key);
845 values.put(EXTRAS_ACCOUNTS_ID, accountId);
846 values.put(EXTRAS_VALUE, value);
847 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
848 }
849
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800850 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -0800851 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800852 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800853 if (Log.isLoggable(TAG, Log.VERBOSE)) {
854 Log.v(TAG, "hasFeatures: " + account
855 + ", response " + response
856 + ", features " + stringArrayToString(features)
857 + ", caller's uid " + Binder.getCallingUid()
858 + ", pid " + Binder.getCallingPid());
859 }
Fred Quintana382601f2010-03-25 12:25:10 -0700860 if (response == null) throw new IllegalArgumentException("response is null");
861 if (account == null) throw new IllegalArgumentException("account is null");
862 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800863 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800864 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800865 long identityToken = clearCallingIdentity();
866 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800867 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800868 } finally {
869 restoreCallingIdentity(identityToken);
870 }
871 }
872
873 private class TestFeaturesSession extends Session {
874 private final String[] mFeatures;
875 private final Account mAccount;
876
Amith Yamasani04e0d262012-02-14 11:50:53 -0800877 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800878 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800879 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800880 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800881 mFeatures = features;
882 mAccount = account;
883 }
884
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700885 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800886 public void run() throws RemoteException {
887 try {
888 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
889 } catch (RemoteException e) {
890 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
891 }
892 }
893
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700894 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800895 public void onResult(Bundle result) {
896 IAccountManagerResponse response = getResponseAndClose();
897 if (response != null) {
898 try {
899 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700900 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800901 return;
902 }
Fred Quintana56285a62010-12-02 14:20:51 -0800903 if (Log.isLoggable(TAG, Log.VERBOSE)) {
904 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
905 + response);
906 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800907 final Bundle newResult = new Bundle();
908 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
909 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
910 response.onResult(newResult);
911 } catch (RemoteException e) {
912 // if the caller is dead then there is no one to care about remote exceptions
913 if (Log.isLoggable(TAG, Log.VERBOSE)) {
914 Log.v(TAG, "failure while notifying response", e);
915 }
916 }
917 }
918 }
919
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700920 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800921 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800922 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800923 + ", " + mAccount
924 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
925 }
926 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800927
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800928 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700929 public void renameAccount(
930 IAccountManagerResponse response, Account accountToRename, String newName) {
931 if (Log.isLoggable(TAG, Log.VERBOSE)) {
932 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
933 + ", caller's uid " + Binder.getCallingUid()
934 + ", pid " + Binder.getCallingPid());
935 }
936 if (accountToRename == null) throw new IllegalArgumentException("account is null");
937 checkAuthenticateAccountsPermission(accountToRename);
938 UserAccounts accounts = getUserAccountsForCaller();
939 long identityToken = clearCallingIdentity();
940 try {
941 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
942 Bundle result = new Bundle();
943 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
944 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
945 try {
946 response.onResult(result);
947 } catch (RemoteException e) {
948 Log.w(TAG, e.getMessage());
949 }
950 } finally {
951 restoreCallingIdentity(identityToken);
952 }
953 }
954
955 private Account renameAccountInternal(
956 UserAccounts accounts, Account accountToRename, String newName) {
957 Account resultAccount = null;
958 /*
959 * Cancel existing notifications. Let authenticators
960 * re-post notifications as required. But we don't know if
961 * the authenticators have bound their notifications to
962 * now stale account name data.
963 *
964 * With a rename api, we might not need to do this anymore but it
965 * shouldn't hurt.
966 */
967 cancelNotification(
968 getSigninRequiredNotificationId(accounts, accountToRename),
969 new UserHandle(accounts.userId));
970 synchronized(accounts.credentialsPermissionNotificationIds) {
971 for (Pair<Pair<Account, String>, Integer> pair:
972 accounts.credentialsPermissionNotificationIds.keySet()) {
973 if (accountToRename.equals(pair.first.first)) {
974 int id = accounts.credentialsPermissionNotificationIds.get(pair);
975 cancelNotification(id, new UserHandle(accounts.userId));
976 }
977 }
978 }
979 synchronized (accounts.cacheLock) {
980 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
981 db.beginTransaction();
982 boolean isSuccessful = false;
983 Account renamedAccount = new Account(newName, accountToRename.type);
984 try {
985 final ContentValues values = new ContentValues();
986 values.put(ACCOUNTS_NAME, newName);
987 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
988 final long accountId = getAccountIdLocked(db, accountToRename);
989 if (accountId >= 0) {
990 final String[] argsAccountId = { String.valueOf(accountId) };
991 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
992 db.setTransactionSuccessful();
993 isSuccessful = true;
994 }
995 } finally {
996 db.endTransaction();
997 if (isSuccessful) {
998 /*
999 * Database transaction was successful. Clean up cached
1000 * data associated with the account in the user profile.
1001 */
1002 insertAccountIntoCacheLocked(accounts, renamedAccount);
1003 /*
1004 * Extract the data and token caches before removing the
1005 * old account to preserve the user data associated with
1006 * the account.
1007 */
1008 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1009 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1010 removeAccountFromCacheLocked(accounts, accountToRename);
1011 /*
1012 * Update the cached data associated with the renamed
1013 * account.
1014 */
1015 accounts.userDataCache.put(renamedAccount, tmpData);
1016 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1017 accounts.previousNameCache.put(
1018 renamedAccount,
1019 new AtomicReference<String>(accountToRename.name));
1020 resultAccount = renamedAccount;
1021
1022 if (accounts.userId == UserHandle.USER_OWNER) {
1023 /*
1024 * Owner's account was renamed, rename the account for
1025 * those users with which the account was shared.
1026 */
1027 List<UserInfo> users = mUserManager.getUsers(true);
1028 for (UserInfo user : users) {
1029 if (!user.isPrimary() && user.isRestricted()) {
1030 renameSharedAccountAsUser(accountToRename, newName, user.id);
1031 }
1032 }
1033 }
1034 sendAccountsChangedBroadcast(accounts.userId);
1035 }
1036 }
1037 }
1038 return resultAccount;
1039 }
1040
1041 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001042 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001043 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1044 Log.v(TAG, "removeAccount: " + account
1045 + ", response " + response
1046 + ", caller's uid " + Binder.getCallingUid()
1047 + ", pid " + Binder.getCallingPid());
1048 }
Fred Quintana382601f2010-03-25 12:25:10 -07001049 if (response == null) throw new IllegalArgumentException("response is null");
1050 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001051 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001052 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001053 UserAccounts accounts = getUserAccountsForCaller();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001054 int userId = Binder.getCallingUserHandle().getIdentifier();
1055 if (!canUserModifyAccounts(userId)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001056 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001057 // TODO: This should be ERROR_CODE_USER_RESTRICTED instead. See http://b/16322768
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001058 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
1059 "User cannot modify accounts");
1060 } catch (RemoteException re) {
1061 }
Amith Yamasani5934dbc2014-02-20 15:23:36 -08001062 return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001063 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001064 if (!canUserModifyAccountsForType(userId, account.type)) {
1065 try {
1066 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1067 "User cannot modify accounts of this type (policy).");
1068 } catch (RemoteException re) {
1069 }
1070 return;
1071 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001072
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001073 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001074
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001075 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001076 synchronized (accounts.credentialsPermissionNotificationIds) {
1077 for (Pair<Pair<Account, String>, Integer> pair:
1078 accounts.credentialsPermissionNotificationIds.keySet()) {
1079 if (account.equals(pair.first.first)) {
1080 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1081 cancelNotification(id, user);
1082 }
1083 }
1084 }
1085
1086 try {
1087 new RemoveAccountSession(accounts, response, account).bind();
1088 } finally {
1089 restoreCallingIdentity(identityToken);
1090 }
1091 }
1092
1093 @Override
1094 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
1095 int userId) {
1096 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1097 Log.v(TAG, "removeAccount: " + account
1098 + ", response " + response
1099 + ", caller's uid " + Binder.getCallingUid()
1100 + ", pid " + Binder.getCallingPid()
1101 + ", for user id " + userId);
1102 }
1103 if (response == null) throw new IllegalArgumentException("response is null");
1104 if (account == null) throw new IllegalArgumentException("account is null");
1105
1106 // Only allow the system process to modify accounts of other users
1107 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1108 + " trying to remove account for " + userId);
1109 checkManageAccountsPermission();
1110
1111 UserAccounts accounts = getUserAccounts(userId);
1112 if (!canUserModifyAccounts(userId)) {
1113 try {
1114 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1115 "User cannot modify accounts");
1116 } catch (RemoteException re) {
1117 }
1118 return;
1119 }
1120 if (!canUserModifyAccountsForType(userId, account.type)) {
1121 try {
1122 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1123 "User cannot modify accounts of this type (policy).");
1124 } catch (RemoteException re) {
1125 }
1126 return;
1127 }
1128
1129 UserHandle user = new UserHandle(userId);
1130 long identityToken = clearCallingIdentity();
1131
1132 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001133 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001134 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001135 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001136 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001137 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001138 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001139 }
1140 }
1141 }
1142
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001143 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001144 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001145 } finally {
1146 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001147 }
Fred Quintana60307342009-03-24 22:48:12 -07001148 }
1149
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001150 private class RemoveAccountSession extends Session {
1151 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001152 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
1153 Account account) {
1154 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001155 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001156 mAccount = account;
1157 }
1158
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001159 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001160 protected String toDebugString(long now) {
1161 return super.toDebugString(now) + ", removeAccount"
1162 + ", account " + mAccount;
1163 }
1164
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001165 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001166 public void run() throws RemoteException {
1167 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1168 }
1169
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001170 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001171 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001172 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1173 && !result.containsKey(AccountManager.KEY_INTENT)) {
1174 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001175 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001176 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001177 }
1178 IAccountManagerResponse response = getResponseAndClose();
1179 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001180 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1181 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1182 + response);
1183 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001184 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001185 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001186 try {
1187 response.onResult(result2);
1188 } catch (RemoteException e) {
1189 // ignore
1190 }
1191 }
1192 }
1193 super.onResult(result);
1194 }
1195 }
1196
Amith Yamasani04e0d262012-02-14 11:50:53 -08001197 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001198 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001199 removeAccountInternal(getUserAccountsForCaller(), account);
1200 }
1201
1202 private void removeAccountInternal(UserAccounts accounts, Account account) {
1203 synchronized (accounts.cacheLock) {
1204 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001205 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1206 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001207 removeAccountFromCacheLocked(accounts, account);
1208 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001209 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001210 if (accounts.userId == UserHandle.USER_OWNER) {
1211 // Owner's account was removed, remove from any users that are sharing
1212 // this account.
1213 long id = Binder.clearCallingIdentity();
1214 try {
1215 List<UserInfo> users = mUserManager.getUsers(true);
1216 for (UserInfo user : users) {
1217 if (!user.isPrimary() && user.isRestricted()) {
1218 removeSharedAccountAsUser(account, user.id);
1219 }
1220 }
1221 } finally {
1222 Binder.restoreCallingIdentity(id);
1223 }
1224 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001225 }
1226
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001227 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001228 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001229 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1230 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
1231 + ", caller's uid " + Binder.getCallingUid()
1232 + ", pid " + Binder.getCallingPid());
1233 }
Fred Quintana382601f2010-03-25 12:25:10 -07001234 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1235 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -08001236 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001237 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001238 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001239 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001240 synchronized (accounts.cacheLock) {
1241 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001242 db.beginTransaction();
1243 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001244 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001245 db.setTransactionSuccessful();
1246 } finally {
1247 db.endTransaction();
1248 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001249 }
Fred Quintana60307342009-03-24 22:48:12 -07001250 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001251 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001252 }
1253 }
1254
Amith Yamasani04e0d262012-02-14 11:50:53 -08001255 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1256 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001257 if (authToken == null || accountType == null) {
1258 return;
1259 }
Fred Quintana33269202009-04-20 16:05:10 -07001260 Cursor cursor = db.rawQuery(
1261 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1262 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1263 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1264 + " FROM " + TABLE_ACCOUNTS
1265 + " JOIN " + TABLE_AUTHTOKENS
1266 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1267 + " = " + AUTHTOKENS_ACCOUNTS_ID
1268 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1269 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1270 new String[]{authToken, accountType});
1271 try {
1272 while (cursor.moveToNext()) {
1273 long authTokenId = cursor.getLong(0);
1274 String accountName = cursor.getString(1);
1275 String authTokenType = cursor.getString(2);
1276 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001277 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001278 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -07001279 }
Fred Quintana33269202009-04-20 16:05:10 -07001280 } finally {
1281 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001282 }
1283 }
1284
Amith Yamasani04e0d262012-02-14 11:50:53 -08001285 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1286 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001287 if (account == null || type == null) {
1288 return false;
1289 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001290 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1291 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001292 synchronized (accounts.cacheLock) {
1293 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001294 db.beginTransaction();
1295 try {
1296 long accountId = getAccountIdLocked(db, account);
1297 if (accountId < 0) {
1298 return false;
1299 }
1300 db.delete(TABLE_AUTHTOKENS,
1301 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1302 new String[]{type});
1303 ContentValues values = new ContentValues();
1304 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1305 values.put(AUTHTOKENS_TYPE, type);
1306 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1307 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1308 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001309 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001310 return true;
1311 }
Fred Quintana33269202009-04-20 16:05:10 -07001312 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001313 } finally {
1314 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001315 }
Fred Quintana60307342009-03-24 22:48:12 -07001316 }
1317 }
1318
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001319 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001320 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001321 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1322 Log.v(TAG, "peekAuthToken: " + account
1323 + ", authTokenType " + authTokenType
1324 + ", caller's uid " + Binder.getCallingUid()
1325 + ", pid " + Binder.getCallingPid());
1326 }
Fred Quintana382601f2010-03-25 12:25:10 -07001327 if (account == null) throw new IllegalArgumentException("account is null");
1328 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001329 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001330 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001331 long identityToken = clearCallingIdentity();
1332 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001333 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001334 } finally {
1335 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001336 }
Fred Quintana60307342009-03-24 22:48:12 -07001337 }
1338
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001339 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001340 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001341 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1342 Log.v(TAG, "setAuthToken: " + account
1343 + ", authTokenType " + authTokenType
1344 + ", caller's uid " + Binder.getCallingUid()
1345 + ", pid " + Binder.getCallingPid());
1346 }
Fred Quintana382601f2010-03-25 12:25:10 -07001347 if (account == null) throw new IllegalArgumentException("account is null");
1348 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001349 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001350 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001351 long identityToken = clearCallingIdentity();
1352 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001353 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001354 } finally {
1355 restoreCallingIdentity(identityToken);
1356 }
Fred Quintana60307342009-03-24 22:48:12 -07001357 }
1358
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001359 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001360 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001361 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1362 Log.v(TAG, "setAuthToken: " + account
1363 + ", caller's uid " + Binder.getCallingUid()
1364 + ", pid " + Binder.getCallingPid());
1365 }
Fred Quintana382601f2010-03-25 12:25:10 -07001366 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001367 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001368 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001369 long identityToken = clearCallingIdentity();
1370 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001371 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001372 } finally {
1373 restoreCallingIdentity(identityToken);
1374 }
Fred Quintana60307342009-03-24 22:48:12 -07001375 }
1376
Amith Yamasani04e0d262012-02-14 11:50:53 -08001377 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001378 if (account == null) {
1379 return;
1380 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001381 synchronized (accounts.cacheLock) {
1382 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001383 db.beginTransaction();
1384 try {
1385 final ContentValues values = new ContentValues();
1386 values.put(ACCOUNTS_PASSWORD, password);
1387 final long accountId = getAccountIdLocked(db, account);
1388 if (accountId >= 0) {
1389 final String[] argsAccountId = {String.valueOf(accountId)};
1390 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1391 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001392 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001393 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001394 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001395 } finally {
1396 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001397 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001398 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001399 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001400 }
1401
Amith Yamasani04e0d262012-02-14 11:50:53 -08001402 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001403 Log.i(TAG, "the accounts changed, sending broadcast of "
1404 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001405 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001406 }
1407
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001408 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001409 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001410 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1411 Log.v(TAG, "clearPassword: " + account
1412 + ", caller's uid " + Binder.getCallingUid()
1413 + ", pid " + Binder.getCallingPid());
1414 }
Fred Quintana382601f2010-03-25 12:25:10 -07001415 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001416 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001417 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001418 long identityToken = clearCallingIdentity();
1419 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001420 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001421 } finally {
1422 restoreCallingIdentity(identityToken);
1423 }
Fred Quintana60307342009-03-24 22:48:12 -07001424 }
1425
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001426 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001427 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001428 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1429 Log.v(TAG, "setUserData: " + account
1430 + ", key " + key
1431 + ", caller's uid " + Binder.getCallingUid()
1432 + ", pid " + Binder.getCallingPid());
1433 }
Fred Quintana382601f2010-03-25 12:25:10 -07001434 if (key == null) throw new IllegalArgumentException("key is null");
1435 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001436 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001437 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001438 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001439 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001440 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001441 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001442 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001443 }
1444 }
1445
Amith Yamasani04e0d262012-02-14 11:50:53 -08001446 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1447 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001448 if (account == null || key == null) {
1449 return;
1450 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001451 synchronized (accounts.cacheLock) {
1452 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001453 db.beginTransaction();
1454 try {
1455 long accountId = getAccountIdLocked(db, account);
1456 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001457 return;
1458 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001459 long extrasId = getExtrasIdLocked(db, accountId, key);
1460 if (extrasId < 0 ) {
1461 extrasId = insertExtraLocked(db, accountId, key, value);
1462 if (extrasId < 0) {
1463 return;
1464 }
1465 } else {
1466 ContentValues values = new ContentValues();
1467 values.put(EXTRAS_VALUE, value);
1468 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1469 return;
1470 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001471
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001472 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001473 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001474 db.setTransactionSuccessful();
1475 } finally {
1476 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001477 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001478 }
1479 }
1480
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001481 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001482 if (result == null) {
1483 Log.e(TAG, "the result is unexpectedly null", new Exception());
1484 }
1485 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1486 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1487 + response);
1488 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001489 try {
1490 response.onResult(result);
1491 } catch (RemoteException e) {
1492 // if the caller is dead then there is no one to care about remote
1493 // exceptions
1494 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1495 Log.v(TAG, "failure while notifying response", e);
1496 }
1497 }
1498 }
1499
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001500 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001501 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1502 final String authTokenType)
1503 throws RemoteException {
1504 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001505 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1506
Fred Quintanad9640ec2012-05-23 12:37:00 -07001507 final int callingUid = getCallingUid();
1508 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001509 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001510 throw new SecurityException("can only call from system");
1511 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001512 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001513 long identityToken = clearCallingIdentity();
1514 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001515 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001516 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001517 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001518 protected String toDebugString(long now) {
1519 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001520 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001521 + ", authTokenType " + authTokenType;
1522 }
1523
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001524 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001525 public void run() throws RemoteException {
1526 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1527 }
1528
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001529 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001530 public void onResult(Bundle result) {
1531 if (result != null) {
1532 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1533 Bundle bundle = new Bundle();
1534 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1535 super.onResult(bundle);
1536 return;
1537 } else {
1538 super.onResult(result);
1539 }
1540 }
1541 }.bind();
1542 } finally {
1543 restoreCallingIdentity(identityToken);
1544 }
1545 }
1546
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001547 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001548 public void getAuthToken(IAccountManagerResponse response, final Account account,
1549 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001550 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001551 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1552 Log.v(TAG, "getAuthToken: " + account
1553 + ", response " + response
1554 + ", authTokenType " + authTokenType
1555 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1556 + ", expectActivityLaunch " + expectActivityLaunch
1557 + ", caller's uid " + Binder.getCallingUid()
1558 + ", pid " + Binder.getCallingPid());
1559 }
Fred Quintana382601f2010-03-25 12:25:10 -07001560 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001561 try {
1562 if (account == null) {
1563 Slog.w(TAG, "getAuthToken called with null account");
1564 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1565 return;
1566 }
1567 if (authTokenType == null) {
1568 Slog.w(TAG, "getAuthToken called with null authTokenType");
1569 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1570 return;
1571 }
1572 } catch (RemoteException e) {
1573 Slog.w(TAG, "Failed to report error back to the client." + e);
1574 return;
1575 }
1576
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001577 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001578 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001579 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1580 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1581 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001582 final boolean customTokens =
1583 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1584
1585 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001586 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001587 final boolean permissionGranted = customTokens ||
1588 permissionIsGranted(account, authTokenType, callerUid);
1589
Costin Manolachec6684f92011-01-14 11:25:39 -08001590 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1591 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001592 // let authenticator know the identity of the caller
1593 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1594 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1595 if (notifyOnAuthFailure) {
1596 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001597 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001598
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001599 long identityToken = clearCallingIdentity();
1600 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001601 // if the caller has permission, do the peek. otherwise go the more expensive
1602 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001603 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001604 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001605 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001606 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001607 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1608 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1609 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001610 onResult(response, result);
1611 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001612 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001613 }
1614
Amith Yamasani04e0d262012-02-14 11:50:53 -08001615 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001616 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001617 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001618 protected String toDebugString(long now) {
1619 if (loginOptions != null) loginOptions.keySet();
1620 return super.toDebugString(now) + ", getAuthToken"
1621 + ", " + account
1622 + ", authTokenType " + authTokenType
1623 + ", loginOptions " + loginOptions
1624 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1625 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001626
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001627 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001628 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001629 // If the caller doesn't have permission then create and return the
1630 // "grant permission" intent instead of the "getAuthToken" intent.
1631 if (!permissionGranted) {
1632 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1633 } else {
1634 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1635 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001636 }
1637
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001638 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001639 public void onResult(Bundle result) {
1640 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001641 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001642 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1643 new AccountAuthenticatorResponse(this),
1644 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001645 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001646 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001647 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001648 onResult(bundle);
1649 return;
1650 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001651 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001652 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001653 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1654 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001655 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001656 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001657 "the type and name should not be empty");
1658 return;
1659 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001660 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001661 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001662 authTokenType, authToken);
1663 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001664 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001665
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001666 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001667 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001668 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001669 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001670 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001671 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001672 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001673 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001674 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001675 }.bind();
1676 } finally {
1677 restoreCallingIdentity(identityToken);
1678 }
Fred Quintana60307342009-03-24 22:48:12 -07001679 }
1680
Dianne Hackborn41203752012-08-31 14:05:51 -07001681 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1682 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001683 int uid = intent.getIntExtra(
1684 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1685 String authTokenType = intent.getStringExtra(
1686 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1687 String authTokenLabel = intent.getStringExtra(
1688 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1689
1690 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1691 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001692 final String titleAndSubtitle =
1693 mContext.getString(R.string.permission_request_notification_with_subtitle,
1694 account.name);
1695 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001696 String title = titleAndSubtitle;
1697 String subtitle = "";
1698 if (index > 0) {
1699 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001700 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001701 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001702 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001703 n.setLatestEventInfo(mContext, title, subtitle,
1704 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001705 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1706 installNotification(getCredentialPermissionNotificationId(
1707 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001708 }
1709
Costin Manolache5f383ad92010-12-02 16:44:46 -08001710 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1711 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001712
1713 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001714 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001715 // Since it was set in Eclair+ we can't change it without breaking apps using
1716 // the intent from a non-Activity context.
1717 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001718 intent.addCategory(
1719 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001720
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001721 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001722 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1723 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001724 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001725
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001726 return intent;
1727 }
1728
1729 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1730 int uid) {
1731 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001732 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001733 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001734 final Pair<Pair<Account, String>, Integer> key =
1735 new Pair<Pair<Account, String>, Integer>(
1736 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001737 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001738 if (id == null) {
1739 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001740 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001741 }
1742 }
1743 return id;
1744 }
1745
Amith Yamasani04e0d262012-02-14 11:50:53 -08001746 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001747 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001748 synchronized (accounts.signinRequiredNotificationIds) {
1749 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001750 if (id == null) {
1751 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001752 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001753 }
1754 }
1755 return id;
1756 }
1757
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001758 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001759 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001760 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001761 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001762 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1763 Log.v(TAG, "addAccount: accountType " + accountType
1764 + ", response " + response
1765 + ", authTokenType " + authTokenType
1766 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1767 + ", expectActivityLaunch " + expectActivityLaunch
1768 + ", caller's uid " + Binder.getCallingUid()
1769 + ", pid " + Binder.getCallingPid());
1770 }
Fred Quintana382601f2010-03-25 12:25:10 -07001771 if (response == null) throw new IllegalArgumentException("response is null");
1772 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001773 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001774
Amith Yamasani71e6c692013-03-24 17:39:28 -07001775 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001776 int userId = Binder.getCallingUserHandle().getIdentifier();
1777 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001778 try {
1779 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1780 "User is not allowed to add an account!");
1781 } catch (RemoteException re) {
1782 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001783 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED);
1784 return;
1785 }
1786 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07001787 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001788 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1789 "User cannot modify accounts of this type (policy).");
1790 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07001791 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001792 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001793 return;
1794 }
1795
Amith Yamasani04e0d262012-02-14 11:50:53 -08001796 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001797 final int pid = Binder.getCallingPid();
1798 final int uid = Binder.getCallingUid();
1799 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1800 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1801 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1802
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001803 long identityToken = clearCallingIdentity();
1804 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001805 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001806 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001807 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001808 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001809 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001810 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001811 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001812
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001813 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001814 protected String toDebugString(long now) {
1815 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001816 + ", accountType " + accountType
1817 + ", requiredFeatures "
1818 + (requiredFeatures != null
1819 ? TextUtils.join(",", requiredFeatures)
1820 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001821 }
1822 }.bind();
1823 } finally {
1824 restoreCallingIdentity(identityToken);
1825 }
Fred Quintana60307342009-03-24 22:48:12 -07001826 }
1827
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001828 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001829 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
1830 final String authTokenType, final String[] requiredFeatures,
1831 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
1832 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1833 Log.v(TAG, "addAccount: accountType " + accountType
1834 + ", response " + response
1835 + ", authTokenType " + authTokenType
1836 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1837 + ", expectActivityLaunch " + expectActivityLaunch
1838 + ", caller's uid " + Binder.getCallingUid()
1839 + ", pid " + Binder.getCallingPid()
1840 + ", for user id " + userId);
1841 }
1842 if (response == null) throw new IllegalArgumentException("response is null");
1843 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1844 checkManageAccountsPermission();
1845
1846 // Only allow the system process to add accounts of other users
1847 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1848 + " trying to add account for " + userId);
1849
1850 // Is user disallowed from modifying accounts?
1851 if (!canUserModifyAccounts(userId)) {
1852 try {
1853 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1854 "User is not allowed to add an account!");
1855 } catch (RemoteException re) {
1856 }
1857 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED);
1858 return;
1859 }
1860 if (!canUserModifyAccountsForType(userId, accountType)) {
1861 try {
1862 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1863 "User cannot modify accounts of this type (policy).");
1864 } catch (RemoteException re) {
1865 }
1866 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
1867 return;
1868 }
1869
1870 UserAccounts accounts = getUserAccounts(userId);
1871 final int pid = Binder.getCallingPid();
1872 final int uid = Binder.getCallingUid();
1873 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1874 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1875 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1876
1877 long identityToken = clearCallingIdentity();
1878 try {
1879 new Session(accounts, response, accountType, expectActivityLaunch,
1880 true /* stripAuthTokenFromResult */) {
1881 @Override
1882 public void run() throws RemoteException {
1883 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
1884 options);
1885 }
1886
1887 @Override
1888 protected String toDebugString(long now) {
1889 return super.toDebugString(now) + ", addAccount"
1890 + ", accountType " + accountType
1891 + ", requiredFeatures "
1892 + (requiredFeatures != null
1893 ? TextUtils.join(",", requiredFeatures)
1894 : null);
1895 }
1896 }.bind();
1897 } finally {
1898 restoreCallingIdentity(identityToken);
1899 }
1900 }
1901
1902 private void showCantAddAccount(int errorCode) {
1903 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1904 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
1905 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1906 long identityToken = clearCallingIdentity();
1907 try {
1908 mContext.startActivity(cantAddAccount);
1909 } finally {
1910 restoreCallingIdentity(identityToken);
1911 }
1912 }
1913
1914 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001915 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1916 final Account account, final Bundle options, final boolean expectActivityLaunch,
1917 int userId) {
1918 // Only allow the system process to read accounts of other users
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001919 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001920 + " trying to confirm account credentials for " + userId);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001921
Fred Quintana56285a62010-12-02 14:20:51 -08001922 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1923 Log.v(TAG, "confirmCredentials: " + account
1924 + ", response " + response
1925 + ", expectActivityLaunch " + expectActivityLaunch
1926 + ", caller's uid " + Binder.getCallingUid()
1927 + ", pid " + Binder.getCallingPid());
1928 }
Fred Quintana382601f2010-03-25 12:25:10 -07001929 if (response == null) throw new IllegalArgumentException("response is null");
1930 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001931 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001932 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001933 long identityToken = clearCallingIdentity();
1934 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001935 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001936 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001937 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001938 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001939 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001940 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001941 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001942 protected String toDebugString(long now) {
1943 return super.toDebugString(now) + ", confirmCredentials"
1944 + ", " + account;
1945 }
1946 }.bind();
1947 } finally {
1948 restoreCallingIdentity(identityToken);
1949 }
Fred Quintana60307342009-03-24 22:48:12 -07001950 }
1951
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001952 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001953 public void updateCredentials(IAccountManagerResponse response, final Account account,
1954 final String authTokenType, final boolean expectActivityLaunch,
1955 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001956 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1957 Log.v(TAG, "updateCredentials: " + account
1958 + ", response " + response
1959 + ", authTokenType " + authTokenType
1960 + ", expectActivityLaunch " + expectActivityLaunch
1961 + ", caller's uid " + Binder.getCallingUid()
1962 + ", pid " + Binder.getCallingPid());
1963 }
Fred Quintana382601f2010-03-25 12:25:10 -07001964 if (response == null) throw new IllegalArgumentException("response is null");
1965 if (account == null) throw new IllegalArgumentException("account is null");
1966 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001967 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001968 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001969 long identityToken = clearCallingIdentity();
1970 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001971 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001972 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001973 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001974 public void run() throws RemoteException {
1975 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1976 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001977 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001978 protected String toDebugString(long now) {
1979 if (loginOptions != null) loginOptions.keySet();
1980 return super.toDebugString(now) + ", updateCredentials"
1981 + ", " + account
1982 + ", authTokenType " + authTokenType
1983 + ", loginOptions " + loginOptions;
1984 }
1985 }.bind();
1986 } finally {
1987 restoreCallingIdentity(identityToken);
1988 }
Fred Quintana60307342009-03-24 22:48:12 -07001989 }
1990
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001991 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001992 public void editProperties(IAccountManagerResponse response, final String accountType,
1993 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001994 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1995 Log.v(TAG, "editProperties: accountType " + accountType
1996 + ", response " + response
1997 + ", expectActivityLaunch " + expectActivityLaunch
1998 + ", caller's uid " + Binder.getCallingUid()
1999 + ", pid " + Binder.getCallingPid());
2000 }
Fred Quintana382601f2010-03-25 12:25:10 -07002001 if (response == null) throw new IllegalArgumentException("response is null");
2002 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002003 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002004 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002005 long identityToken = clearCallingIdentity();
2006 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002007 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08002008 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002009 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002010 public void run() throws RemoteException {
2011 mAuthenticator.editProperties(this, mAccountType);
2012 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002013 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002014 protected String toDebugString(long now) {
2015 return super.toDebugString(now) + ", editProperties"
2016 + ", accountType " + accountType;
2017 }
2018 }.bind();
2019 } finally {
2020 restoreCallingIdentity(identityToken);
2021 }
Fred Quintana60307342009-03-24 22:48:12 -07002022 }
2023
Fred Quintana33269202009-04-20 16:05:10 -07002024 private class GetAccountsByTypeAndFeatureSession extends Session {
2025 private final String[] mFeatures;
2026 private volatile Account[] mAccountsOfType = null;
2027 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2028 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002029 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002030
Amith Yamasani04e0d262012-02-14 11:50:53 -08002031 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002032 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002033 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08002034 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002035 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002036 mFeatures = features;
2037 }
2038
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002039 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002040 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002041 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002042 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2043 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002044 }
Fred Quintana33269202009-04-20 16:05:10 -07002045 // check whether each account matches the requested features
2046 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2047 mCurrentAccount = 0;
2048
2049 checkAccount();
2050 }
2051
2052 public void checkAccount() {
2053 if (mCurrentAccount >= mAccountsOfType.length) {
2054 sendResult();
2055 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002056 }
Fred Quintana33269202009-04-20 16:05:10 -07002057
Fred Quintana29e94b82010-03-10 12:11:51 -08002058 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2059 if (accountAuthenticator == null) {
2060 // It is possible that the authenticator has died, which is indicated by
2061 // mAuthenticator being set to null. If this happens then just abort.
2062 // There is no need to send back a result or error in this case since
2063 // that already happened when mAuthenticator was cleared.
2064 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2065 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2066 + " connected to the authenticator, " + toDebugString());
2067 }
2068 return;
2069 }
Fred Quintana33269202009-04-20 16:05:10 -07002070 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002071 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002072 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002073 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002074 }
2075 }
2076
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002077 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002078 public void onResult(Bundle result) {
2079 mNumResults++;
2080 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002081 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002082 return;
2083 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002084 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002085 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2086 }
2087 mCurrentAccount++;
2088 checkAccount();
2089 }
2090
2091 public void sendResult() {
2092 IAccountManagerResponse response = getResponseAndClose();
2093 if (response != null) {
2094 try {
2095 Account[] accounts = new Account[mAccountsWithFeatures.size()];
2096 for (int i = 0; i < accounts.length; i++) {
2097 accounts[i] = mAccountsWithFeatures.get(i);
2098 }
Fred Quintana56285a62010-12-02 14:20:51 -08002099 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2100 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2101 + response);
2102 }
Fred Quintana33269202009-04-20 16:05:10 -07002103 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002104 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07002105 response.onResult(result);
2106 } catch (RemoteException e) {
2107 // if the caller is dead then there is no one to care about remote exceptions
2108 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2109 Log.v(TAG, "failure while notifying response", e);
2110 }
2111 }
2112 }
2113 }
2114
2115
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002116 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002117 protected String toDebugString(long now) {
2118 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2119 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2120 }
2121 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002122
Amith Yamasani04e0d262012-02-14 11:50:53 -08002123 /**
2124 * Returns the accounts for a specific user
2125 * @hide
2126 */
2127 public Account[] getAccounts(int userId) {
2128 checkReadAccountsPermission();
2129 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002130 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002131 long identityToken = clearCallingIdentity();
2132 try {
2133 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002134 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002135 }
2136 } finally {
2137 restoreCallingIdentity(identityToken);
2138 }
2139 }
2140
Amith Yamasanif29f2362012-04-05 18:29:52 -07002141 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002142 * Returns accounts for all running users.
2143 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07002144 * @hide
2145 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002146 public AccountAndUser[] getRunningAccounts() {
2147 final int[] runningUserIds;
2148 try {
2149 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2150 } catch (RemoteException e) {
2151 // Running in system_server; should never happen
2152 throw new RuntimeException(e);
2153 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002154 return getAccounts(runningUserIds);
2155 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07002156
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002157 /** {@hide} */
2158 public AccountAndUser[] getAllAccounts() {
2159 final List<UserInfo> users = getUserManager().getUsers();
2160 final int[] userIds = new int[users.size()];
2161 for (int i = 0; i < userIds.length; i++) {
2162 userIds[i] = users.get(i).id;
2163 }
2164 return getAccounts(userIds);
2165 }
2166
2167 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002168 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002169 for (int userId : userIds) {
2170 UserAccounts userAccounts = getUserAccounts(userId);
2171 if (userAccounts == null) continue;
2172 synchronized (userAccounts.cacheLock) {
2173 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2174 Binder.getCallingUid(), null);
2175 for (int a = 0; a < accounts.length; a++) {
2176 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07002177 }
2178 }
2179 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002180
2181 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2182 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002183 }
2184
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002185 @Override
2186 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002187 return getAccountsAsUser(type, userId, null, -1);
2188 }
2189
2190 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
2191 int packageUid) {
2192 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002193 // Only allow the system process to read accounts of other users
2194 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002195 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002196 && mContext.checkCallingOrSelfPermission(
2197 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2198 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002199 throw new SecurityException("User " + UserHandle.getCallingUserId()
2200 + " trying to get account for " + userId);
2201 }
2202
Fred Quintana56285a62010-12-02 14:20:51 -08002203 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2204 Log.v(TAG, "getAccounts: accountType " + type
2205 + ", caller's uid " + Binder.getCallingUid()
2206 + ", pid " + Binder.getCallingPid());
2207 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002208 // If the original calling app was using the framework account chooser activity, we'll
2209 // be passed in the original caller's uid here, which is what should be used for filtering.
2210 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2211 callingUid = packageUid;
2212 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002213 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002214 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002215 long identityToken = clearCallingIdentity();
2216 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002217 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002218 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002219 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002220 } finally {
2221 restoreCallingIdentity(identityToken);
2222 }
2223 }
2224
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002225 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002226 public boolean addSharedAccountAsUser(Account account, int userId) {
2227 userId = handleIncomingUser(userId);
2228 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
2229 ContentValues values = new ContentValues();
2230 values.put(ACCOUNTS_NAME, account.name);
2231 values.put(ACCOUNTS_TYPE, account.type);
2232 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2233 new String[] {account.name, account.type});
2234 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2235 if (accountId < 0) {
2236 Log.w(TAG, "insertAccountIntoDatabase: " + account
2237 + ", skipping the DB insert failed");
2238 return false;
2239 }
2240 return true;
2241 }
2242
2243 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002244 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
2245 userId = handleIncomingUser(userId);
2246 UserAccounts accounts = getUserAccounts(userId);
2247 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2248 final ContentValues values = new ContentValues();
2249 values.put(ACCOUNTS_NAME, newName);
2250 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
2251 int r = db.update(
2252 TABLE_SHARED_ACCOUNTS,
2253 values,
2254 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2255 new String[] { account.name, account.type });
2256 if (r > 0) {
2257 // Recursively rename the account.
2258 renameAccountInternal(accounts, account, newName);
2259 }
2260 return r > 0;
2261 }
2262
2263 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002264 public boolean removeSharedAccountAsUser(Account account, int userId) {
2265 userId = handleIncomingUser(userId);
2266 UserAccounts accounts = getUserAccounts(userId);
2267 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2268 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2269 new String[] {account.name, account.type});
2270 if (r > 0) {
2271 removeAccountInternal(accounts, account);
2272 }
2273 return r > 0;
2274 }
2275
2276 @Override
2277 public Account[] getSharedAccountsAsUser(int userId) {
2278 userId = handleIncomingUser(userId);
2279 UserAccounts accounts = getUserAccounts(userId);
2280 ArrayList<Account> accountList = new ArrayList<Account>();
2281 Cursor cursor = null;
2282 try {
2283 cursor = accounts.openHelper.getReadableDatabase()
2284 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2285 null, null, null, null, null);
2286 if (cursor != null && cursor.moveToFirst()) {
2287 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2288 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2289 do {
2290 accountList.add(new Account(cursor.getString(nameIndex),
2291 cursor.getString(typeIndex)));
2292 } while (cursor.moveToNext());
2293 }
2294 } finally {
2295 if (cursor != null) {
2296 cursor.close();
2297 }
2298 }
2299 Account[] accountArray = new Account[accountList.size()];
2300 accountList.toArray(accountArray);
2301 return accountArray;
2302 }
2303
2304 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002305 public Account[] getAccounts(String type) {
2306 return getAccountsAsUser(type, UserHandle.getCallingUserId());
2307 }
2308
Amith Yamasani27db4682013-03-30 17:07:47 -07002309 @Override
2310 public Account[] getAccountsForPackage(String packageName, int uid) {
2311 int callingUid = Binder.getCallingUid();
2312 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2313 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2314 + callingUid + " with uid=" + uid);
2315 }
2316 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
2317 }
2318
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002319 @Override
2320 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
2321 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
2322 int packageUid = -1;
2323 try {
2324 packageUid = AppGlobals.getPackageManager().getPackageUid(
2325 packageName, UserHandle.getCallingUserId());
2326 } catch (RemoteException re) {
2327 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2328 return new Account[0];
2329 }
2330 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
2331 }
2332
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002333 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002334 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07002335 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08002336 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2337 Log.v(TAG, "getAccounts: accountType " + type
2338 + ", response " + response
2339 + ", features " + stringArrayToString(features)
2340 + ", caller's uid " + Binder.getCallingUid()
2341 + ", pid " + Binder.getCallingPid());
2342 }
Fred Quintana382601f2010-03-25 12:25:10 -07002343 if (response == null) throw new IllegalArgumentException("response is null");
2344 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002345 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002346 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002347 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07002348 long identityToken = clearCallingIdentity();
2349 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002350 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002351 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002352 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002353 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002354 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002355 Bundle result = new Bundle();
2356 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2357 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002358 return;
2359 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002360 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
2361 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002362 } finally {
2363 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002364 }
2365 }
2366
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002367 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002368 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002369 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002370 try {
2371 if (cursor.moveToNext()) {
2372 return cursor.getLong(0);
2373 }
2374 return -1;
2375 } finally {
2376 cursor.close();
2377 }
2378 }
2379
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002380 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002381 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2382 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2383 new String[]{key}, null, null, null);
2384 try {
2385 if (cursor.moveToNext()) {
2386 return cursor.getLong(0);
2387 }
2388 return -1;
2389 } finally {
2390 cursor.close();
2391 }
2392 }
2393
Fred Quintanaa698f422009-04-08 19:14:54 -07002394 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002395 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002396 IAccountManagerResponse mResponse;
2397 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002398 final boolean mExpectActivityLaunch;
2399 final long mCreationTime;
2400
Fred Quintana33269202009-04-20 16:05:10 -07002401 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002402 private int mNumRequestContinued = 0;
2403 private int mNumErrors = 0;
2404
Fred Quintana60307342009-03-24 22:48:12 -07002405 IAccountAuthenticator mAuthenticator = null;
2406
Fred Quintana8570f742010-02-18 10:32:54 -08002407 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002408 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002409
Amith Yamasani04e0d262012-02-14 11:50:53 -08002410 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08002411 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07002412 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002413 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002414 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002415 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002416 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002417 mResponse = response;
2418 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002419 mExpectActivityLaunch = expectActivityLaunch;
2420 mCreationTime = SystemClock.elapsedRealtime();
2421 synchronized (mSessions) {
2422 mSessions.put(toString(), this);
2423 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002424 if (response != null) {
2425 try {
2426 response.asBinder().linkToDeath(this, 0 /* flags */);
2427 } catch (RemoteException e) {
2428 mResponse = null;
2429 binderDied();
2430 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002431 }
Fred Quintana60307342009-03-24 22:48:12 -07002432 }
2433
Fred Quintanaa698f422009-04-08 19:14:54 -07002434 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002435 if (mResponse == null) {
2436 // this session has already been closed
2437 return null;
2438 }
Fred Quintana60307342009-03-24 22:48:12 -07002439 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002440 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002441 return response;
2442 }
2443
Fred Quintanaa698f422009-04-08 19:14:54 -07002444 private void close() {
2445 synchronized (mSessions) {
2446 if (mSessions.remove(toString()) == null) {
2447 // the session was already closed, so bail out now
2448 return;
2449 }
2450 }
2451 if (mResponse != null) {
2452 // stop listening for response deaths
2453 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2454
2455 // clear this so that we don't accidentally send any further results
2456 mResponse = null;
2457 }
2458 cancelTimeout();
2459 unbind();
2460 }
2461
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002462 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002463 public void binderDied() {
2464 mResponse = null;
2465 close();
2466 }
2467
2468 protected String toDebugString() {
2469 return toDebugString(SystemClock.elapsedRealtime());
2470 }
2471
2472 protected String toDebugString(long now) {
2473 return "Session: expectLaunch " + mExpectActivityLaunch
2474 + ", connected " + (mAuthenticator != null)
2475 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2476 + "/" + mNumErrors + ")"
2477 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2478 }
2479
Fred Quintana60307342009-03-24 22:48:12 -07002480 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002481 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2482 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2483 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002484 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002485 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002486 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002487 }
2488 }
2489
2490 private void unbind() {
2491 if (mAuthenticator != null) {
2492 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002493 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002494 }
2495 }
2496
2497 public void scheduleTimeout() {
2498 mMessageHandler.sendMessageDelayed(
2499 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2500 }
2501
2502 public void cancelTimeout() {
2503 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2504 }
2505
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002506 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002507 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002508 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002509 try {
2510 run();
2511 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002512 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002513 "remote exception");
2514 }
Fred Quintana60307342009-03-24 22:48:12 -07002515 }
2516
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002517 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002518 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002519 mAuthenticator = null;
2520 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002521 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002522 try {
2523 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2524 "disconnected");
2525 } catch (RemoteException e) {
2526 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2527 Log.v(TAG, "Session.onServiceDisconnected: "
2528 + "caught RemoteException while responding", e);
2529 }
2530 }
Fred Quintana60307342009-03-24 22:48:12 -07002531 }
2532 }
2533
Fred Quintanab839afc2009-10-14 15:57:28 -07002534 public abstract void run() throws RemoteException;
2535
Fred Quintana60307342009-03-24 22:48:12 -07002536 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002537 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002538 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002539 try {
2540 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2541 "timeout");
2542 } catch (RemoteException e) {
2543 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2544 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2545 e);
2546 }
2547 }
Fred Quintana60307342009-03-24 22:48:12 -07002548 }
2549 }
2550
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002551 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002552 public void onResult(Bundle result) {
2553 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002554 Intent intent = null;
2555 if (result != null
2556 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2557 /*
2558 * The Authenticator API allows third party authenticators to
2559 * supply arbitrary intents to other apps that they can run,
2560 * this can be very bad when those apps are in the system like
2561 * the System Settings.
2562 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002563 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07002564 long bid = Binder.clearCallingIdentity();
2565 try {
2566 PackageManager pm = mContext.getPackageManager();
2567 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2568 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2569 if (PackageManager.SIGNATURE_MATCH !=
2570 pm.checkSignatures(authenticatorUid, targetUid)) {
2571 throw new SecurityException(
2572 "Activity to be started with KEY_INTENT must " +
2573 "share Authenticator's signatures");
2574 }
2575 } finally {
2576 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002577 }
2578 }
2579 if (result != null
2580 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002581 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2582 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002583 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2584 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002585 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2586 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002587 }
Fred Quintana60307342009-03-24 22:48:12 -07002588 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002589 IAccountManagerResponse response;
2590 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002591 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002592 response = mResponse;
2593 } else {
2594 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002595 }
Fred Quintana60307342009-03-24 22:48:12 -07002596 if (response != null) {
2597 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002598 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002599 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2600 Log.v(TAG, getClass().getSimpleName()
2601 + " calling onError() on response " + response);
2602 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002603 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002604 "null bundle returned");
2605 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002606 if (mStripAuthTokenFromResult) {
2607 result.remove(AccountManager.KEY_AUTHTOKEN);
2608 }
Fred Quintana56285a62010-12-02 14:20:51 -08002609 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2610 Log.v(TAG, getClass().getSimpleName()
2611 + " calling onResult() on response " + response);
2612 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002613 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
2614 (intent == null)) {
2615 // All AccountManager error codes are greater than 0
2616 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
2617 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2618 } else {
2619 response.onResult(result);
2620 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002621 }
Fred Quintana60307342009-03-24 22:48:12 -07002622 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002623 // if the caller is dead then there is no one to care about remote exceptions
2624 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2625 Log.v(TAG, "failure while notifying response", e);
2626 }
Fred Quintana60307342009-03-24 22:48:12 -07002627 }
2628 }
2629 }
Fred Quintana60307342009-03-24 22:48:12 -07002630
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002631 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002632 public void onRequestContinued() {
2633 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002634 }
2635
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002636 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002637 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002638 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002639 IAccountManagerResponse response = getResponseAndClose();
2640 if (response != null) {
2641 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002642 Log.v(TAG, getClass().getSimpleName()
2643 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002644 }
2645 try {
2646 response.onError(errorCode, errorMessage);
2647 } catch (RemoteException e) {
2648 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2649 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2650 }
2651 }
2652 } else {
2653 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2654 Log.v(TAG, "Session.onError: already closed");
2655 }
Fred Quintana60307342009-03-24 22:48:12 -07002656 }
2657 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002658
2659 /**
2660 * find the component name for the authenticator and initiate a bind
2661 * if no authenticator or the bind fails then return false, otherwise return true
2662 */
2663 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002664 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2665 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2666 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002667 if (authenticatorInfo == null) {
2668 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2669 Log.v(TAG, "there is no authenticator for " + authenticatorType
2670 + ", bailing out");
2671 }
2672 return false;
2673 }
2674
2675 Intent intent = new Intent();
2676 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2677 intent.setComponent(authenticatorInfo.componentName);
2678 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2679 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2680 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002681 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2682 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002683 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2684 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2685 }
2686 return false;
2687 }
2688
2689
2690 return true;
2691 }
Fred Quintana60307342009-03-24 22:48:12 -07002692 }
2693
2694 private class MessageHandler extends Handler {
2695 MessageHandler(Looper looper) {
2696 super(looper);
2697 }
Costin Manolache3348f142009-09-29 18:58:36 -07002698
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002699 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002700 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002701 switch (msg.what) {
2702 case MESSAGE_TIMED_OUT:
2703 Session session = (Session)msg.obj;
2704 session.onTimedOut();
2705 break;
2706
Amith Yamasani5be347b2013-03-31 17:44:31 -07002707 case MESSAGE_COPY_SHARED_ACCOUNT:
2708 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2709 break;
2710
Fred Quintana60307342009-03-24 22:48:12 -07002711 default:
2712 throw new IllegalStateException("unhandled message: " + msg.what);
2713 }
2714 }
2715 }
2716
Amith Yamasani04e0d262012-02-14 11:50:53 -08002717 private static String getDatabaseName(int userId) {
2718 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002719 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002720 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002721 // Migrate old file, if it exists, to the new location.
2722 // Make sure the new file doesn't already exist. A dummy file could have been
2723 // accidentally created in the old location, causing the new one to become corrupted
2724 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002725 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002726 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002727 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002728 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002729 if (!userDir.exists()) {
2730 if (!userDir.mkdirs()) {
2731 throw new IllegalStateException("User dir cannot be created: " + userDir);
2732 }
2733 }
2734 if (!oldFile.renameTo(databaseFile)) {
2735 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2736 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002737 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002738 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002739 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002740 }
2741
Amith Yamasani04e0d262012-02-14 11:50:53 -08002742 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002743
Amith Yamasani04e0d262012-02-14 11:50:53 -08002744 public DatabaseHelper(Context context, int userId) {
2745 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002746 }
2747
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002748 /**
2749 * This call needs to be made while the mCacheLock is held. The way to
2750 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2751 * @param db The database.
2752 */
Fred Quintana60307342009-03-24 22:48:12 -07002753 @Override
2754 public void onCreate(SQLiteDatabase db) {
2755 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2756 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2757 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2758 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2759 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002760 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Fred Quintana60307342009-03-24 22:48:12 -07002761 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2762
2763 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2764 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2765 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2766 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2767 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2768 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2769
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002770 createGrantsTable(db);
2771
Fred Quintana60307342009-03-24 22:48:12 -07002772 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2773 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2774 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2775 + EXTRAS_KEY + " TEXT NOT NULL, "
2776 + EXTRAS_VALUE + " TEXT, "
2777 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2778
2779 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2780 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2781 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002782
Amith Yamasani67df64b2012-12-14 12:09:36 -08002783 createSharedAccountsTable(db);
2784
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002785 createAccountsDeletionTrigger(db);
2786 }
2787
Amith Yamasani67df64b2012-12-14 12:09:36 -08002788 private void createSharedAccountsTable(SQLiteDatabase db) {
2789 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2790 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2791 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2792 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2793 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2794 }
2795
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002796 private void addOldAccountNameColumn(SQLiteDatabase db) {
2797 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
2798 }
2799
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002800 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002801 db.execSQL(""
2802 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2803 + " BEGIN"
2804 + " DELETE FROM " + TABLE_AUTHTOKENS
2805 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2806 + " DELETE FROM " + TABLE_EXTRAS
2807 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002808 + " DELETE FROM " + TABLE_GRANTS
2809 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002810 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002811 }
2812
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002813 private void createGrantsTable(SQLiteDatabase db) {
2814 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2815 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2816 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2817 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2818 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2819 + "," + GRANTS_GRANTEE_UID + "))");
2820 }
2821
Fred Quintana60307342009-03-24 22:48:12 -07002822 @Override
2823 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002824 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002825
Fred Quintanaa698f422009-04-08 19:14:54 -07002826 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002827 // no longer need to do anything since the work is done
2828 // when upgrading from version 2
2829 oldVersion++;
2830 }
2831
2832 if (oldVersion == 2) {
2833 createGrantsTable(db);
2834 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2835 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002836 oldVersion++;
2837 }
Costin Manolache3348f142009-09-29 18:58:36 -07002838
2839 if (oldVersion == 3) {
2840 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2841 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2842 oldVersion++;
2843 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002844
2845 if (oldVersion == 4) {
2846 createSharedAccountsTable(db);
2847 oldVersion++;
2848 }
2849
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002850 if (oldVersion == 5) {
2851 addOldAccountNameColumn(db);
2852 oldVersion++;
2853 }
2854
Amith Yamasani67df64b2012-12-14 12:09:36 -08002855 if (oldVersion != newVersion) {
2856 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2857 }
Fred Quintana60307342009-03-24 22:48:12 -07002858 }
2859
2860 @Override
2861 public void onOpen(SQLiteDatabase db) {
2862 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2863 }
2864 }
2865
Fred Quintana60307342009-03-24 22:48:12 -07002866 public IBinder onBind(Intent intent) {
2867 return asBinder();
2868 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002869
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002870 /**
2871 * Searches array of arguments for the specified string
2872 * @param args array of argument strings
2873 * @param value value to search for
2874 * @return true if the value is contained in the array
2875 */
2876 private static boolean scanArgs(String[] args, String value) {
2877 if (args != null) {
2878 for (String arg : args) {
2879 if (value.equals(arg)) {
2880 return true;
2881 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002882 }
2883 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002884 return false;
2885 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002886
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002887 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002888 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002889 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2890 != PackageManager.PERMISSION_GRANTED) {
2891 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2892 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2893 + " without permission " + android.Manifest.permission.DUMP);
2894 return;
2895 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002896 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002897 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002898
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002899 final List<UserInfo> users = getUserManager().getUsers();
2900 for (UserInfo user : users) {
2901 ipw.println("User " + user + ":");
2902 ipw.increaseIndent();
2903 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2904 ipw.println();
2905 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002906 }
2907 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002908
Amith Yamasani04e0d262012-02-14 11:50:53 -08002909 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2910 String[] args, boolean isCheckinRequest) {
2911 synchronized (userAccounts.cacheLock) {
2912 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002913
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002914 if (isCheckinRequest) {
2915 // This is a checkin request. *Only* upload the account types and the count of each.
2916 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2917 null, null, ACCOUNTS_TYPE, null, null);
2918 try {
2919 while (cursor.moveToNext()) {
2920 // print type,count
2921 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2922 }
2923 } finally {
2924 if (cursor != null) {
2925 cursor.close();
2926 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002927 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002928 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002929 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002930 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002931 fout.println("Accounts: " + accounts.length);
2932 for (Account account : accounts) {
2933 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002934 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002935
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002936 fout.println();
2937 synchronized (mSessions) {
2938 final long now = SystemClock.elapsedRealtime();
2939 fout.println("Active Sessions: " + mSessions.size());
2940 for (Session session : mSessions.values()) {
2941 fout.println(" " + session.toDebugString(now));
2942 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002943 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002944
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002945 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002946 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002947 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002948 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002949 }
2950
Amith Yamasani04e0d262012-02-14 11:50:53 -08002951 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002952 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002953 long identityToken = clearCallingIdentity();
2954 try {
2955 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2956 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2957 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002958
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002959 if (intent.getComponent() != null &&
2960 GrantCredentialsPermissionActivity.class.getName().equals(
2961 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002962 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002963 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002964 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002965 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002966 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2967 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002968 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002969 final String notificationTitleFormat =
2970 mContext.getText(R.string.notification_title).toString();
2971 n.setLatestEventInfo(mContext,
2972 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002973 message, PendingIntent.getActivityAsUser(
2974 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002975 null, user));
2976 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002977 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002978 } finally {
2979 restoreCallingIdentity(identityToken);
2980 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002981 }
2982
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002983 protected void installNotification(final int notificationId, final Notification n,
2984 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002985 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002986 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002987 }
2988
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002989 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002990 long identityToken = clearCallingIdentity();
2991 try {
2992 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002993 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002994 } finally {
2995 restoreCallingIdentity(identityToken);
2996 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002997 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002998
Fred Quintanab38eb142010-02-24 13:40:54 -08002999 /** Succeeds if any of the specified permissions are granted. */
3000 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003001 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08003002
3003 for (String perm : permissions) {
3004 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
3005 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003006 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08003007 }
3008 return;
3009 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003010 }
Fred Quintanab38eb142010-02-24 13:40:54 -08003011
3012 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08003013 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08003014 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003015 }
3016
Amith Yamasani67df64b2012-12-14 12:09:36 -08003017 private int handleIncomingUser(int userId) {
3018 try {
3019 return ActivityManagerNative.getDefault().handleIncomingUser(
3020 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
3021 } catch (RemoteException re) {
3022 // Shouldn't happen, local.
3023 }
3024 return userId;
3025 }
3026
Christopher Tateccbf84f2013-05-08 15:25:41 -07003027 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003028 final int callingUserId = UserHandle.getUserId(callingUid);
3029
3030 final PackageManager userPackageManager;
3031 try {
3032 userPackageManager = mContext.createPackageContextAsUser(
3033 "android", 0, new UserHandle(callingUserId)).getPackageManager();
3034 } catch (NameNotFoundException e) {
3035 return false;
3036 }
3037
3038 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07003039 for (String name : packages) {
3040 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003041 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08003042 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07003043 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07003044 return true;
3045 }
3046 } catch (PackageManager.NameNotFoundException e) {
3047 return false;
3048 }
3049 }
3050 return false;
3051 }
3052
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003053 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07003054 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07003055 final boolean fromAuthenticator = account != null
3056 && hasAuthenticatorUid(account.type, callerUid);
3057 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08003058 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003059 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3060 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08003061 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003062 + ": is authenticator? " + fromAuthenticator
3063 + ", has explicit permission? " + hasExplicitGrants);
3064 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07003065 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003066 }
3067
Fred Quintana1a231912009-10-15 11:31:30 -07003068 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003069 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003070 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003071 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003072 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003073 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08003074 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003075 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003076 }
3077 }
3078 return false;
3079 }
3080
Amith Yamasani04e0d262012-02-14 11:50:53 -08003081 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
3082 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003083 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003084 return true;
3085 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003086 UserAccounts accounts = getUserAccountsForCaller();
3087 synchronized (accounts.cacheLock) {
3088 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3089 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003090 account.name, account.type};
3091 final boolean permissionGranted =
3092 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
3093 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
3094 // TODO: Skip this check when running automated tests. Replace this
3095 // with a more general solution.
3096 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08003097 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003098 + " but ignoring since device is in test harness.");
3099 return true;
3100 }
3101 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003102 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003103 }
3104
3105 private void checkCallingUidAgainstAuthenticator(Account account) {
3106 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07003107 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003108 String msg = "caller uid " + uid + " is different than the authenticator's uid";
3109 Log.w(TAG, msg);
3110 throw new SecurityException(msg);
3111 }
3112 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3113 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
3114 }
3115 }
3116
3117 private void checkAuthenticateAccountsPermission(Account account) {
3118 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
3119 checkCallingUidAgainstAuthenticator(account);
3120 }
3121
3122 private void checkReadAccountsPermission() {
3123 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
3124 }
3125
3126 private void checkManageAccountsPermission() {
3127 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
3128 }
3129
Fred Quintanab38eb142010-02-24 13:40:54 -08003130 private void checkManageAccountsOrUseCredentialsPermissions() {
3131 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
3132 Manifest.permission.USE_CREDENTIALS);
3133 }
3134
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003135 private boolean canUserModifyAccounts(int userId) {
3136 if (getUserManager().getUserRestrictions(new UserHandle(userId))
3137 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
3138 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003139 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003140 return true;
3141 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003142
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003143 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003144 DevicePolicyManager dpm = (DevicePolicyManager) mContext
3145 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003146 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02003147 if (typesArray == null) {
3148 return true;
3149 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003150 for (String forbiddenType : typesArray) {
3151 if (forbiddenType.equals(accountType)) {
3152 return false;
3153 }
3154 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003155 return true;
3156 }
3157
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003158 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07003159 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
3160 throws RemoteException {
3161 final int callingUid = getCallingUid();
3162
Amith Yamasani27db4682013-03-30 17:07:47 -07003163 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07003164 throw new SecurityException();
3165 }
3166
3167 if (value) {
3168 grantAppPermission(account, authTokenType, uid);
3169 } else {
3170 revokeAppPermission(account, authTokenType, uid);
3171 }
3172 }
3173
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003174 /**
3175 * Allow callers with the given uid permission to get credentials for account/authTokenType.
3176 * <p>
3177 * Although this is public it can only be accessed via the AccountManagerService object
3178 * which is in the system. This means we don't need to protect it with permissions.
3179 * @hide
3180 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003181 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003182 if (account == null || authTokenType == null) {
3183 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003184 return;
3185 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003186 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003187 synchronized (accounts.cacheLock) {
3188 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003189 db.beginTransaction();
3190 try {
3191 long accountId = getAccountIdLocked(db, account);
3192 if (accountId >= 0) {
3193 ContentValues values = new ContentValues();
3194 values.put(GRANTS_ACCOUNTS_ID, accountId);
3195 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
3196 values.put(GRANTS_GRANTEE_UID, uid);
3197 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
3198 db.setTransactionSuccessful();
3199 }
3200 } finally {
3201 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003202 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003203 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3204 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003205 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003206 }
3207
3208 /**
3209 * Don't allow callers with the given uid permission to get credentials for
3210 * account/authTokenType.
3211 * <p>
3212 * Although this is public it can only be accessed via the AccountManagerService object
3213 * which is in the system. This means we don't need to protect it with permissions.
3214 * @hide
3215 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003216 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003217 if (account == null || authTokenType == null) {
3218 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003219 return;
3220 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003221 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003222 synchronized (accounts.cacheLock) {
3223 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003224 db.beginTransaction();
3225 try {
3226 long accountId = getAccountIdLocked(db, account);
3227 if (accountId >= 0) {
3228 db.delete(TABLE_GRANTS,
3229 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
3230 + GRANTS_GRANTEE_UID + "=?",
3231 new String[]{String.valueOf(accountId), authTokenType,
3232 String.valueOf(uid)});
3233 db.setTransactionSuccessful();
3234 }
3235 } finally {
3236 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003237 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003238 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3239 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003240 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003241 }
Fred Quintana56285a62010-12-02 14:20:51 -08003242
3243 static final private String stringArrayToString(String[] value) {
3244 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
3245 }
3246
Amith Yamasani04e0d262012-02-14 11:50:53 -08003247 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
3248 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003249 if (oldAccountsForType != null) {
3250 ArrayList<Account> newAccountsList = new ArrayList<Account>();
3251 for (Account curAccount : oldAccountsForType) {
3252 if (!curAccount.equals(account)) {
3253 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003254 }
3255 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003256 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003257 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003258 } else {
3259 Account[] newAccountsForType = new Account[newAccountsList.size()];
3260 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003261 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003262 }
Fred Quintana56285a62010-12-02 14:20:51 -08003263 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003264 accounts.userDataCache.remove(account);
3265 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003266 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003267 }
3268
3269 /**
3270 * This assumes that the caller has already checked that the account is not already present.
3271 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08003272 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
3273 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003274 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
3275 Account[] newAccountsForType = new Account[oldLength + 1];
3276 if (accountsForType != null) {
3277 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08003278 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003279 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003280 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08003281 }
3282
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003283 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07003284 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003285 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07003286 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003287 return unfiltered;
3288 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003289 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
3290 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003291 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003292 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003293 // otherwise return non-shared accounts only.
3294 // This might be a temporary way to specify a whitelist
3295 String whiteList = mContext.getResources().getString(
3296 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
3297 for (String packageName : packages) {
3298 if (whiteList.contains(";" + packageName + ";")) {
3299 return unfiltered;
3300 }
3301 }
3302 ArrayList<Account> allowed = new ArrayList<Account>();
3303 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
3304 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003305 String requiredAccountType = "";
3306 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07003307 // If there's an explicit callingPackage specified, check if that package
3308 // opted in to see restricted accounts.
3309 if (callingPackage != null) {
3310 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003311 if (pi != null && pi.restrictedAccountType != null) {
3312 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07003313 }
3314 } else {
3315 // Otherwise check if the callingUid has a package that has opted in
3316 for (String packageName : packages) {
3317 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
3318 if (pi != null && pi.restrictedAccountType != null) {
3319 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07003320 break;
3321 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003322 }
3323 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003324 } catch (NameNotFoundException nnfe) {
3325 }
3326 for (Account account : unfiltered) {
3327 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003328 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003329 } else {
3330 boolean found = false;
3331 for (Account shared : sharedAccounts) {
3332 if (shared.equals(account)) {
3333 found = true;
3334 break;
3335 }
3336 }
3337 if (!found) {
3338 allowed.add(account);
3339 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003340 }
3341 }
3342 Account[] filtered = new Account[allowed.size()];
3343 allowed.toArray(filtered);
3344 return filtered;
3345 } else {
3346 return unfiltered;
3347 }
3348 }
3349
Amith Yamasani27db4682013-03-30 17:07:47 -07003350 /*
3351 * packageName can be null. If not null, it should be used to filter out restricted accounts
3352 * that the package is not allowed to access.
3353 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003354 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07003355 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003356 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003357 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003358 if (accounts == null) {
3359 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08003360 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003361 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07003362 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003363 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003364 } else {
3365 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003366 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003367 totalLength += accounts.length;
3368 }
3369 if (totalLength == 0) {
3370 return EMPTY_ACCOUNT_ARRAY;
3371 }
3372 Account[] accounts = new Account[totalLength];
3373 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003374 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003375 System.arraycopy(accountsOfType, 0, accounts, totalLength,
3376 accountsOfType.length);
3377 totalLength += accountsOfType.length;
3378 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003379 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003380 }
3381 }
3382
Amith Yamasani04e0d262012-02-14 11:50:53 -08003383 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3384 Account account, String key, String value) {
3385 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003386 if (userDataForAccount == null) {
3387 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003388 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003389 }
3390 if (value == null) {
3391 userDataForAccount.remove(key);
3392 } else {
3393 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003394 }
3395 }
3396
Amith Yamasani04e0d262012-02-14 11:50:53 -08003397 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3398 Account account, String key, String value) {
3399 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003400 if (authTokensForAccount == null) {
3401 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003402 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003403 }
3404 if (value == null) {
3405 authTokensForAccount.remove(key);
3406 } else {
3407 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003408 }
3409 }
3410
Amith Yamasani04e0d262012-02-14 11:50:53 -08003411 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
3412 String authTokenType) {
3413 synchronized (accounts.cacheLock) {
3414 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003415 if (authTokensForAccount == null) {
3416 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003417 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003418 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003419 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003420 }
3421 return authTokensForAccount.get(authTokenType);
3422 }
3423 }
3424
Amith Yamasani04e0d262012-02-14 11:50:53 -08003425 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
3426 synchronized (accounts.cacheLock) {
3427 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003428 if (userDataForAccount == null) {
3429 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003430 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003431 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003432 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003433 }
3434 return userDataForAccount.get(key);
3435 }
3436 }
3437
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003438 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3439 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003440 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003441 Cursor cursor = db.query(TABLE_EXTRAS,
3442 COLUMNS_EXTRAS_KEY_AND_VALUE,
3443 SELECTION_USERDATA_BY_ACCOUNT,
3444 new String[]{account.name, account.type},
3445 null, null, null);
3446 try {
3447 while (cursor.moveToNext()) {
3448 final String tmpkey = cursor.getString(0);
3449 final String value = cursor.getString(1);
3450 userDataForAccount.put(tmpkey, value);
3451 }
3452 } finally {
3453 cursor.close();
3454 }
3455 return userDataForAccount;
3456 }
3457
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003458 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3459 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003460 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003461 Cursor cursor = db.query(TABLE_AUTHTOKENS,
3462 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3463 SELECTION_AUTHTOKENS_BY_ACCOUNT,
3464 new String[]{account.name, account.type},
3465 null, null, null);
3466 try {
3467 while (cursor.moveToNext()) {
3468 final String type = cursor.getString(0);
3469 final String authToken = cursor.getString(1);
3470 authTokensForAccount.put(type, authToken);
3471 }
3472 } finally {
3473 cursor.close();
3474 }
3475 return authTokensForAccount;
3476 }
Fred Quintana60307342009-03-24 22:48:12 -07003477}