blob: 2b1a2b21c5a3e985e51143f3e4a65f4b20e7b527 [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
17package android.accounts;
18
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080020import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070021import android.app.ActivityManagerNative;
Doug Zongker885cfc232009-10-21 16:52:44 -070022import android.app.Notification;
23import android.app.NotificationManager;
24import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070025import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070026import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070031import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070032import android.content.pm.ApplicationInfo;
33import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070034import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070035import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070036import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070037import android.content.pm.RegisteredServicesCacheListener;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070038import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070039import android.database.Cursor;
40import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070041import android.database.sqlite.SQLiteDatabase;
42import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070043import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070044import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080045import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070046import android.os.Handler;
47import android.os.HandlerThread;
48import android.os.IBinder;
49import android.os.Looper;
50import android.os.Message;
51import android.os.RemoteException;
52import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070053import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070055import android.text.TextUtils;
56import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070057import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070058import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080059import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070060
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070061import com.android.internal.R;
Amith Yamasani04e0d262012-02-14 11:50:53 -080062import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070063import com.google.android.collect.Lists;
64import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070065
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070067import java.io.FileDescriptor;
68import java.io.PrintWriter;
69import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080070import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070071import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070072import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070073import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080074import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070075import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080076import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070077import java.util.concurrent.atomic.AtomicInteger;
78import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070079
Fred Quintana60307342009-03-24 22:48:12 -070080/**
81 * A system service that provides account, password, and authtoken management for all
82 * accounts on the device. Some of these calls are implemented with the help of the corresponding
83 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
84 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070085 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -070086 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070087 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070088public class AccountManagerService
89 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080090 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -070091 private static final String TAG = "AccountManagerService";
92
93 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
94 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070095 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070096
97 private final Context mContext;
98
Fred Quintana56285a62010-12-02 14:20:51 -080099 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700100 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800101
Fred Quintana60307342009-03-24 22:48:12 -0700102 private HandlerThread mMessageThread;
103 private final MessageHandler mMessageHandler;
104
105 // Messages that can be sent on mHandler
106 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700107
Fred Quintana56285a62010-12-02 14:20:51 -0800108 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700109
110 private static final String TABLE_ACCOUNTS = "accounts";
111 private static final String ACCOUNTS_ID = "_id";
112 private static final String ACCOUNTS_NAME = "name";
113 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700114 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700115 private static final String ACCOUNTS_PASSWORD = "password";
116
117 private static final String TABLE_AUTHTOKENS = "authtokens";
118 private static final String AUTHTOKENS_ID = "_id";
119 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
120 private static final String AUTHTOKENS_TYPE = "type";
121 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
122
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700123 private static final String TABLE_GRANTS = "grants";
124 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
125 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
126 private static final String GRANTS_GRANTEE_UID = "uid";
127
Fred Quintana60307342009-03-24 22:48:12 -0700128 private static final String TABLE_EXTRAS = "extras";
129 private static final String EXTRAS_ID = "_id";
130 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
131 private static final String EXTRAS_KEY = "key";
132 private static final String EXTRAS_VALUE = "value";
133
134 private static final String TABLE_META = "meta";
135 private static final String META_KEY = "key";
136 private static final String META_VALUE = "value";
137
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700138 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
139 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700140 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700141
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700142 private static final String COUNT_OF_MATCHING_GRANTS = ""
143 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
144 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
145 + " AND " + GRANTS_GRANTEE_UID + "=?"
146 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
147 + " AND " + ACCOUNTS_NAME + "=?"
148 + " AND " + ACCOUNTS_TYPE + "=?";
149
Fred Quintana56285a62010-12-02 14:20:51 -0800150 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
151 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
152 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
153 AUTHTOKENS_AUTHTOKEN};
154
155 private static final String SELECTION_USERDATA_BY_ACCOUNT =
156 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
157 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
158
Fred Quintanaa698f422009-04-08 19:14:54 -0700159 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700160 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
161
Amith Yamasani04e0d262012-02-14 11:50:53 -0800162 static class UserAccounts {
163 private final int userId;
164 private final DatabaseHelper openHelper;
165 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
166 credentialsPermissionNotificationIds =
167 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
168 private final HashMap<Account, Integer> signinRequiredNotificationIds =
169 new HashMap<Account, Integer>();
170 private final Object cacheLock = new Object();
171 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700172 private final HashMap<String, Account[]> accountCache =
173 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800174 /** protected by the {@link #cacheLock} */
175 private HashMap<Account, HashMap<String, String>> userDataCache =
176 new HashMap<Account, HashMap<String, String>>();
177 /** protected by the {@link #cacheLock} */
178 private HashMap<Account, HashMap<String, String>> authTokenCache =
179 new HashMap<Account, HashMap<String, String>>();
180
181 UserAccounts(Context context, int userId) {
182 this.userId = userId;
183 synchronized (cacheLock) {
184 openHelper = new DatabaseHelper(context, userId);
185 }
186 }
187 }
188
189 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
190
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700191 private static AtomicReference<AccountManagerService> sThis =
192 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700193 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700194
195 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700196 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700197 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
198 }
199
Fred Quintana56285a62010-12-02 14:20:51 -0800200
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700201 /**
202 * This should only be called by system code. One should only call this after the service
203 * has started.
204 * @return a reference to the AccountManagerService instance
205 * @hide
206 */
207 public static AccountManagerService getSingleton() {
208 return sThis.get();
209 }
Fred Quintana60307342009-03-24 22:48:12 -0700210
Fred Quintana56285a62010-12-02 14:20:51 -0800211 public AccountManagerService(Context context) {
212 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700213 }
214
Fred Quintana56285a62010-12-02 14:20:51 -0800215 public AccountManagerService(Context context, PackageManager packageManager,
216 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700217 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800218 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700219
Fred Quintana60307342009-03-24 22:48:12 -0700220 mMessageThread = new HandlerThread("AccountManagerService");
221 mMessageThread.start();
222 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
223
Fred Quintana56285a62010-12-02 14:20:51 -0800224 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800225 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700226
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700227 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800228
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800229 IntentFilter intentFilter = new IntentFilter();
230 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
231 intentFilter.addDataScheme("package");
232 mContext.registerReceiver(new BroadcastReceiver() {
233 @Override
234 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800235 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800236 }
237 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800238
Amith Yamasani13593602012-03-22 16:16:17 -0700239 IntentFilter userFilter = new IntentFilter();
240 userFilter.addAction(Intent.ACTION_USER_REMOVED);
241 mContext.registerReceiver(new BroadcastReceiver() {
242 @Override
243 public void onReceive(Context context, Intent intent) {
244 onUserRemoved(intent);
245 }
246 }, userFilter);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800247 }
248
Kenny Root26ff6622012-07-30 12:58:03 -0700249 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700250 }
251
Amith Yamasani258848d2012-08-10 17:06:33 -0700252 private UserManager getUserManager() {
253 if (mUserManager == null) {
254 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
255 }
256 return mUserManager;
257 }
258
Amith Yamasani04e0d262012-02-14 11:50:53 -0800259 private UserAccounts initUser(int userId) {
260 synchronized (mUsers) {
261 UserAccounts accounts = mUsers.get(userId);
262 if (accounts == null) {
263 accounts = new UserAccounts(mContext, userId);
264 mUsers.append(userId, accounts);
265 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700266 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800267 }
268 return accounts;
269 }
270 }
271
272 private void purgeOldGrantsAll() {
273 synchronized (mUsers) {
274 for (int i = 0; i < mUsers.size(); i++) {
275 purgeOldGrants(mUsers.valueAt(i));
276 }
277 }
278 }
279
280 private void purgeOldGrants(UserAccounts accounts) {
281 synchronized (accounts.cacheLock) {
282 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800283 final Cursor cursor = db.query(TABLE_GRANTS,
284 new String[]{GRANTS_GRANTEE_UID},
285 null, null, GRANTS_GRANTEE_UID, null, null);
286 try {
287 while (cursor.moveToNext()) {
288 final int uid = cursor.getInt(0);
289 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
290 if (packageExists) {
291 continue;
292 }
293 Log.d(TAG, "deleting grants for UID " + uid
294 + " because its package is no longer installed");
295 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
296 new String[]{Integer.toString(uid)});
297 }
298 } finally {
299 cursor.close();
300 }
301 }
302 }
303
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700304 /**
305 * Validate internal set of accounts against installed authenticators for
306 * given user. Clears cached authenticators before validating.
307 */
308 public void validateAccounts(int userId) {
309 final UserAccounts accounts = getUserAccounts(userId);
310
311 // Invalidate user-specific cache to make sure we catch any
312 // removed authenticators.
313 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
314 }
315
316 /**
317 * Validate internal set of accounts against installed authenticators for
318 * given user. Clear cached authenticators before validating when requested.
319 */
320 private void validateAccountsInternal(
321 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
322 if (invalidateAuthenticatorCache) {
323 mAuthenticatorCache.invalidateCache(accounts.userId);
324 }
325
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700326 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
327 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
328 mAuthenticatorCache.getAllServices(accounts.userId)) {
329 knownAuth.add(service.type);
330 }
331
Amith Yamasani04e0d262012-02-14 11:50:53 -0800332 synchronized (accounts.cacheLock) {
333 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800334 boolean accountDeleted = false;
335 Cursor cursor = db.query(TABLE_ACCOUNTS,
336 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
337 null, null, null, null, null);
338 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800339 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800340 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700341 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800342 while (cursor.moveToNext()) {
343 final long accountId = cursor.getLong(0);
344 final String accountType = cursor.getString(1);
345 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700346
347 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700348 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800349 + accountType + " no longer has a registered authenticator");
350 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
351 accountDeleted = true;
352 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800353 accounts.userDataCache.remove(account);
354 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800355 } else {
356 ArrayList<String> accountNames = accountNamesByType.get(accountType);
357 if (accountNames == null) {
358 accountNames = new ArrayList<String>();
359 accountNamesByType.put(accountType, accountNames);
360 }
361 accountNames.add(accountName);
362 }
363 }
Andy McFadden2f362292012-01-20 14:43:38 -0800364 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800365 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800366 final String accountType = cur.getKey();
367 final ArrayList<String> accountNames = cur.getValue();
368 final Account[] accountsForType = new Account[accountNames.size()];
369 int i = 0;
370 for (String accountName : accountNames) {
371 accountsForType[i] = new Account(accountName, accountType);
372 ++i;
373 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800374 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800375 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800376 } finally {
377 cursor.close();
378 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800379 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800380 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800381 }
382 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700383 }
384
Amith Yamasani04e0d262012-02-14 11:50:53 -0800385 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700386 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800387 }
388
389 protected UserAccounts getUserAccounts(int userId) {
390 synchronized (mUsers) {
391 UserAccounts accounts = mUsers.get(userId);
392 if (accounts == null) {
393 accounts = initUser(userId);
394 mUsers.append(userId, accounts);
395 }
396 return accounts;
397 }
398 }
399
Amith Yamasani13593602012-03-22 16:16:17 -0700400 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700401 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700402 if (userId < 1) return;
403
404 UserAccounts accounts;
405 synchronized (mUsers) {
406 accounts = mUsers.get(userId);
407 mUsers.remove(userId);
408 }
409 if (accounts == null) {
410 File dbFile = new File(getDatabaseName(userId));
411 dbFile.delete();
412 return;
413 }
414
415 synchronized (accounts.cacheLock) {
416 accounts.openHelper.close();
417 File dbFile = new File(getDatabaseName(userId));
418 dbFile.delete();
419 }
420 }
421
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700422 @Override
423 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700424 Slog.d(TAG, "onServiceChanged() for userId " + userId);
425 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700426 }
427
Fred Quintanaa698f422009-04-08 19:14:54 -0700428 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800429 if (Log.isLoggable(TAG, Log.VERBOSE)) {
430 Log.v(TAG, "getPassword: " + account
431 + ", caller's uid " + Binder.getCallingUid()
432 + ", pid " + Binder.getCallingPid());
433 }
Fred Quintana382601f2010-03-25 12:25:10 -0700434 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700435 checkAuthenticateAccountsPermission(account);
436
Amith Yamasani04e0d262012-02-14 11:50:53 -0800437 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700438 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700439 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800440 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700441 } finally {
442 restoreCallingIdentity(identityToken);
443 }
444 }
445
Amith Yamasani04e0d262012-02-14 11:50:53 -0800446 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700447 if (account == null) {
448 return null;
449 }
450
Amith Yamasani04e0d262012-02-14 11:50:53 -0800451 synchronized (accounts.cacheLock) {
452 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800453 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
454 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
455 new String[]{account.name, account.type}, null, null, null);
456 try {
457 if (cursor.moveToNext()) {
458 return cursor.getString(0);
459 }
460 return null;
461 } finally {
462 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700463 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700464 }
465 }
466
467 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800468 if (Log.isLoggable(TAG, Log.VERBOSE)) {
469 Log.v(TAG, "getUserData: " + account
470 + ", key " + key
471 + ", caller's uid " + Binder.getCallingUid()
472 + ", pid " + Binder.getCallingPid());
473 }
Fred Quintana382601f2010-03-25 12:25:10 -0700474 if (account == null) throw new IllegalArgumentException("account is null");
475 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700476 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800477 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700478 long identityToken = clearCallingIdentity();
479 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800480 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700481 } finally {
482 restoreCallingIdentity(identityToken);
483 }
484 }
485
Fred Quintana97889762009-06-15 12:29:24 -0700486 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800487 if (Log.isLoggable(TAG, Log.VERBOSE)) {
488 Log.v(TAG, "getAuthenticatorTypes: "
489 + "caller's uid " + Binder.getCallingUid()
490 + ", pid " + Binder.getCallingPid());
491 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700492 final int userId = UserHandle.getCallingUserId();
493 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700494 try {
Fred Quintana97889762009-06-15 12:29:24 -0700495 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700496 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700497 AuthenticatorDescription[] types =
498 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700499 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700500 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700501 : authenticatorCollection) {
502 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700503 i++;
504 }
505 return types;
506 } finally {
507 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700508 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700509 }
510
Fred Quintanaa698f422009-04-08 19:14:54 -0700511 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800512 if (Log.isLoggable(TAG, Log.VERBOSE)) {
513 Log.v(TAG, "addAccount: " + account
514 + ", caller's uid " + Binder.getCallingUid()
515 + ", pid " + Binder.getCallingPid());
516 }
Fred Quintana382601f2010-03-25 12:25:10 -0700517 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700518 checkAuthenticateAccountsPermission(account);
519
Amith Yamasani04e0d262012-02-14 11:50:53 -0800520 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700521 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700522 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700523 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800524 return addAccountInternal(accounts, account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700525 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700526 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700527 }
528 }
529
Amith Yamasani04e0d262012-02-14 11:50:53 -0800530 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
531 Bundle extras) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700532 if (account == null) {
533 return false;
534 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800535 synchronized (accounts.cacheLock) {
536 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800537 db.beginTransaction();
538 try {
539 long numMatches = DatabaseUtils.longForQuery(db,
540 "select count(*) from " + TABLE_ACCOUNTS
541 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
542 new String[]{account.name, account.type});
543 if (numMatches > 0) {
544 Log.w(TAG, "insertAccountIntoDatabase: " + account
545 + ", skipping since the account already exists");
546 return false;
547 }
548 ContentValues values = new ContentValues();
549 values.put(ACCOUNTS_NAME, account.name);
550 values.put(ACCOUNTS_TYPE, account.type);
551 values.put(ACCOUNTS_PASSWORD, password);
552 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
553 if (accountId < 0) {
554 Log.w(TAG, "insertAccountIntoDatabase: " + account
555 + ", skipping the DB insert failed");
556 return false;
557 }
558 if (extras != null) {
559 for (String key : extras.keySet()) {
560 final String value = extras.getString(key);
561 if (insertExtraLocked(db, accountId, key, value) < 0) {
562 Log.w(TAG, "insertAccountIntoDatabase: " + account
563 + ", skipping since insertExtra failed for key " + key);
564 return false;
565 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700566 }
567 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800568 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800569 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800570 } finally {
571 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700572 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800573 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800574 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700575 }
576 }
577
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800578 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700579 ContentValues values = new ContentValues();
580 values.put(EXTRAS_KEY, key);
581 values.put(EXTRAS_ACCOUNTS_ID, accountId);
582 values.put(EXTRAS_VALUE, value);
583 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
584 }
585
Fred Quintana3084a6f2010-01-14 18:02:03 -0800586 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800587 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800588 if (Log.isLoggable(TAG, Log.VERBOSE)) {
589 Log.v(TAG, "hasFeatures: " + account
590 + ", response " + response
591 + ", features " + stringArrayToString(features)
592 + ", caller's uid " + Binder.getCallingUid()
593 + ", pid " + Binder.getCallingPid());
594 }
Fred Quintana382601f2010-03-25 12:25:10 -0700595 if (response == null) throw new IllegalArgumentException("response is null");
596 if (account == null) throw new IllegalArgumentException("account is null");
597 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800598 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800599 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800600 long identityToken = clearCallingIdentity();
601 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800602 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800603 } finally {
604 restoreCallingIdentity(identityToken);
605 }
606 }
607
608 private class TestFeaturesSession extends Session {
609 private final String[] mFeatures;
610 private final Account mAccount;
611
Amith Yamasani04e0d262012-02-14 11:50:53 -0800612 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800613 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800614 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800615 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800616 mFeatures = features;
617 mAccount = account;
618 }
619
620 public void run() throws RemoteException {
621 try {
622 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
623 } catch (RemoteException e) {
624 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
625 }
626 }
627
628 public void onResult(Bundle result) {
629 IAccountManagerResponse response = getResponseAndClose();
630 if (response != null) {
631 try {
632 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700633 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800634 return;
635 }
Fred Quintana56285a62010-12-02 14:20:51 -0800636 if (Log.isLoggable(TAG, Log.VERBOSE)) {
637 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
638 + response);
639 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800640 final Bundle newResult = new Bundle();
641 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
642 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
643 response.onResult(newResult);
644 } catch (RemoteException e) {
645 // if the caller is dead then there is no one to care about remote exceptions
646 if (Log.isLoggable(TAG, Log.VERBOSE)) {
647 Log.v(TAG, "failure while notifying response", e);
648 }
649 }
650 }
651 }
652
653 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800654 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800655 + ", " + mAccount
656 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
657 }
658 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800659
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700660 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800661 if (Log.isLoggable(TAG, Log.VERBOSE)) {
662 Log.v(TAG, "removeAccount: " + account
663 + ", response " + response
664 + ", caller's uid " + Binder.getCallingUid()
665 + ", pid " + Binder.getCallingPid());
666 }
Fred Quintana382601f2010-03-25 12:25:10 -0700667 if (response == null) throw new IllegalArgumentException("response is null");
668 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700669 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700670 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800671 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700672 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800673
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700674 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800675 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800676 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800677 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800678 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800679 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700680 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800681 }
682 }
683 }
684
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700685 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800686 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700687 } finally {
688 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700689 }
Fred Quintana60307342009-03-24 22:48:12 -0700690 }
691
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700692 private class RemoveAccountSession extends Session {
693 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800694 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
695 Account account) {
696 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800697 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700698 mAccount = account;
699 }
700
701 protected String toDebugString(long now) {
702 return super.toDebugString(now) + ", removeAccount"
703 + ", account " + mAccount;
704 }
705
706 public void run() throws RemoteException {
707 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
708 }
709
710 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700711 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
712 && !result.containsKey(AccountManager.KEY_INTENT)) {
713 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700714 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800715 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700716 }
717 IAccountManagerResponse response = getResponseAndClose();
718 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800719 if (Log.isLoggable(TAG, Log.VERBOSE)) {
720 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
721 + response);
722 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700723 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700724 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700725 try {
726 response.onResult(result2);
727 } catch (RemoteException e) {
728 // ignore
729 }
730 }
731 }
732 super.onResult(result);
733 }
734 }
735
Amith Yamasani04e0d262012-02-14 11:50:53 -0800736 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800737 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800738 removeAccountInternal(getUserAccountsForCaller(), account);
739 }
740
741 private void removeAccountInternal(UserAccounts accounts, Account account) {
742 synchronized (accounts.cacheLock) {
743 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800744 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
745 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800746 removeAccountFromCacheLocked(accounts, account);
747 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800748 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700749 }
750
Fred Quintanaa698f422009-04-08 19:14:54 -0700751 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800752 if (Log.isLoggable(TAG, Log.VERBOSE)) {
753 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
754 + ", caller's uid " + Binder.getCallingUid()
755 + ", pid " + Binder.getCallingPid());
756 }
Fred Quintana382601f2010-03-25 12:25:10 -0700757 if (accountType == null) throw new IllegalArgumentException("accountType is null");
758 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800759 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800760 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700761 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700762 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800763 synchronized (accounts.cacheLock) {
764 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800765 db.beginTransaction();
766 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800767 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800768 db.setTransactionSuccessful();
769 } finally {
770 db.endTransaction();
771 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700772 }
Fred Quintana60307342009-03-24 22:48:12 -0700773 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700774 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700775 }
776 }
777
Amith Yamasani04e0d262012-02-14 11:50:53 -0800778 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
779 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700780 if (authToken == null || accountType == null) {
781 return;
782 }
Fred Quintana33269202009-04-20 16:05:10 -0700783 Cursor cursor = db.rawQuery(
784 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
785 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
786 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
787 + " FROM " + TABLE_ACCOUNTS
788 + " JOIN " + TABLE_AUTHTOKENS
789 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
790 + " = " + AUTHTOKENS_ACCOUNTS_ID
791 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
792 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
793 new String[]{authToken, accountType});
794 try {
795 while (cursor.moveToNext()) {
796 long authTokenId = cursor.getLong(0);
797 String accountName = cursor.getString(1);
798 String authTokenType = cursor.getString(2);
799 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800800 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800801 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700802 }
Fred Quintana33269202009-04-20 16:05:10 -0700803 } finally {
804 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700805 }
806 }
807
Amith Yamasani04e0d262012-02-14 11:50:53 -0800808 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
809 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700810 if (account == null || type == null) {
811 return false;
812 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700813 cancelNotification(getSigninRequiredNotificationId(accounts, account),
814 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800815 synchronized (accounts.cacheLock) {
816 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800817 db.beginTransaction();
818 try {
819 long accountId = getAccountIdLocked(db, account);
820 if (accountId < 0) {
821 return false;
822 }
823 db.delete(TABLE_AUTHTOKENS,
824 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
825 new String[]{type});
826 ContentValues values = new ContentValues();
827 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
828 values.put(AUTHTOKENS_TYPE, type);
829 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
830 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
831 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800832 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800833 return true;
834 }
Fred Quintana33269202009-04-20 16:05:10 -0700835 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800836 } finally {
837 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -0700838 }
Fred Quintana60307342009-03-24 22:48:12 -0700839 }
840 }
841
Fred Quintanaa698f422009-04-08 19:14:54 -0700842 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800843 if (Log.isLoggable(TAG, Log.VERBOSE)) {
844 Log.v(TAG, "peekAuthToken: " + account
845 + ", authTokenType " + authTokenType
846 + ", caller's uid " + Binder.getCallingUid()
847 + ", pid " + Binder.getCallingPid());
848 }
Fred Quintana382601f2010-03-25 12:25:10 -0700849 if (account == null) throw new IllegalArgumentException("account is null");
850 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700851 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800852 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700853 long identityToken = clearCallingIdentity();
854 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800855 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700856 } finally {
857 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700858 }
Fred Quintana60307342009-03-24 22:48:12 -0700859 }
860
Fred Quintanaa698f422009-04-08 19:14:54 -0700861 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800862 if (Log.isLoggable(TAG, Log.VERBOSE)) {
863 Log.v(TAG, "setAuthToken: " + account
864 + ", authTokenType " + authTokenType
865 + ", caller's uid " + Binder.getCallingUid()
866 + ", pid " + Binder.getCallingPid());
867 }
Fred Quintana382601f2010-03-25 12:25:10 -0700868 if (account == null) throw new IllegalArgumentException("account is null");
869 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700870 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800871 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700872 long identityToken = clearCallingIdentity();
873 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800874 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700875 } finally {
876 restoreCallingIdentity(identityToken);
877 }
Fred Quintana60307342009-03-24 22:48:12 -0700878 }
879
Fred Quintanaa698f422009-04-08 19:14:54 -0700880 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -0800881 if (Log.isLoggable(TAG, Log.VERBOSE)) {
882 Log.v(TAG, "setAuthToken: " + account
883 + ", caller's uid " + Binder.getCallingUid()
884 + ", pid " + Binder.getCallingPid());
885 }
Fred Quintana382601f2010-03-25 12:25:10 -0700886 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700887 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800888 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700889 long identityToken = clearCallingIdentity();
890 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800891 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700892 } finally {
893 restoreCallingIdentity(identityToken);
894 }
Fred Quintana60307342009-03-24 22:48:12 -0700895 }
896
Amith Yamasani04e0d262012-02-14 11:50:53 -0800897 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700898 if (account == null) {
899 return;
900 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800901 synchronized (accounts.cacheLock) {
902 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800903 db.beginTransaction();
904 try {
905 final ContentValues values = new ContentValues();
906 values.put(ACCOUNTS_PASSWORD, password);
907 final long accountId = getAccountIdLocked(db, account);
908 if (accountId >= 0) {
909 final String[] argsAccountId = {String.valueOf(accountId)};
910 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
911 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800912 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800913 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -0800914 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800915 } finally {
916 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800917 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800918 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800919 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700920 }
921
Amith Yamasani04e0d262012-02-14 11:50:53 -0800922 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800923 Log.i(TAG, "the accounts changed, sending broadcast of "
924 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700925 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -0700926 }
927
Fred Quintanaa698f422009-04-08 19:14:54 -0700928 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800929 if (Log.isLoggable(TAG, Log.VERBOSE)) {
930 Log.v(TAG, "clearPassword: " + account
931 + ", caller's uid " + Binder.getCallingUid()
932 + ", pid " + Binder.getCallingPid());
933 }
Fred Quintana382601f2010-03-25 12:25:10 -0700934 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700935 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800936 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700937 long identityToken = clearCallingIdentity();
938 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800939 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700940 } finally {
941 restoreCallingIdentity(identityToken);
942 }
Fred Quintana60307342009-03-24 22:48:12 -0700943 }
944
Fred Quintanaa698f422009-04-08 19:14:54 -0700945 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -0800946 if (Log.isLoggable(TAG, Log.VERBOSE)) {
947 Log.v(TAG, "setUserData: " + account
948 + ", key " + key
949 + ", caller's uid " + Binder.getCallingUid()
950 + ", pid " + Binder.getCallingPid());
951 }
Fred Quintana382601f2010-03-25 12:25:10 -0700952 if (key == null) throw new IllegalArgumentException("key is null");
953 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700954 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800955 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700956 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700957 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800958 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700959 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700960 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700961 }
962 }
963
Amith Yamasani04e0d262012-02-14 11:50:53 -0800964 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
965 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700966 if (account == null || key == null) {
967 return;
968 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800969 synchronized (accounts.cacheLock) {
970 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800971 db.beginTransaction();
972 try {
973 long accountId = getAccountIdLocked(db, account);
974 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700975 return;
976 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800977 long extrasId = getExtrasIdLocked(db, accountId, key);
978 if (extrasId < 0 ) {
979 extrasId = insertExtraLocked(db, accountId, key, value);
980 if (extrasId < 0) {
981 return;
982 }
983 } else {
984 ContentValues values = new ContentValues();
985 values.put(EXTRAS_VALUE, value);
986 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
987 return;
988 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700989
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800990 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800991 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800992 db.setTransactionSuccessful();
993 } finally {
994 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700995 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700996 }
997 }
998
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700999 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001000 if (result == null) {
1001 Log.e(TAG, "the result is unexpectedly null", new Exception());
1002 }
1003 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1004 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1005 + response);
1006 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001007 try {
1008 response.onResult(result);
1009 } catch (RemoteException e) {
1010 // if the caller is dead then there is no one to care about remote
1011 // exceptions
1012 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1013 Log.v(TAG, "failure while notifying response", e);
1014 }
1015 }
1016 }
1017
Fred Quintanad9640ec2012-05-23 12:37:00 -07001018 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1019 final String authTokenType)
1020 throws RemoteException {
1021 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001022 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1023
Fred Quintanad9640ec2012-05-23 12:37:00 -07001024 final int callingUid = getCallingUid();
1025 clearCallingIdentity();
1026 if (callingUid != android.os.Process.SYSTEM_UID) {
1027 throw new SecurityException("can only call from system");
1028 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001029 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001030 long identityToken = clearCallingIdentity();
1031 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001032 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001033 false /* stripAuthTokenFromResult */) {
1034 protected String toDebugString(long now) {
1035 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001036 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001037 + ", authTokenType " + authTokenType;
1038 }
1039
1040 public void run() throws RemoteException {
1041 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1042 }
1043
1044 public void onResult(Bundle result) {
1045 if (result != null) {
1046 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1047 Bundle bundle = new Bundle();
1048 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1049 super.onResult(bundle);
1050 return;
1051 } else {
1052 super.onResult(result);
1053 }
1054 }
1055 }.bind();
1056 } finally {
1057 restoreCallingIdentity(identityToken);
1058 }
1059 }
1060
Fred Quintanaa698f422009-04-08 19:14:54 -07001061 public void getAuthToken(IAccountManagerResponse response, final Account account,
1062 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001063 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001064 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1065 Log.v(TAG, "getAuthToken: " + account
1066 + ", response " + response
1067 + ", authTokenType " + authTokenType
1068 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1069 + ", expectActivityLaunch " + expectActivityLaunch
1070 + ", caller's uid " + Binder.getCallingUid()
1071 + ", pid " + Binder.getCallingPid());
1072 }
Fred Quintana382601f2010-03-25 12:25:10 -07001073 if (response == null) throw new IllegalArgumentException("response is null");
1074 if (account == null) throw new IllegalArgumentException("account is null");
1075 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001076 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001077 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001078 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1079 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1080 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001081 final boolean customTokens =
1082 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1083
1084 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001085 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001086 final boolean permissionGranted = customTokens ||
1087 permissionIsGranted(account, authTokenType, callerUid);
1088
Costin Manolachec6684f92011-01-14 11:25:39 -08001089 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1090 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001091 // let authenticator know the identity of the caller
1092 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1093 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1094 if (notifyOnAuthFailure) {
1095 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001096 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001097
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001098 long identityToken = clearCallingIdentity();
1099 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001100 // if the caller has permission, do the peek. otherwise go the more expensive
1101 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001102 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001103 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001104 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001105 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001106 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1107 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1108 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001109 onResult(response, result);
1110 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001111 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001112 }
1113
Amith Yamasani04e0d262012-02-14 11:50:53 -08001114 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001115 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001116 protected String toDebugString(long now) {
1117 if (loginOptions != null) loginOptions.keySet();
1118 return super.toDebugString(now) + ", getAuthToken"
1119 + ", " + account
1120 + ", authTokenType " + authTokenType
1121 + ", loginOptions " + loginOptions
1122 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1123 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001124
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001125 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001126 // If the caller doesn't have permission then create and return the
1127 // "grant permission" intent instead of the "getAuthToken" intent.
1128 if (!permissionGranted) {
1129 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1130 } else {
1131 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1132 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001133 }
1134
1135 public void onResult(Bundle result) {
1136 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001137 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001138 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1139 new AccountAuthenticatorResponse(this),
1140 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001141 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001142 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001143 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001144 onResult(bundle);
1145 return;
1146 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001147 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001148 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001149 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1150 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001151 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001152 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001153 "the type and name should not be empty");
1154 return;
1155 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001156 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001157 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001158 authTokenType, authToken);
1159 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001160 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001161
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001162 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001163 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001164 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001165 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001166 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001167 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001168 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001169 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001170 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001171 }.bind();
1172 } finally {
1173 restoreCallingIdentity(identityToken);
1174 }
Fred Quintana60307342009-03-24 22:48:12 -07001175 }
1176
Dianne Hackborn41203752012-08-31 14:05:51 -07001177 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1178 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001179 int uid = intent.getIntExtra(
1180 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1181 String authTokenType = intent.getStringExtra(
1182 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1183 String authTokenLabel = intent.getStringExtra(
1184 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1185
1186 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1187 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001188 final String titleAndSubtitle =
1189 mContext.getString(R.string.permission_request_notification_with_subtitle,
1190 account.name);
1191 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001192 String title = titleAndSubtitle;
1193 String subtitle = "";
1194 if (index > 0) {
1195 title = titleAndSubtitle.substring(0, index);
1196 subtitle = titleAndSubtitle.substring(index + 1);
1197 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001198 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001199 n.setLatestEventInfo(mContext, title, subtitle,
1200 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001201 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1202 installNotification(getCredentialPermissionNotificationId(
1203 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001204 }
1205
Costin Manolache5f383ad92010-12-02 16:44:46 -08001206 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1207 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001208
1209 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001210 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001211 // Since it was set in Eclair+ we can't change it without breaking apps using
1212 // the intent from a non-Activity context.
1213 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001214 intent.addCategory(
1215 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001216
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001217 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001218 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1219 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001220 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001221
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001222 return intent;
1223 }
1224
1225 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1226 int uid) {
1227 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001228 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001229 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001230 final Pair<Pair<Account, String>, Integer> key =
1231 new Pair<Pair<Account, String>, Integer>(
1232 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001233 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001234 if (id == null) {
1235 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001236 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001237 }
1238 }
1239 return id;
1240 }
1241
Amith Yamasani04e0d262012-02-14 11:50:53 -08001242 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001243 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001244 synchronized (accounts.signinRequiredNotificationIds) {
1245 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001246 if (id == null) {
1247 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001248 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001249 }
1250 }
1251 return id;
1252 }
1253
Fred Quintana33269202009-04-20 16:05:10 -07001254 public void addAcount(final IAccountManagerResponse response, final String accountType,
1255 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001256 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001257 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1258 Log.v(TAG, "addAccount: accountType " + accountType
1259 + ", response " + response
1260 + ", authTokenType " + authTokenType
1261 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1262 + ", expectActivityLaunch " + expectActivityLaunch
1263 + ", caller's uid " + Binder.getCallingUid()
1264 + ", pid " + Binder.getCallingPid());
1265 }
Fred Quintana382601f2010-03-25 12:25:10 -07001266 if (response == null) throw new IllegalArgumentException("response is null");
1267 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001268 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001269
Amith Yamasani04e0d262012-02-14 11:50:53 -08001270 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001271 final int pid = Binder.getCallingPid();
1272 final int uid = Binder.getCallingUid();
1273 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1274 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1275 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1276
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001277 long identityToken = clearCallingIdentity();
1278 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001279 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001280 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001281 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001282 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001283 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001284 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001285
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001286 protected String toDebugString(long now) {
1287 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001288 + ", accountType " + accountType
1289 + ", requiredFeatures "
1290 + (requiredFeatures != null
1291 ? TextUtils.join(",", requiredFeatures)
1292 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001293 }
1294 }.bind();
1295 } finally {
1296 restoreCallingIdentity(identityToken);
1297 }
Fred Quintana60307342009-03-24 22:48:12 -07001298 }
1299
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001300 @Override
1301 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1302 final Account account, final Bundle options, final boolean expectActivityLaunch,
1303 int userId) {
1304 // Only allow the system process to read accounts of other users
1305 if (userId != UserHandle.getCallingUserId()
1306 && Binder.getCallingUid() != android.os.Process.myUid()) {
1307 throw new SecurityException("User " + UserHandle.getCallingUserId()
1308 + " trying to confirm account credentials for " + userId);
1309 }
1310
Fred Quintana56285a62010-12-02 14:20:51 -08001311 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1312 Log.v(TAG, "confirmCredentials: " + account
1313 + ", response " + response
1314 + ", expectActivityLaunch " + expectActivityLaunch
1315 + ", caller's uid " + Binder.getCallingUid()
1316 + ", pid " + Binder.getCallingPid());
1317 }
Fred Quintana382601f2010-03-25 12:25:10 -07001318 if (response == null) throw new IllegalArgumentException("response is null");
1319 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001320 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001321 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001322 long identityToken = clearCallingIdentity();
1323 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001324 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001325 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001326 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001327 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001328 }
1329 protected String toDebugString(long now) {
1330 return super.toDebugString(now) + ", confirmCredentials"
1331 + ", " + account;
1332 }
1333 }.bind();
1334 } finally {
1335 restoreCallingIdentity(identityToken);
1336 }
Fred Quintana60307342009-03-24 22:48:12 -07001337 }
1338
Fred Quintanaa698f422009-04-08 19:14:54 -07001339 public void updateCredentials(IAccountManagerResponse response, final Account account,
1340 final String authTokenType, final boolean expectActivityLaunch,
1341 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001342 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1343 Log.v(TAG, "updateCredentials: " + account
1344 + ", response " + response
1345 + ", authTokenType " + authTokenType
1346 + ", expectActivityLaunch " + expectActivityLaunch
1347 + ", caller's uid " + Binder.getCallingUid()
1348 + ", pid " + Binder.getCallingPid());
1349 }
Fred Quintana382601f2010-03-25 12:25:10 -07001350 if (response == null) throw new IllegalArgumentException("response is null");
1351 if (account == null) throw new IllegalArgumentException("account is null");
1352 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001353 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001354 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001355 long identityToken = clearCallingIdentity();
1356 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001357 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001358 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001359 public void run() throws RemoteException {
1360 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1361 }
1362 protected String toDebugString(long now) {
1363 if (loginOptions != null) loginOptions.keySet();
1364 return super.toDebugString(now) + ", updateCredentials"
1365 + ", " + account
1366 + ", authTokenType " + authTokenType
1367 + ", loginOptions " + loginOptions;
1368 }
1369 }.bind();
1370 } finally {
1371 restoreCallingIdentity(identityToken);
1372 }
Fred Quintana60307342009-03-24 22:48:12 -07001373 }
1374
Fred Quintanaa698f422009-04-08 19:14:54 -07001375 public void editProperties(IAccountManagerResponse response, final String accountType,
1376 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001377 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1378 Log.v(TAG, "editProperties: accountType " + accountType
1379 + ", response " + response
1380 + ", expectActivityLaunch " + expectActivityLaunch
1381 + ", caller's uid " + Binder.getCallingUid()
1382 + ", pid " + Binder.getCallingPid());
1383 }
Fred Quintana382601f2010-03-25 12:25:10 -07001384 if (response == null) throw new IllegalArgumentException("response is null");
1385 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001386 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001387 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001388 long identityToken = clearCallingIdentity();
1389 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001390 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001391 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001392 public void run() throws RemoteException {
1393 mAuthenticator.editProperties(this, mAccountType);
1394 }
1395 protected String toDebugString(long now) {
1396 return super.toDebugString(now) + ", editProperties"
1397 + ", accountType " + accountType;
1398 }
1399 }.bind();
1400 } finally {
1401 restoreCallingIdentity(identityToken);
1402 }
Fred Quintana60307342009-03-24 22:48:12 -07001403 }
1404
Fred Quintana33269202009-04-20 16:05:10 -07001405 private class GetAccountsByTypeAndFeatureSession extends Session {
1406 private final String[] mFeatures;
1407 private volatile Account[] mAccountsOfType = null;
1408 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1409 private volatile int mCurrentAccount = 0;
1410
Amith Yamasani04e0d262012-02-14 11:50:53 -08001411 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
1412 IAccountManagerResponse response, String type, String[] features) {
1413 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001414 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001415 mFeatures = features;
1416 }
1417
1418 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001419 synchronized (mAccounts.cacheLock) {
1420 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001421 }
Fred Quintana33269202009-04-20 16:05:10 -07001422 // check whether each account matches the requested features
1423 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1424 mCurrentAccount = 0;
1425
1426 checkAccount();
1427 }
1428
1429 public void checkAccount() {
1430 if (mCurrentAccount >= mAccountsOfType.length) {
1431 sendResult();
1432 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001433 }
Fred Quintana33269202009-04-20 16:05:10 -07001434
Fred Quintana29e94b82010-03-10 12:11:51 -08001435 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1436 if (accountAuthenticator == null) {
1437 // It is possible that the authenticator has died, which is indicated by
1438 // mAuthenticator being set to null. If this happens then just abort.
1439 // There is no need to send back a result or error in this case since
1440 // that already happened when mAuthenticator was cleared.
1441 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1442 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1443 + " connected to the authenticator, " + toDebugString());
1444 }
1445 return;
1446 }
Fred Quintana33269202009-04-20 16:05:10 -07001447 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001448 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001449 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001450 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001451 }
1452 }
1453
1454 public void onResult(Bundle result) {
1455 mNumResults++;
1456 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001457 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001458 return;
1459 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001460 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001461 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1462 }
1463 mCurrentAccount++;
1464 checkAccount();
1465 }
1466
1467 public void sendResult() {
1468 IAccountManagerResponse response = getResponseAndClose();
1469 if (response != null) {
1470 try {
1471 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1472 for (int i = 0; i < accounts.length; i++) {
1473 accounts[i] = mAccountsWithFeatures.get(i);
1474 }
Fred Quintana56285a62010-12-02 14:20:51 -08001475 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1476 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1477 + response);
1478 }
Fred Quintana33269202009-04-20 16:05:10 -07001479 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001480 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001481 response.onResult(result);
1482 } catch (RemoteException e) {
1483 // if the caller is dead then there is no one to care about remote exceptions
1484 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1485 Log.v(TAG, "failure while notifying response", e);
1486 }
1487 }
1488 }
1489 }
1490
1491
1492 protected String toDebugString(long now) {
1493 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1494 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1495 }
1496 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001497
Amith Yamasani04e0d262012-02-14 11:50:53 -08001498 /**
1499 * Returns the accounts for a specific user
1500 * @hide
1501 */
1502 public Account[] getAccounts(int userId) {
1503 checkReadAccountsPermission();
1504 UserAccounts accounts = getUserAccounts(userId);
1505 long identityToken = clearCallingIdentity();
1506 try {
1507 synchronized (accounts.cacheLock) {
1508 return getAccountsFromCacheLocked(accounts, null);
1509 }
1510 } finally {
1511 restoreCallingIdentity(identityToken);
1512 }
1513 }
1514
Amith Yamasanif29f2362012-04-05 18:29:52 -07001515 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001516 * Returns accounts for all running users.
1517 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001518 * @hide
1519 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001520 public AccountAndUser[] getRunningAccounts() {
1521 final int[] runningUserIds;
1522 try {
1523 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1524 } catch (RemoteException e) {
1525 // Running in system_server; should never happen
1526 throw new RuntimeException(e);
1527 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001528 return getAccounts(runningUserIds);
1529 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001530
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001531 /** {@hide} */
1532 public AccountAndUser[] getAllAccounts() {
1533 final List<UserInfo> users = getUserManager().getUsers();
1534 final int[] userIds = new int[users.size()];
1535 for (int i = 0; i < userIds.length; i++) {
1536 userIds[i] = users.get(i).id;
1537 }
1538 return getAccounts(userIds);
1539 }
1540
1541 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001542 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1543 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001544 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001545 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001546 if (userAccounts == null) continue;
1547 synchronized (userAccounts.cacheLock) {
1548 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null);
1549 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001550 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001551 }
1552 }
1553 }
1554 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001555
1556 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1557 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001558 }
1559
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001560 @Override
1561 public Account[] getAccountsAsUser(String type, int userId) {
1562 // Only allow the system process to read accounts of other users
1563 if (userId != UserHandle.getCallingUserId()
1564 && Binder.getCallingUid() != android.os.Process.myUid()) {
1565 throw new SecurityException("User " + UserHandle.getCallingUserId()
1566 + " trying to get account for " + userId);
1567 }
1568
Fred Quintana56285a62010-12-02 14:20:51 -08001569 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1570 Log.v(TAG, "getAccounts: accountType " + type
1571 + ", caller's uid " + Binder.getCallingUid()
1572 + ", pid " + Binder.getCallingPid());
1573 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001574 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001575 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001576 long identityToken = clearCallingIdentity();
1577 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001578 synchronized (accounts.cacheLock) {
1579 return getAccountsFromCacheLocked(accounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001580 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001581 } finally {
1582 restoreCallingIdentity(identityToken);
1583 }
1584 }
1585
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001586 @Override
1587 public Account[] getAccounts(String type) {
1588 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1589 }
1590
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001591 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001592 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001593 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1594 Log.v(TAG, "getAccounts: accountType " + type
1595 + ", response " + response
1596 + ", features " + stringArrayToString(features)
1597 + ", caller's uid " + Binder.getCallingUid()
1598 + ", pid " + Binder.getCallingPid());
1599 }
Fred Quintana382601f2010-03-25 12:25:10 -07001600 if (response == null) throw new IllegalArgumentException("response is null");
1601 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001602 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001603 UserAccounts userAccounts = getUserAccountsForCaller();
Fred Quintana33269202009-04-20 16:05:10 -07001604 long identityToken = clearCallingIdentity();
1605 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001606 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001607 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001608 synchronized (userAccounts.cacheLock) {
1609 accounts = getAccountsFromCacheLocked(userAccounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001610 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001611 Bundle result = new Bundle();
1612 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1613 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001614 return;
1615 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001616 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001617 } finally {
1618 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001619 }
1620 }
1621
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001622 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001623 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001624 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001625 try {
1626 if (cursor.moveToNext()) {
1627 return cursor.getLong(0);
1628 }
1629 return -1;
1630 } finally {
1631 cursor.close();
1632 }
1633 }
1634
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001635 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001636 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1637 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1638 new String[]{key}, null, null, null);
1639 try {
1640 if (cursor.moveToNext()) {
1641 return cursor.getLong(0);
1642 }
1643 return -1;
1644 } finally {
1645 cursor.close();
1646 }
1647 }
1648
Fred Quintanaa698f422009-04-08 19:14:54 -07001649 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001650 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001651 IAccountManagerResponse mResponse;
1652 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001653 final boolean mExpectActivityLaunch;
1654 final long mCreationTime;
1655
Fred Quintana33269202009-04-20 16:05:10 -07001656 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001657 private int mNumRequestContinued = 0;
1658 private int mNumErrors = 0;
1659
Fred Quintana60307342009-03-24 22:48:12 -07001660
1661 IAccountAuthenticator mAuthenticator = null;
1662
Fred Quintana8570f742010-02-18 10:32:54 -08001663 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001664 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001665
Amith Yamasani04e0d262012-02-14 11:50:53 -08001666 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001667 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001668 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001669 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001670 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001671 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001672 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001673 mResponse = response;
1674 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001675 mExpectActivityLaunch = expectActivityLaunch;
1676 mCreationTime = SystemClock.elapsedRealtime();
1677 synchronized (mSessions) {
1678 mSessions.put(toString(), this);
1679 }
1680 try {
1681 response.asBinder().linkToDeath(this, 0 /* flags */);
1682 } catch (RemoteException e) {
1683 mResponse = null;
1684 binderDied();
1685 }
Fred Quintana60307342009-03-24 22:48:12 -07001686 }
1687
Fred Quintanaa698f422009-04-08 19:14:54 -07001688 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001689 if (mResponse == null) {
1690 // this session has already been closed
1691 return null;
1692 }
Fred Quintana60307342009-03-24 22:48:12 -07001693 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001694 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001695 return response;
1696 }
1697
Fred Quintanaa698f422009-04-08 19:14:54 -07001698 private void close() {
1699 synchronized (mSessions) {
1700 if (mSessions.remove(toString()) == null) {
1701 // the session was already closed, so bail out now
1702 return;
1703 }
1704 }
1705 if (mResponse != null) {
1706 // stop listening for response deaths
1707 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1708
1709 // clear this so that we don't accidentally send any further results
1710 mResponse = null;
1711 }
1712 cancelTimeout();
1713 unbind();
1714 }
1715
1716 public void binderDied() {
1717 mResponse = null;
1718 close();
1719 }
1720
1721 protected String toDebugString() {
1722 return toDebugString(SystemClock.elapsedRealtime());
1723 }
1724
1725 protected String toDebugString(long now) {
1726 return "Session: expectLaunch " + mExpectActivityLaunch
1727 + ", connected " + (mAuthenticator != null)
1728 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1729 + "/" + mNumErrors + ")"
1730 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1731 }
1732
Fred Quintana60307342009-03-24 22:48:12 -07001733 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001734 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1735 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1736 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001737 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001738 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001739 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001740 }
1741 }
1742
1743 private void unbind() {
1744 if (mAuthenticator != null) {
1745 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001746 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001747 }
1748 }
1749
1750 public void scheduleTimeout() {
1751 mMessageHandler.sendMessageDelayed(
1752 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1753 }
1754
1755 public void cancelTimeout() {
1756 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1757 }
1758
Fred Quintanab839afc2009-10-14 15:57:28 -07001759 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001760 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001761 try {
1762 run();
1763 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001764 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001765 "remote exception");
1766 }
Fred Quintana60307342009-03-24 22:48:12 -07001767 }
1768
Fred Quintanab839afc2009-10-14 15:57:28 -07001769 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001770 mAuthenticator = null;
1771 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001772 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001773 try {
1774 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1775 "disconnected");
1776 } catch (RemoteException e) {
1777 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1778 Log.v(TAG, "Session.onServiceDisconnected: "
1779 + "caught RemoteException while responding", e);
1780 }
1781 }
Fred Quintana60307342009-03-24 22:48:12 -07001782 }
1783 }
1784
Fred Quintanab839afc2009-10-14 15:57:28 -07001785 public abstract void run() throws RemoteException;
1786
Fred Quintana60307342009-03-24 22:48:12 -07001787 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001788 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001789 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001790 try {
1791 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1792 "timeout");
1793 } catch (RemoteException e) {
1794 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1795 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
1796 e);
1797 }
1798 }
Fred Quintana60307342009-03-24 22:48:12 -07001799 }
1800 }
1801
Fred Quintanaa698f422009-04-08 19:14:54 -07001802 public void onResult(Bundle result) {
1803 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001804 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1805 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1806 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001807 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1808 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001809 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
1810 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001811 }
Fred Quintana60307342009-03-24 22:48:12 -07001812 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001813 IAccountManagerResponse response;
1814 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001815 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001816 response = mResponse;
1817 } else {
1818 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001819 }
Fred Quintana60307342009-03-24 22:48:12 -07001820 if (response != null) {
1821 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001822 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001823 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1824 Log.v(TAG, getClass().getSimpleName()
1825 + " calling onError() on response " + response);
1826 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001827 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001828 "null bundle returned");
1829 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001830 if (mStripAuthTokenFromResult) {
1831 result.remove(AccountManager.KEY_AUTHTOKEN);
1832 }
Fred Quintana56285a62010-12-02 14:20:51 -08001833 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1834 Log.v(TAG, getClass().getSimpleName()
1835 + " calling onResult() on response " + response);
1836 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001837 response.onResult(result);
1838 }
Fred Quintana60307342009-03-24 22:48:12 -07001839 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001840 // if the caller is dead then there is no one to care about remote exceptions
1841 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1842 Log.v(TAG, "failure while notifying response", e);
1843 }
Fred Quintana60307342009-03-24 22:48:12 -07001844 }
1845 }
1846 }
Fred Quintana60307342009-03-24 22:48:12 -07001847
Fred Quintanaa698f422009-04-08 19:14:54 -07001848 public void onRequestContinued() {
1849 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001850 }
1851
1852 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001853 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001854 IAccountManagerResponse response = getResponseAndClose();
1855 if (response != null) {
1856 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001857 Log.v(TAG, getClass().getSimpleName()
1858 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001859 }
1860 try {
1861 response.onError(errorCode, errorMessage);
1862 } catch (RemoteException e) {
1863 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1864 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1865 }
1866 }
1867 } else {
1868 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1869 Log.v(TAG, "Session.onError: already closed");
1870 }
Fred Quintana60307342009-03-24 22:48:12 -07001871 }
1872 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001873
1874 /**
1875 * find the component name for the authenticator and initiate a bind
1876 * if no authenticator or the bind fails then return false, otherwise return true
1877 */
1878 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001879 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1880 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1881 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07001882 if (authenticatorInfo == null) {
1883 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1884 Log.v(TAG, "there is no authenticator for " + authenticatorType
1885 + ", bailing out");
1886 }
1887 return false;
1888 }
1889
1890 Intent intent = new Intent();
1891 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1892 intent.setComponent(authenticatorInfo.componentName);
1893 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1894 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1895 }
Amith Yamasani34daa752012-03-19 16:14:23 -07001896 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE, mAccounts.userId)) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001897 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1898 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1899 }
1900 return false;
1901 }
1902
1903
1904 return true;
1905 }
Fred Quintana60307342009-03-24 22:48:12 -07001906 }
1907
1908 private class MessageHandler extends Handler {
1909 MessageHandler(Looper looper) {
1910 super(looper);
1911 }
Costin Manolache3348f142009-09-29 18:58:36 -07001912
Fred Quintana60307342009-03-24 22:48:12 -07001913 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001914 switch (msg.what) {
1915 case MESSAGE_TIMED_OUT:
1916 Session session = (Session)msg.obj;
1917 session.onTimedOut();
1918 break;
1919
1920 default:
1921 throw new IllegalStateException("unhandled message: " + msg.what);
1922 }
1923 }
1924 }
1925
Amith Yamasani04e0d262012-02-14 11:50:53 -08001926 private static String getDatabaseName(int userId) {
1927 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07001928 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001929 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07001930 // Migrate old file, if it exists, to the new location.
1931 // Make sure the new file doesn't already exist. A dummy file could have been
1932 // accidentally created in the old location, causing the new one to become corrupted
1933 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08001934 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07001935 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07001936 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07001937 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07001938 if (!userDir.exists()) {
1939 if (!userDir.mkdirs()) {
1940 throw new IllegalStateException("User dir cannot be created: " + userDir);
1941 }
1942 }
1943 if (!oldFile.renameTo(databaseFile)) {
1944 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
1945 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001946 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08001947 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001948 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08001949 }
1950
Amith Yamasani04e0d262012-02-14 11:50:53 -08001951 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001952
Amith Yamasani04e0d262012-02-14 11:50:53 -08001953 public DatabaseHelper(Context context, int userId) {
1954 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001955 }
1956
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001957 /**
1958 * This call needs to be made while the mCacheLock is held. The way to
1959 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
1960 * @param db The database.
1961 */
Fred Quintana60307342009-03-24 22:48:12 -07001962 @Override
1963 public void onCreate(SQLiteDatabase db) {
1964 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1965 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1966 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1967 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1968 + ACCOUNTS_PASSWORD + " TEXT, "
1969 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1970
1971 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1972 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1973 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1974 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1975 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1976 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1977
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001978 createGrantsTable(db);
1979
Fred Quintana60307342009-03-24 22:48:12 -07001980 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1981 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1982 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1983 + EXTRAS_KEY + " TEXT NOT NULL, "
1984 + EXTRAS_VALUE + " TEXT, "
1985 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1986
1987 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1988 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1989 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001990
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001991 createAccountsDeletionTrigger(db);
1992 }
1993
1994 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001995 db.execSQL(""
1996 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1997 + " BEGIN"
1998 + " DELETE FROM " + TABLE_AUTHTOKENS
1999 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2000 + " DELETE FROM " + TABLE_EXTRAS
2001 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002002 + " DELETE FROM " + TABLE_GRANTS
2003 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002004 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002005 }
2006
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002007 private void createGrantsTable(SQLiteDatabase db) {
2008 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2009 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2010 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2011 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2012 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2013 + "," + GRANTS_GRANTEE_UID + "))");
2014 }
2015
Fred Quintana60307342009-03-24 22:48:12 -07002016 @Override
2017 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002018 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002019
Fred Quintanaa698f422009-04-08 19:14:54 -07002020 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002021 // no longer need to do anything since the work is done
2022 // when upgrading from version 2
2023 oldVersion++;
2024 }
2025
2026 if (oldVersion == 2) {
2027 createGrantsTable(db);
2028 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2029 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002030 oldVersion++;
2031 }
Costin Manolache3348f142009-09-29 18:58:36 -07002032
2033 if (oldVersion == 3) {
2034 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2035 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2036 oldVersion++;
2037 }
Fred Quintana60307342009-03-24 22:48:12 -07002038 }
2039
2040 @Override
2041 public void onOpen(SQLiteDatabase db) {
2042 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2043 }
2044 }
2045
Fred Quintana60307342009-03-24 22:48:12 -07002046 public IBinder onBind(Intent intent) {
2047 return asBinder();
2048 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002049
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002050 /**
2051 * Searches array of arguments for the specified string
2052 * @param args array of argument strings
2053 * @param value value to search for
2054 * @return true if the value is contained in the array
2055 */
2056 private static boolean scanArgs(String[] args, String value) {
2057 if (args != null) {
2058 for (String arg : args) {
2059 if (value.equals(arg)) {
2060 return true;
2061 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002062 }
2063 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002064 return false;
2065 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002066
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002067 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002068 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002069 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2070 != PackageManager.PERMISSION_GRANTED) {
2071 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2072 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2073 + " without permission " + android.Manifest.permission.DUMP);
2074 return;
2075 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002076 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002077 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002078
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002079 final List<UserInfo> users = getUserManager().getUsers();
2080 for (UserInfo user : users) {
2081 ipw.println("User " + user + ":");
2082 ipw.increaseIndent();
2083 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2084 ipw.println();
2085 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002086 }
2087 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002088
Amith Yamasani04e0d262012-02-14 11:50:53 -08002089 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2090 String[] args, boolean isCheckinRequest) {
2091 synchronized (userAccounts.cacheLock) {
2092 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002093
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002094 if (isCheckinRequest) {
2095 // This is a checkin request. *Only* upload the account types and the count of each.
2096 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2097 null, null, ACCOUNTS_TYPE, null, null);
2098 try {
2099 while (cursor.moveToNext()) {
2100 // print type,count
2101 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2102 }
2103 } finally {
2104 if (cursor != null) {
2105 cursor.close();
2106 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002107 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002108 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002109 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002110 fout.println("Accounts: " + accounts.length);
2111 for (Account account : accounts) {
2112 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002113 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002114
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002115 fout.println();
2116 synchronized (mSessions) {
2117 final long now = SystemClock.elapsedRealtime();
2118 fout.println("Active Sessions: " + mSessions.size());
2119 for (Session session : mSessions.values()) {
2120 fout.println(" " + session.toDebugString(now));
2121 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002122 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002123
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002124 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002125 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002126 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002127 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002128 }
2129
Amith Yamasani04e0d262012-02-14 11:50:53 -08002130 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002131 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002132 long identityToken = clearCallingIdentity();
2133 try {
2134 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2135 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2136 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002137
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002138 if (intent.getComponent() != null &&
2139 GrantCredentialsPermissionActivity.class.getName().equals(
2140 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002141 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002142 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002143 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002144 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002145 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2146 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002147 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002148 final String notificationTitleFormat =
2149 mContext.getText(R.string.notification_title).toString();
2150 n.setLatestEventInfo(mContext,
2151 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002152 message, PendingIntent.getActivityAsUser(
2153 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002154 null, user));
2155 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002156 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002157 } finally {
2158 restoreCallingIdentity(identityToken);
2159 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002160 }
2161
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002162 protected void installNotification(final int notificationId, final Notification n,
2163 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002164 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002165 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002166 }
2167
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002168 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002169 long identityToken = clearCallingIdentity();
2170 try {
2171 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002172 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002173 } finally {
2174 restoreCallingIdentity(identityToken);
2175 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002176 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002177
Fred Quintanab38eb142010-02-24 13:40:54 -08002178 /** Succeeds if any of the specified permissions are granted. */
2179 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002180 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002181
2182 for (String perm : permissions) {
2183 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2184 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002185 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002186 }
2187 return;
2188 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002189 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002190
2191 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002192 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002193 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002194 }
2195
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002196 private boolean inSystemImage(int callingUid) {
2197 final int callingUserId = UserHandle.getUserId(callingUid);
2198
2199 final PackageManager userPackageManager;
2200 try {
2201 userPackageManager = mContext.createPackageContextAsUser(
2202 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2203 } catch (NameNotFoundException e) {
2204 return false;
2205 }
2206
2207 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002208 for (String name : packages) {
2209 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002210 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002211 if (packageInfo != null
2212 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002213 return true;
2214 }
2215 } catch (PackageManager.NameNotFoundException e) {
2216 return false;
2217 }
2218 }
2219 return false;
2220 }
2221
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002222 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002223 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002224 final boolean fromAuthenticator = account != null
2225 && hasAuthenticatorUid(account.type, callerUid);
2226 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002227 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002228 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2229 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002230 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002231 + ": is authenticator? " + fromAuthenticator
2232 + ", has explicit permission? " + hasExplicitGrants);
2233 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002234 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002235 }
2236
Fred Quintana1a231912009-10-15 11:31:30 -07002237 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002238 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002239 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002240 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002241 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002242 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002243 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002244 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002245 }
2246 }
2247 return false;
2248 }
2249
Amith Yamasani04e0d262012-02-14 11:50:53 -08002250 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2251 int callerUid) {
2252 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002253 return true;
2254 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002255 UserAccounts accounts = getUserAccountsForCaller();
2256 synchronized (accounts.cacheLock) {
2257 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2258 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002259 account.name, account.type};
2260 final boolean permissionGranted =
2261 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2262 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2263 // TODO: Skip this check when running automated tests. Replace this
2264 // with a more general solution.
2265 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002266 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002267 + " but ignoring since device is in test harness.");
2268 return true;
2269 }
2270 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002271 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002272 }
2273
2274 private void checkCallingUidAgainstAuthenticator(Account account) {
2275 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002276 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002277 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2278 Log.w(TAG, msg);
2279 throw new SecurityException(msg);
2280 }
2281 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2282 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2283 }
2284 }
2285
2286 private void checkAuthenticateAccountsPermission(Account account) {
2287 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2288 checkCallingUidAgainstAuthenticator(account);
2289 }
2290
2291 private void checkReadAccountsPermission() {
2292 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2293 }
2294
2295 private void checkManageAccountsPermission() {
2296 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2297 }
2298
Fred Quintanab38eb142010-02-24 13:40:54 -08002299 private void checkManageAccountsOrUseCredentialsPermissions() {
2300 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2301 Manifest.permission.USE_CREDENTIALS);
2302 }
2303
Fred Quintanad9640ec2012-05-23 12:37:00 -07002304 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2305 throws RemoteException {
2306 final int callingUid = getCallingUid();
2307
2308 if (callingUid != android.os.Process.SYSTEM_UID) {
2309 throw new SecurityException();
2310 }
2311
2312 if (value) {
2313 grantAppPermission(account, authTokenType, uid);
2314 } else {
2315 revokeAppPermission(account, authTokenType, uid);
2316 }
2317 }
2318
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002319 /**
2320 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2321 * <p>
2322 * Although this is public it can only be accessed via the AccountManagerService object
2323 * which is in the system. This means we don't need to protect it with permissions.
2324 * @hide
2325 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002326 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002327 if (account == null || authTokenType == null) {
2328 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002329 return;
2330 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002331 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002332 synchronized (accounts.cacheLock) {
2333 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002334 db.beginTransaction();
2335 try {
2336 long accountId = getAccountIdLocked(db, account);
2337 if (accountId >= 0) {
2338 ContentValues values = new ContentValues();
2339 values.put(GRANTS_ACCOUNTS_ID, accountId);
2340 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2341 values.put(GRANTS_GRANTEE_UID, uid);
2342 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2343 db.setTransactionSuccessful();
2344 }
2345 } finally {
2346 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002347 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002348 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2349 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002350 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002351 }
2352
2353 /**
2354 * Don't allow callers with the given uid permission to get credentials for
2355 * account/authTokenType.
2356 * <p>
2357 * Although this is public it can only be accessed via the AccountManagerService object
2358 * which is in the system. This means we don't need to protect it with permissions.
2359 * @hide
2360 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002361 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002362 if (account == null || authTokenType == null) {
2363 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002364 return;
2365 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002366 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002367 synchronized (accounts.cacheLock) {
2368 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002369 db.beginTransaction();
2370 try {
2371 long accountId = getAccountIdLocked(db, account);
2372 if (accountId >= 0) {
2373 db.delete(TABLE_GRANTS,
2374 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2375 + GRANTS_GRANTEE_UID + "=?",
2376 new String[]{String.valueOf(accountId), authTokenType,
2377 String.valueOf(uid)});
2378 db.setTransactionSuccessful();
2379 }
2380 } finally {
2381 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002382 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002383 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2384 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002385 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002386 }
Fred Quintana56285a62010-12-02 14:20:51 -08002387
2388 static final private String stringArrayToString(String[] value) {
2389 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2390 }
2391
Amith Yamasani04e0d262012-02-14 11:50:53 -08002392 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2393 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002394 if (oldAccountsForType != null) {
2395 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2396 for (Account curAccount : oldAccountsForType) {
2397 if (!curAccount.equals(account)) {
2398 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002399 }
2400 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002401 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002402 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002403 } else {
2404 Account[] newAccountsForType = new Account[newAccountsList.size()];
2405 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002406 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002407 }
Fred Quintana56285a62010-12-02 14:20:51 -08002408 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002409 accounts.userDataCache.remove(account);
2410 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002411 }
2412
2413 /**
2414 * This assumes that the caller has already checked that the account is not already present.
2415 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002416 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2417 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002418 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2419 Account[] newAccountsForType = new Account[oldLength + 1];
2420 if (accountsForType != null) {
2421 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002422 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002423 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002424 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002425 }
2426
Amith Yamasani04e0d262012-02-14 11:50:53 -08002427 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002428 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002429 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002430 if (accounts == null) {
2431 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002432 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002433 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002434 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002435 } else {
2436 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002437 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002438 totalLength += accounts.length;
2439 }
2440 if (totalLength == 0) {
2441 return EMPTY_ACCOUNT_ARRAY;
2442 }
2443 Account[] accounts = new Account[totalLength];
2444 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002445 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002446 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2447 accountsOfType.length);
2448 totalLength += accountsOfType.length;
2449 }
2450 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002451 }
2452 }
2453
Amith Yamasani04e0d262012-02-14 11:50:53 -08002454 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2455 Account account, String key, String value) {
2456 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002457 if (userDataForAccount == null) {
2458 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002459 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002460 }
2461 if (value == null) {
2462 userDataForAccount.remove(key);
2463 } else {
2464 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002465 }
2466 }
2467
Amith Yamasani04e0d262012-02-14 11:50:53 -08002468 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2469 Account account, String key, String value) {
2470 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002471 if (authTokensForAccount == null) {
2472 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002473 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002474 }
2475 if (value == null) {
2476 authTokensForAccount.remove(key);
2477 } else {
2478 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002479 }
2480 }
2481
Amith Yamasani04e0d262012-02-14 11:50:53 -08002482 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2483 String authTokenType) {
2484 synchronized (accounts.cacheLock) {
2485 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002486 if (authTokensForAccount == null) {
2487 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002488 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002489 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002490 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002491 }
2492 return authTokensForAccount.get(authTokenType);
2493 }
2494 }
2495
Amith Yamasani04e0d262012-02-14 11:50:53 -08002496 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2497 synchronized (accounts.cacheLock) {
2498 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002499 if (userDataForAccount == null) {
2500 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002501 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002502 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002503 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002504 }
2505 return userDataForAccount.get(key);
2506 }
2507 }
2508
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002509 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2510 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002511 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002512 Cursor cursor = db.query(TABLE_EXTRAS,
2513 COLUMNS_EXTRAS_KEY_AND_VALUE,
2514 SELECTION_USERDATA_BY_ACCOUNT,
2515 new String[]{account.name, account.type},
2516 null, null, null);
2517 try {
2518 while (cursor.moveToNext()) {
2519 final String tmpkey = cursor.getString(0);
2520 final String value = cursor.getString(1);
2521 userDataForAccount.put(tmpkey, value);
2522 }
2523 } finally {
2524 cursor.close();
2525 }
2526 return userDataForAccount;
2527 }
2528
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002529 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2530 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002531 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002532 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2533 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2534 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2535 new String[]{account.name, account.type},
2536 null, null, null);
2537 try {
2538 while (cursor.moveToNext()) {
2539 final String type = cursor.getString(0);
2540 final String authToken = cursor.getString(1);
2541 authTokensForAccount.put(type, authToken);
2542 }
2543 } finally {
2544 cursor.close();
2545 }
2546 return authTokensForAccount;
2547 }
Fred Quintana60307342009-03-24 22:48:12 -07002548}