blob: 09daf569349b7a41a5c4dc6662a4811f3889421f [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080020import android.accounts.Account;
21import android.accounts.AccountAndUser;
22import android.accounts.AccountAuthenticatorResponse;
23import android.accounts.AccountManager;
24import android.accounts.AuthenticatorDescription;
25import android.accounts.GrantCredentialsPermissionActivity;
26import android.accounts.IAccountAuthenticator;
27import android.accounts.IAccountAuthenticatorResponse;
28import android.accounts.IAccountManager;
29import android.accounts.IAccountManagerResponse;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080030import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070031import android.app.ActivityManagerNative;
Doug Zongker885cfc232009-10-21 16:52:44 -070032import android.app.Notification;
33import android.app.NotificationManager;
34import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070035import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070036import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070037import android.content.ContentValues;
38import android.content.Context;
39import android.content.Intent;
40import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070041import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070042import android.content.pm.ApplicationInfo;
43import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070044import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070045import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070046import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070047import android.content.pm.RegisteredServicesCacheListener;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070048import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070049import android.database.Cursor;
50import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070051import android.database.sqlite.SQLiteDatabase;
52import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070053import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070054import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080055import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070056import android.os.Handler;
57import android.os.HandlerThread;
58import android.os.IBinder;
59import android.os.Looper;
60import android.os.Message;
61import android.os.RemoteException;
62import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070063import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070064import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import android.text.TextUtils;
66import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070067import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070068import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080069import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070070
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070071import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080072import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080073import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070074import com.google.android.collect.Lists;
75import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070076
Oscar Montemayora8529f62009-11-18 10:14:20 -080077import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070078import java.io.FileDescriptor;
79import java.io.PrintWriter;
80import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080081import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070082import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070083import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070084import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080085import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070086import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080087import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070088import java.util.concurrent.atomic.AtomicInteger;
89import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070090
Fred Quintana60307342009-03-24 22:48:12 -070091/**
92 * A system service that provides account, password, and authtoken management for all
93 * accounts on the device. Some of these calls are implemented with the help of the corresponding
94 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
95 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070096 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -070097 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070098 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070099public class AccountManagerService
100 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800101 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700102 private static final String TAG = "AccountManagerService";
103
104 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
105 private static final String DATABASE_NAME = "accounts.db";
Amith Yamasani67df64b2012-12-14 12:09:36 -0800106 private static final int DATABASE_VERSION = 5;
Fred Quintana60307342009-03-24 22:48:12 -0700107
108 private final Context mContext;
109
Fred Quintana56285a62010-12-02 14:20:51 -0800110 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700111 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800112
Fred Quintana60307342009-03-24 22:48:12 -0700113 private HandlerThread mMessageThread;
114 private final MessageHandler mMessageHandler;
115
116 // Messages that can be sent on mHandler
117 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700118
Fred Quintana56285a62010-12-02 14:20:51 -0800119 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700120
121 private static final String TABLE_ACCOUNTS = "accounts";
122 private static final String ACCOUNTS_ID = "_id";
123 private static final String ACCOUNTS_NAME = "name";
124 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700125 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700126 private static final String ACCOUNTS_PASSWORD = "password";
127
128 private static final String TABLE_AUTHTOKENS = "authtokens";
129 private static final String AUTHTOKENS_ID = "_id";
130 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
131 private static final String AUTHTOKENS_TYPE = "type";
132 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
133
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700134 private static final String TABLE_GRANTS = "grants";
135 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
136 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
137 private static final String GRANTS_GRANTEE_UID = "uid";
138
Fred Quintana60307342009-03-24 22:48:12 -0700139 private static final String TABLE_EXTRAS = "extras";
140 private static final String EXTRAS_ID = "_id";
141 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
142 private static final String EXTRAS_KEY = "key";
143 private static final String EXTRAS_VALUE = "value";
144
145 private static final String TABLE_META = "meta";
146 private static final String META_KEY = "key";
147 private static final String META_VALUE = "value";
148
Amith Yamasani67df64b2012-12-14 12:09:36 -0800149 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
150
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700151 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
152 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700153 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700154
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700155 private static final String COUNT_OF_MATCHING_GRANTS = ""
156 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
157 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
158 + " AND " + GRANTS_GRANTEE_UID + "=?"
159 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
160 + " AND " + ACCOUNTS_NAME + "=?"
161 + " AND " + ACCOUNTS_TYPE + "=?";
162
Fred Quintana56285a62010-12-02 14:20:51 -0800163 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
164 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
165 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
166 AUTHTOKENS_AUTHTOKEN};
167
168 private static final String SELECTION_USERDATA_BY_ACCOUNT =
169 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
170 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
171
Fred Quintanaa698f422009-04-08 19:14:54 -0700172 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700173 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
174
Amith Yamasani04e0d262012-02-14 11:50:53 -0800175 static class UserAccounts {
176 private final int userId;
177 private final DatabaseHelper openHelper;
178 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
179 credentialsPermissionNotificationIds =
180 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
181 private final HashMap<Account, Integer> signinRequiredNotificationIds =
182 new HashMap<Account, Integer>();
183 private final Object cacheLock = new Object();
184 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700185 private final HashMap<String, Account[]> accountCache =
186 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800187 /** protected by the {@link #cacheLock} */
188 private HashMap<Account, HashMap<String, String>> userDataCache =
189 new HashMap<Account, HashMap<String, String>>();
190 /** protected by the {@link #cacheLock} */
191 private HashMap<Account, HashMap<String, String>> authTokenCache =
192 new HashMap<Account, HashMap<String, String>>();
193
194 UserAccounts(Context context, int userId) {
195 this.userId = userId;
196 synchronized (cacheLock) {
197 openHelper = new DatabaseHelper(context, userId);
198 }
199 }
200 }
201
202 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
203
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700204 private static AtomicReference<AccountManagerService> sThis =
205 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700206 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700207
208 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700209 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700210 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
211 }
212
Fred Quintana56285a62010-12-02 14:20:51 -0800213
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700214 /**
215 * This should only be called by system code. One should only call this after the service
216 * has started.
217 * @return a reference to the AccountManagerService instance
218 * @hide
219 */
220 public static AccountManagerService getSingleton() {
221 return sThis.get();
222 }
Fred Quintana60307342009-03-24 22:48:12 -0700223
Fred Quintana56285a62010-12-02 14:20:51 -0800224 public AccountManagerService(Context context) {
225 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700226 }
227
Fred Quintana56285a62010-12-02 14:20:51 -0800228 public AccountManagerService(Context context, PackageManager packageManager,
229 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700230 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800231 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700232
Fred Quintana60307342009-03-24 22:48:12 -0700233 mMessageThread = new HandlerThread("AccountManagerService");
234 mMessageThread.start();
235 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
236
Fred Quintana56285a62010-12-02 14:20:51 -0800237 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800238 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700239
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700240 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800241
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800242 IntentFilter intentFilter = new IntentFilter();
243 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
244 intentFilter.addDataScheme("package");
245 mContext.registerReceiver(new BroadcastReceiver() {
246 @Override
247 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800248 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800249 }
250 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800251
Amith Yamasani13593602012-03-22 16:16:17 -0700252 IntentFilter userFilter = new IntentFilter();
253 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800254 userFilter.addAction(Intent.ACTION_USER_STARTED);
255 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700256 @Override
257 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800258 String action = intent.getAction();
259 if (Intent.ACTION_USER_REMOVED.equals(action)) {
260 onUserRemoved(intent);
261 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
262 onUserStarted(intent);
263 }
Amith Yamasani13593602012-03-22 16:16:17 -0700264 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800265 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800266 }
267
Kenny Root26ff6622012-07-30 12:58:03 -0700268 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700269 }
270
Amith Yamasani258848d2012-08-10 17:06:33 -0700271 private UserManager getUserManager() {
272 if (mUserManager == null) {
273 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
274 }
275 return mUserManager;
276 }
277
Amith Yamasani04e0d262012-02-14 11:50:53 -0800278 private UserAccounts initUser(int userId) {
279 synchronized (mUsers) {
280 UserAccounts accounts = mUsers.get(userId);
281 if (accounts == null) {
282 accounts = new UserAccounts(mContext, userId);
283 mUsers.append(userId, accounts);
284 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700285 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800286 }
287 return accounts;
288 }
289 }
290
291 private void purgeOldGrantsAll() {
292 synchronized (mUsers) {
293 for (int i = 0; i < mUsers.size(); i++) {
294 purgeOldGrants(mUsers.valueAt(i));
295 }
296 }
297 }
298
299 private void purgeOldGrants(UserAccounts accounts) {
300 synchronized (accounts.cacheLock) {
301 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800302 final Cursor cursor = db.query(TABLE_GRANTS,
303 new String[]{GRANTS_GRANTEE_UID},
304 null, null, GRANTS_GRANTEE_UID, null, null);
305 try {
306 while (cursor.moveToNext()) {
307 final int uid = cursor.getInt(0);
308 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
309 if (packageExists) {
310 continue;
311 }
312 Log.d(TAG, "deleting grants for UID " + uid
313 + " because its package is no longer installed");
314 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
315 new String[]{Integer.toString(uid)});
316 }
317 } finally {
318 cursor.close();
319 }
320 }
321 }
322
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700323 /**
324 * Validate internal set of accounts against installed authenticators for
325 * given user. Clears cached authenticators before validating.
326 */
327 public void validateAccounts(int userId) {
328 final UserAccounts accounts = getUserAccounts(userId);
329
330 // Invalidate user-specific cache to make sure we catch any
331 // removed authenticators.
332 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
333 }
334
335 /**
336 * Validate internal set of accounts against installed authenticators for
337 * given user. Clear cached authenticators before validating when requested.
338 */
339 private void validateAccountsInternal(
340 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
341 if (invalidateAuthenticatorCache) {
342 mAuthenticatorCache.invalidateCache(accounts.userId);
343 }
344
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700345 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
346 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
347 mAuthenticatorCache.getAllServices(accounts.userId)) {
348 knownAuth.add(service.type);
349 }
350
Amith Yamasani04e0d262012-02-14 11:50:53 -0800351 synchronized (accounts.cacheLock) {
352 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800353 boolean accountDeleted = false;
354 Cursor cursor = db.query(TABLE_ACCOUNTS,
355 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
356 null, null, null, null, null);
357 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800358 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800359 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700360 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800361 while (cursor.moveToNext()) {
362 final long accountId = cursor.getLong(0);
363 final String accountType = cursor.getString(1);
364 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700365
366 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700367 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800368 + accountType + " no longer has a registered authenticator");
369 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
370 accountDeleted = true;
371 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800372 accounts.userDataCache.remove(account);
373 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800374 } else {
375 ArrayList<String> accountNames = accountNamesByType.get(accountType);
376 if (accountNames == null) {
377 accountNames = new ArrayList<String>();
378 accountNamesByType.put(accountType, accountNames);
379 }
380 accountNames.add(accountName);
381 }
382 }
Andy McFadden2f362292012-01-20 14:43:38 -0800383 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800384 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800385 final String accountType = cur.getKey();
386 final ArrayList<String> accountNames = cur.getValue();
387 final Account[] accountsForType = new Account[accountNames.size()];
388 int i = 0;
389 for (String accountName : accountNames) {
390 accountsForType[i] = new Account(accountName, accountType);
391 ++i;
392 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800393 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800394 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800395 } finally {
396 cursor.close();
397 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800398 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800399 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800400 }
401 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700402 }
403
Amith Yamasani04e0d262012-02-14 11:50:53 -0800404 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700405 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800406 }
407
408 protected UserAccounts getUserAccounts(int userId) {
409 synchronized (mUsers) {
410 UserAccounts accounts = mUsers.get(userId);
411 if (accounts == null) {
412 accounts = initUser(userId);
413 mUsers.append(userId, accounts);
414 }
415 return accounts;
416 }
417 }
418
Amith Yamasani13593602012-03-22 16:16:17 -0700419 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700420 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700421 if (userId < 1) return;
422
423 UserAccounts accounts;
424 synchronized (mUsers) {
425 accounts = mUsers.get(userId);
426 mUsers.remove(userId);
427 }
428 if (accounts == null) {
429 File dbFile = new File(getDatabaseName(userId));
430 dbFile.delete();
431 return;
432 }
433
434 synchronized (accounts.cacheLock) {
435 accounts.openHelper.close();
436 File dbFile = new File(getDatabaseName(userId));
437 dbFile.delete();
438 }
439 }
440
Amith Yamasani67df64b2012-12-14 12:09:36 -0800441 private void onUserStarted(Intent intent) {
442 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
443 if (userId < 1) return;
444
445 // Check if there's a shared account that needs to be created as an account
446 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
447 if (sharedAccounts == null || sharedAccounts.length == 0) return;
448 Account[] accounts = getAccountsAsUser(null, userId);
449 for (Account sa : sharedAccounts) {
450 if (ArrayUtils.contains(accounts, sa)) continue;
451 // Account doesn't exist. Copy it now.
452 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
453 }
454 }
455
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700456 @Override
457 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700458 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700459 }
460
Fred Quintanaa698f422009-04-08 19:14:54 -0700461 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800462 if (Log.isLoggable(TAG, Log.VERBOSE)) {
463 Log.v(TAG, "getPassword: " + account
464 + ", caller's uid " + Binder.getCallingUid()
465 + ", pid " + Binder.getCallingPid());
466 }
Fred Quintana382601f2010-03-25 12:25:10 -0700467 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700468 checkAuthenticateAccountsPermission(account);
469
Amith Yamasani04e0d262012-02-14 11:50:53 -0800470 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700471 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700472 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800473 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700474 } finally {
475 restoreCallingIdentity(identityToken);
476 }
477 }
478
Amith Yamasani04e0d262012-02-14 11:50:53 -0800479 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700480 if (account == null) {
481 return null;
482 }
483
Amith Yamasani04e0d262012-02-14 11:50:53 -0800484 synchronized (accounts.cacheLock) {
485 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800486 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
487 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
488 new String[]{account.name, account.type}, null, null, null);
489 try {
490 if (cursor.moveToNext()) {
491 return cursor.getString(0);
492 }
493 return null;
494 } finally {
495 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700496 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700497 }
498 }
499
500 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800501 if (Log.isLoggable(TAG, Log.VERBOSE)) {
502 Log.v(TAG, "getUserData: " + account
503 + ", key " + key
504 + ", caller's uid " + Binder.getCallingUid()
505 + ", pid " + Binder.getCallingPid());
506 }
Fred Quintana382601f2010-03-25 12:25:10 -0700507 if (account == null) throw new IllegalArgumentException("account is null");
508 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700509 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800510 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700511 long identityToken = clearCallingIdentity();
512 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800513 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700514 } finally {
515 restoreCallingIdentity(identityToken);
516 }
517 }
518
Fred Quintana97889762009-06-15 12:29:24 -0700519 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800520 if (Log.isLoggable(TAG, Log.VERBOSE)) {
521 Log.v(TAG, "getAuthenticatorTypes: "
522 + "caller's uid " + Binder.getCallingUid()
523 + ", pid " + Binder.getCallingPid());
524 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700525 final int userId = UserHandle.getCallingUserId();
526 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700527 try {
Fred Quintana97889762009-06-15 12:29:24 -0700528 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700529 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700530 AuthenticatorDescription[] types =
531 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700532 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700533 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700534 : authenticatorCollection) {
535 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700536 i++;
537 }
538 return types;
539 } finally {
540 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700541 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700542 }
543
Fred Quintanaa698f422009-04-08 19:14:54 -0700544 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800545 if (Log.isLoggable(TAG, Log.VERBOSE)) {
546 Log.v(TAG, "addAccount: " + account
547 + ", caller's uid " + Binder.getCallingUid()
548 + ", pid " + Binder.getCallingPid());
549 }
Fred Quintana382601f2010-03-25 12:25:10 -0700550 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700551 checkAuthenticateAccountsPermission(account);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800552 if (!canUserModifyAccounts(Binder.getCallingUid())) {
553 return false;
554 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700555
Amith Yamasani04e0d262012-02-14 11:50:53 -0800556 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700557 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700558 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700559 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800560 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700561 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700562 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700563 }
564 }
565
Amith Yamasani67df64b2012-12-14 12:09:36 -0800566 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
567 final UserAccounts fromAccounts = getUserAccounts(userFrom);
568 final UserAccounts toAccounts = getUserAccounts(userTo);
569 if (fromAccounts == null || toAccounts == null) {
570 return false;
571 }
572
573 long identityToken = clearCallingIdentity();
574 try {
575 new Session(fromAccounts, null, account.type, false,
576 false /* stripAuthTokenFromResult */) {
577 protected String toDebugString(long now) {
578 return super.toDebugString(now) + ", getAccountCredentialsForClone"
579 + ", " + account.type;
580 }
581
582 public void run() throws RemoteException {
583 mAuthenticator.getAccountCredentialsForCloning(this, account);
584 }
585
586 public void onResult(Bundle result) {
587 if (result != null) {
588 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
589 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800590 completeCloningAccount(result, account, toAccounts);
591 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800592 clonePassword(fromAccounts, toAccounts, account);
593 }
594 return;
595 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800596 clonePassword(fromAccounts, toAccounts, account);
597 super.onResult(result);
598 }
599 }
600 }.bind();
601 } finally {
602 restoreCallingIdentity(identityToken);
603 }
604 return true;
605 }
606
607 // TODO: Remove fallback - move to authenticator
608 private void clonePassword(UserAccounts fromAccounts, UserAccounts toAccounts,
609 Account account) {
610 long id = clearCallingIdentity();
611 try {
612 String password = readPasswordInternal(fromAccounts, account);
613 String extraFlags = readUserDataInternal(fromAccounts, account, "flags");
614 String extraServices = readUserDataInternal(fromAccounts, account, "services");
615 Bundle extras = new Bundle();
616 extras.putString("flags", extraFlags);
617 extras.putString("services", extraServices);
618 addAccountInternal(toAccounts, account, password, extras, true);
619 } finally {
620 restoreCallingIdentity(id);
621 }
622 }
623
624 void completeCloningAccount(final Bundle result, final Account account,
625 final UserAccounts targetUser) {
626 long id = clearCallingIdentity();
627 try {
628 new Session(targetUser, null, account.type, false,
629 false /* stripAuthTokenFromResult */) {
630 protected String toDebugString(long now) {
631 return super.toDebugString(now) + ", getAccountCredentialsForClone"
632 + ", " + account.type;
633 }
634
635 public void run() throws RemoteException {
636 mAuthenticator.addAccountFromCredentials(this, account, result);
637 }
638
639 public void onResult(Bundle result) {
640 if (result != null) {
641 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
642 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800643 } else {
644 // TODO: Show error notification
645 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800646 }
647 return;
648 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800649 super.onResult(result);
650 }
651 }
652
653 public void onError(int errorCode, String errorMessage) {
654 super.onError(errorCode, errorMessage);
655 // TODO: Show error notification to user
656 // TODO: Should we remove the shadow account so that it doesn't keep trying?
657 }
658
659 }.bind();
660 } finally {
661 restoreCallingIdentity(id);
662 }
663 }
664
Amith Yamasani04e0d262012-02-14 11:50:53 -0800665 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800666 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700667 if (account == null) {
668 return false;
669 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800670 synchronized (accounts.cacheLock) {
671 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800672 db.beginTransaction();
673 try {
674 long numMatches = DatabaseUtils.longForQuery(db,
675 "select count(*) from " + TABLE_ACCOUNTS
676 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
677 new String[]{account.name, account.type});
678 if (numMatches > 0) {
679 Log.w(TAG, "insertAccountIntoDatabase: " + account
680 + ", skipping since the account already exists");
681 return false;
682 }
683 ContentValues values = new ContentValues();
684 values.put(ACCOUNTS_NAME, account.name);
685 values.put(ACCOUNTS_TYPE, account.type);
686 values.put(ACCOUNTS_PASSWORD, password);
687 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
688 if (accountId < 0) {
689 Log.w(TAG, "insertAccountIntoDatabase: " + account
690 + ", skipping the DB insert failed");
691 return false;
692 }
693 if (extras != null) {
694 for (String key : extras.keySet()) {
695 final String value = extras.getString(key);
696 if (insertExtraLocked(db, accountId, key, value) < 0) {
697 Log.w(TAG, "insertAccountIntoDatabase: " + account
698 + ", skipping since insertExtra failed for key " + key);
699 return false;
700 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700701 }
702 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800703 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800704 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800705 } finally {
706 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700707 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800708 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800709 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700710 }
711 }
712
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800713 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700714 ContentValues values = new ContentValues();
715 values.put(EXTRAS_KEY, key);
716 values.put(EXTRAS_ACCOUNTS_ID, accountId);
717 values.put(EXTRAS_VALUE, value);
718 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
719 }
720
Fred Quintana3084a6f2010-01-14 18:02:03 -0800721 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800722 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800723 if (Log.isLoggable(TAG, Log.VERBOSE)) {
724 Log.v(TAG, "hasFeatures: " + account
725 + ", response " + response
726 + ", features " + stringArrayToString(features)
727 + ", caller's uid " + Binder.getCallingUid()
728 + ", pid " + Binder.getCallingPid());
729 }
Fred Quintana382601f2010-03-25 12:25:10 -0700730 if (response == null) throw new IllegalArgumentException("response is null");
731 if (account == null) throw new IllegalArgumentException("account is null");
732 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800733 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800734 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800735 long identityToken = clearCallingIdentity();
736 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800737 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800738 } finally {
739 restoreCallingIdentity(identityToken);
740 }
741 }
742
743 private class TestFeaturesSession extends Session {
744 private final String[] mFeatures;
745 private final Account mAccount;
746
Amith Yamasani04e0d262012-02-14 11:50:53 -0800747 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800748 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800749 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800750 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800751 mFeatures = features;
752 mAccount = account;
753 }
754
755 public void run() throws RemoteException {
756 try {
757 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
758 } catch (RemoteException e) {
759 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
760 }
761 }
762
763 public void onResult(Bundle result) {
764 IAccountManagerResponse response = getResponseAndClose();
765 if (response != null) {
766 try {
767 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700768 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800769 return;
770 }
Fred Quintana56285a62010-12-02 14:20:51 -0800771 if (Log.isLoggable(TAG, Log.VERBOSE)) {
772 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
773 + response);
774 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800775 final Bundle newResult = new Bundle();
776 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
777 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
778 response.onResult(newResult);
779 } catch (RemoteException e) {
780 // if the caller is dead then there is no one to care about remote exceptions
781 if (Log.isLoggable(TAG, Log.VERBOSE)) {
782 Log.v(TAG, "failure while notifying response", e);
783 }
784 }
785 }
786 }
787
788 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800789 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800790 + ", " + mAccount
791 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
792 }
793 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800794
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700795 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800796 if (Log.isLoggable(TAG, Log.VERBOSE)) {
797 Log.v(TAG, "removeAccount: " + account
798 + ", response " + response
799 + ", caller's uid " + Binder.getCallingUid()
800 + ", pid " + Binder.getCallingPid());
801 }
Fred Quintana382601f2010-03-25 12:25:10 -0700802 if (response == null) throw new IllegalArgumentException("response is null");
803 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700804 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700805 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800806 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800807 if (!canUserModifyAccounts(Binder.getCallingUid())) {
808 try {
809 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
810 "User cannot modify accounts");
811 } catch (RemoteException re) {
812 }
813 }
814
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700815 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800816
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700817 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800818 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800819 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800820 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800821 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800822 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700823 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800824 }
825 }
826 }
827
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700828 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800829 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700830 } finally {
831 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700832 }
Fred Quintana60307342009-03-24 22:48:12 -0700833 }
834
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700835 private class RemoveAccountSession extends Session {
836 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800837 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
838 Account account) {
839 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800840 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700841 mAccount = account;
842 }
843
844 protected String toDebugString(long now) {
845 return super.toDebugString(now) + ", removeAccount"
846 + ", account " + mAccount;
847 }
848
849 public void run() throws RemoteException {
850 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
851 }
852
853 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700854 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
855 && !result.containsKey(AccountManager.KEY_INTENT)) {
856 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700857 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800858 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700859 }
860 IAccountManagerResponse response = getResponseAndClose();
861 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800862 if (Log.isLoggable(TAG, Log.VERBOSE)) {
863 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
864 + response);
865 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700866 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700867 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700868 try {
869 response.onResult(result2);
870 } catch (RemoteException e) {
871 // ignore
872 }
873 }
874 }
875 super.onResult(result);
876 }
877 }
878
Amith Yamasani04e0d262012-02-14 11:50:53 -0800879 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800880 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800881 removeAccountInternal(getUserAccountsForCaller(), account);
882 }
883
884 private void removeAccountInternal(UserAccounts accounts, Account account) {
885 synchronized (accounts.cacheLock) {
886 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800887 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
888 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800889 removeAccountFromCacheLocked(accounts, account);
890 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800891 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800892 if (accounts.userId == UserHandle.USER_OWNER) {
893 // Owner's account was removed, remove from any users that are sharing
894 // this account.
895 long id = Binder.clearCallingIdentity();
896 try {
897 List<UserInfo> users = mUserManager.getUsers(true);
898 for (UserInfo user : users) {
899 if (!user.isPrimary() && user.isRestricted()) {
900 removeSharedAccountAsUser(account, user.id);
901 }
902 }
903 } finally {
904 Binder.restoreCallingIdentity(id);
905 }
906 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700907 }
908
Fred Quintanaa698f422009-04-08 19:14:54 -0700909 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800910 if (Log.isLoggable(TAG, Log.VERBOSE)) {
911 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
912 + ", caller's uid " + Binder.getCallingUid()
913 + ", pid " + Binder.getCallingPid());
914 }
Fred Quintana382601f2010-03-25 12:25:10 -0700915 if (accountType == null) throw new IllegalArgumentException("accountType is null");
916 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800917 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800918 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700919 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700920 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800921 synchronized (accounts.cacheLock) {
922 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800923 db.beginTransaction();
924 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800925 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800926 db.setTransactionSuccessful();
927 } finally {
928 db.endTransaction();
929 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700930 }
Fred Quintana60307342009-03-24 22:48:12 -0700931 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700932 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700933 }
934 }
935
Amith Yamasani04e0d262012-02-14 11:50:53 -0800936 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
937 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700938 if (authToken == null || accountType == null) {
939 return;
940 }
Fred Quintana33269202009-04-20 16:05:10 -0700941 Cursor cursor = db.rawQuery(
942 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
943 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
944 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
945 + " FROM " + TABLE_ACCOUNTS
946 + " JOIN " + TABLE_AUTHTOKENS
947 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
948 + " = " + AUTHTOKENS_ACCOUNTS_ID
949 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
950 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
951 new String[]{authToken, accountType});
952 try {
953 while (cursor.moveToNext()) {
954 long authTokenId = cursor.getLong(0);
955 String accountName = cursor.getString(1);
956 String authTokenType = cursor.getString(2);
957 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800958 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800959 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700960 }
Fred Quintana33269202009-04-20 16:05:10 -0700961 } finally {
962 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700963 }
964 }
965
Amith Yamasani04e0d262012-02-14 11:50:53 -0800966 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
967 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700968 if (account == null || type == null) {
969 return false;
970 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700971 cancelNotification(getSigninRequiredNotificationId(accounts, account),
972 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800973 synchronized (accounts.cacheLock) {
974 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800975 db.beginTransaction();
976 try {
977 long accountId = getAccountIdLocked(db, account);
978 if (accountId < 0) {
979 return false;
980 }
981 db.delete(TABLE_AUTHTOKENS,
982 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
983 new String[]{type});
984 ContentValues values = new ContentValues();
985 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
986 values.put(AUTHTOKENS_TYPE, type);
987 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
988 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
989 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800990 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800991 return true;
992 }
Fred Quintana33269202009-04-20 16:05:10 -0700993 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800994 } finally {
995 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -0700996 }
Fred Quintana60307342009-03-24 22:48:12 -0700997 }
998 }
999
Fred Quintanaa698f422009-04-08 19:14:54 -07001000 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001001 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1002 Log.v(TAG, "peekAuthToken: " + account
1003 + ", authTokenType " + authTokenType
1004 + ", caller's uid " + Binder.getCallingUid()
1005 + ", pid " + Binder.getCallingPid());
1006 }
Fred Quintana382601f2010-03-25 12:25:10 -07001007 if (account == null) throw new IllegalArgumentException("account is null");
1008 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001009 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001010 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001011 long identityToken = clearCallingIdentity();
1012 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001013 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001014 } finally {
1015 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001016 }
Fred Quintana60307342009-03-24 22:48:12 -07001017 }
1018
Fred Quintanaa698f422009-04-08 19:14:54 -07001019 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001020 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1021 Log.v(TAG, "setAuthToken: " + account
1022 + ", authTokenType " + authTokenType
1023 + ", caller's uid " + Binder.getCallingUid()
1024 + ", pid " + Binder.getCallingPid());
1025 }
Fred Quintana382601f2010-03-25 12:25:10 -07001026 if (account == null) throw new IllegalArgumentException("account is null");
1027 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001028 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001029 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001030 long identityToken = clearCallingIdentity();
1031 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001032 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001033 } finally {
1034 restoreCallingIdentity(identityToken);
1035 }
Fred Quintana60307342009-03-24 22:48:12 -07001036 }
1037
Fred Quintanaa698f422009-04-08 19:14:54 -07001038 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001039 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1040 Log.v(TAG, "setAuthToken: " + account
1041 + ", caller's uid " + Binder.getCallingUid()
1042 + ", pid " + Binder.getCallingPid());
1043 }
Fred Quintana382601f2010-03-25 12:25:10 -07001044 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001045 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001046 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001047 long identityToken = clearCallingIdentity();
1048 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001049 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001050 } finally {
1051 restoreCallingIdentity(identityToken);
1052 }
Fred Quintana60307342009-03-24 22:48:12 -07001053 }
1054
Amith Yamasani04e0d262012-02-14 11:50:53 -08001055 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001056 if (account == null) {
1057 return;
1058 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001059 synchronized (accounts.cacheLock) {
1060 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001061 db.beginTransaction();
1062 try {
1063 final ContentValues values = new ContentValues();
1064 values.put(ACCOUNTS_PASSWORD, password);
1065 final long accountId = getAccountIdLocked(db, account);
1066 if (accountId >= 0) {
1067 final String[] argsAccountId = {String.valueOf(accountId)};
1068 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1069 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001070 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001071 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001072 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001073 } finally {
1074 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001075 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001076 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001077 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001078 }
1079
Amith Yamasani04e0d262012-02-14 11:50:53 -08001080 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001081 Log.i(TAG, "the accounts changed, sending broadcast of "
1082 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001083 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001084 }
1085
Fred Quintanaa698f422009-04-08 19:14:54 -07001086 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001087 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1088 Log.v(TAG, "clearPassword: " + account
1089 + ", caller's uid " + Binder.getCallingUid()
1090 + ", pid " + Binder.getCallingPid());
1091 }
Fred Quintana382601f2010-03-25 12:25:10 -07001092 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001093 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001094 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001095 long identityToken = clearCallingIdentity();
1096 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001097 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001098 } finally {
1099 restoreCallingIdentity(identityToken);
1100 }
Fred Quintana60307342009-03-24 22:48:12 -07001101 }
1102
Fred Quintanaa698f422009-04-08 19:14:54 -07001103 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001104 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1105 Log.v(TAG, "setUserData: " + account
1106 + ", key " + key
1107 + ", caller's uid " + Binder.getCallingUid()
1108 + ", pid " + Binder.getCallingPid());
1109 }
Fred Quintana382601f2010-03-25 12:25:10 -07001110 if (key == null) throw new IllegalArgumentException("key is null");
1111 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001112 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001113 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001114 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001115 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001116 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001117 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001118 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001119 }
1120 }
1121
Amith Yamasani04e0d262012-02-14 11:50:53 -08001122 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1123 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001124 if (account == null || key == null) {
1125 return;
1126 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001127 synchronized (accounts.cacheLock) {
1128 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001129 db.beginTransaction();
1130 try {
1131 long accountId = getAccountIdLocked(db, account);
1132 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001133 return;
1134 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001135 long extrasId = getExtrasIdLocked(db, accountId, key);
1136 if (extrasId < 0 ) {
1137 extrasId = insertExtraLocked(db, accountId, key, value);
1138 if (extrasId < 0) {
1139 return;
1140 }
1141 } else {
1142 ContentValues values = new ContentValues();
1143 values.put(EXTRAS_VALUE, value);
1144 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1145 return;
1146 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001147
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001148 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001149 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001150 db.setTransactionSuccessful();
1151 } finally {
1152 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001153 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001154 }
1155 }
1156
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001157 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001158 if (result == null) {
1159 Log.e(TAG, "the result is unexpectedly null", new Exception());
1160 }
1161 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1162 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1163 + response);
1164 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001165 try {
1166 response.onResult(result);
1167 } catch (RemoteException e) {
1168 // if the caller is dead then there is no one to care about remote
1169 // exceptions
1170 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1171 Log.v(TAG, "failure while notifying response", e);
1172 }
1173 }
1174 }
1175
Fred Quintanad9640ec2012-05-23 12:37:00 -07001176 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1177 final String authTokenType)
1178 throws RemoteException {
1179 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001180 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1181
Fred Quintanad9640ec2012-05-23 12:37:00 -07001182 final int callingUid = getCallingUid();
1183 clearCallingIdentity();
1184 if (callingUid != android.os.Process.SYSTEM_UID) {
1185 throw new SecurityException("can only call from system");
1186 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001187 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001188 long identityToken = clearCallingIdentity();
1189 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001190 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001191 false /* stripAuthTokenFromResult */) {
1192 protected String toDebugString(long now) {
1193 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001194 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001195 + ", authTokenType " + authTokenType;
1196 }
1197
1198 public void run() throws RemoteException {
1199 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1200 }
1201
1202 public void onResult(Bundle result) {
1203 if (result != null) {
1204 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1205 Bundle bundle = new Bundle();
1206 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1207 super.onResult(bundle);
1208 return;
1209 } else {
1210 super.onResult(result);
1211 }
1212 }
1213 }.bind();
1214 } finally {
1215 restoreCallingIdentity(identityToken);
1216 }
1217 }
1218
Fred Quintanaa698f422009-04-08 19:14:54 -07001219 public void getAuthToken(IAccountManagerResponse response, final Account account,
1220 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001221 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001222 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1223 Log.v(TAG, "getAuthToken: " + account
1224 + ", response " + response
1225 + ", authTokenType " + authTokenType
1226 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1227 + ", expectActivityLaunch " + expectActivityLaunch
1228 + ", caller's uid " + Binder.getCallingUid()
1229 + ", pid " + Binder.getCallingPid());
1230 }
Fred Quintana382601f2010-03-25 12:25:10 -07001231 if (response == null) throw new IllegalArgumentException("response is null");
1232 if (account == null) throw new IllegalArgumentException("account is null");
1233 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001234 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001235 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001236 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1237 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1238 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001239 final boolean customTokens =
1240 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1241
1242 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001243 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001244 final boolean permissionGranted = customTokens ||
1245 permissionIsGranted(account, authTokenType, callerUid);
1246
Costin Manolachec6684f92011-01-14 11:25:39 -08001247 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1248 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001249 // let authenticator know the identity of the caller
1250 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1251 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1252 if (notifyOnAuthFailure) {
1253 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001254 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001255
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001256 long identityToken = clearCallingIdentity();
1257 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001258 // if the caller has permission, do the peek. otherwise go the more expensive
1259 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001260 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001261 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001262 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001263 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001264 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1265 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1266 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001267 onResult(response, result);
1268 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001269 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001270 }
1271
Amith Yamasani04e0d262012-02-14 11:50:53 -08001272 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001273 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001274 protected String toDebugString(long now) {
1275 if (loginOptions != null) loginOptions.keySet();
1276 return super.toDebugString(now) + ", getAuthToken"
1277 + ", " + account
1278 + ", authTokenType " + authTokenType
1279 + ", loginOptions " + loginOptions
1280 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1281 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001282
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001283 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001284 // If the caller doesn't have permission then create and return the
1285 // "grant permission" intent instead of the "getAuthToken" intent.
1286 if (!permissionGranted) {
1287 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1288 } else {
1289 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1290 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001291 }
1292
1293 public void onResult(Bundle result) {
1294 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001295 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001296 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1297 new AccountAuthenticatorResponse(this),
1298 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001299 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001300 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001301 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001302 onResult(bundle);
1303 return;
1304 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001305 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001306 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001307 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1308 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001309 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001310 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001311 "the type and name should not be empty");
1312 return;
1313 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001314 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001315 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001316 authTokenType, authToken);
1317 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001318 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001319
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001320 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001321 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001322 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001323 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001324 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001325 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001326 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001327 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001328 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001329 }.bind();
1330 } finally {
1331 restoreCallingIdentity(identityToken);
1332 }
Fred Quintana60307342009-03-24 22:48:12 -07001333 }
1334
Dianne Hackborn41203752012-08-31 14:05:51 -07001335 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1336 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001337 int uid = intent.getIntExtra(
1338 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1339 String authTokenType = intent.getStringExtra(
1340 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1341 String authTokenLabel = intent.getStringExtra(
1342 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1343
1344 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1345 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001346 final String titleAndSubtitle =
1347 mContext.getString(R.string.permission_request_notification_with_subtitle,
1348 account.name);
1349 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001350 String title = titleAndSubtitle;
1351 String subtitle = "";
1352 if (index > 0) {
1353 title = titleAndSubtitle.substring(0, index);
1354 subtitle = titleAndSubtitle.substring(index + 1);
1355 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001356 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001357 n.setLatestEventInfo(mContext, title, subtitle,
1358 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001359 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1360 installNotification(getCredentialPermissionNotificationId(
1361 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001362 }
1363
Costin Manolache5f383ad92010-12-02 16:44:46 -08001364 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1365 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001366
1367 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001368 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001369 // Since it was set in Eclair+ we can't change it without breaking apps using
1370 // the intent from a non-Activity context.
1371 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001372 intent.addCategory(
1373 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001374
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001375 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001376 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1377 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001378 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001379
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001380 return intent;
1381 }
1382
1383 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1384 int uid) {
1385 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001386 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001387 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001388 final Pair<Pair<Account, String>, Integer> key =
1389 new Pair<Pair<Account, String>, Integer>(
1390 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001391 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001392 if (id == null) {
1393 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001394 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001395 }
1396 }
1397 return id;
1398 }
1399
Amith Yamasani04e0d262012-02-14 11:50:53 -08001400 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001401 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001402 synchronized (accounts.signinRequiredNotificationIds) {
1403 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001404 if (id == null) {
1405 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001406 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001407 }
1408 }
1409 return id;
1410 }
1411
Fred Quintana33269202009-04-20 16:05:10 -07001412 public void addAcount(final IAccountManagerResponse response, final String accountType,
1413 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001414 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001415 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1416 Log.v(TAG, "addAccount: accountType " + accountType
1417 + ", response " + response
1418 + ", authTokenType " + authTokenType
1419 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1420 + ", expectActivityLaunch " + expectActivityLaunch
1421 + ", caller's uid " + Binder.getCallingUid()
1422 + ", pid " + Binder.getCallingPid());
1423 }
Fred Quintana382601f2010-03-25 12:25:10 -07001424 if (response == null) throw new IllegalArgumentException("response is null");
1425 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001426 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001427
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001428 // Is user allowed to modify accounts?
1429 if (!getUserManager().getUserRestrictions(Binder.getCallingUserHandle())
1430 .getBoolean(UserManager.ALLOW_MODIFY_ACCOUNTS)) {
1431 try {
1432 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1433 "User is not allowed to add an account!");
1434 } catch (RemoteException re) {
1435 }
1436 return;
1437 }
1438
Amith Yamasani04e0d262012-02-14 11:50:53 -08001439 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001440 final int pid = Binder.getCallingPid();
1441 final int uid = Binder.getCallingUid();
1442 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1443 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1444 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1445
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001446 long identityToken = clearCallingIdentity();
1447 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001448 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001449 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001450 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001451 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001452 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001453 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001454
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001455 protected String toDebugString(long now) {
1456 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001457 + ", accountType " + accountType
1458 + ", requiredFeatures "
1459 + (requiredFeatures != null
1460 ? TextUtils.join(",", requiredFeatures)
1461 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001462 }
1463 }.bind();
1464 } finally {
1465 restoreCallingIdentity(identityToken);
1466 }
Fred Quintana60307342009-03-24 22:48:12 -07001467 }
1468
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001469 @Override
1470 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1471 final Account account, final Bundle options, final boolean expectActivityLaunch,
1472 int userId) {
1473 // Only allow the system process to read accounts of other users
1474 if (userId != UserHandle.getCallingUserId()
1475 && Binder.getCallingUid() != android.os.Process.myUid()) {
1476 throw new SecurityException("User " + UserHandle.getCallingUserId()
1477 + " trying to confirm account credentials for " + userId);
1478 }
1479
Fred Quintana56285a62010-12-02 14:20:51 -08001480 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1481 Log.v(TAG, "confirmCredentials: " + account
1482 + ", response " + response
1483 + ", expectActivityLaunch " + expectActivityLaunch
1484 + ", caller's uid " + Binder.getCallingUid()
1485 + ", pid " + Binder.getCallingPid());
1486 }
Fred Quintana382601f2010-03-25 12:25:10 -07001487 if (response == null) throw new IllegalArgumentException("response is null");
1488 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001489 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001490 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001491 long identityToken = clearCallingIdentity();
1492 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001493 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001494 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001495 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001496 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001497 }
1498 protected String toDebugString(long now) {
1499 return super.toDebugString(now) + ", confirmCredentials"
1500 + ", " + account;
1501 }
1502 }.bind();
1503 } finally {
1504 restoreCallingIdentity(identityToken);
1505 }
Fred Quintana60307342009-03-24 22:48:12 -07001506 }
1507
Fred Quintanaa698f422009-04-08 19:14:54 -07001508 public void updateCredentials(IAccountManagerResponse response, final Account account,
1509 final String authTokenType, final boolean expectActivityLaunch,
1510 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001511 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1512 Log.v(TAG, "updateCredentials: " + account
1513 + ", response " + response
1514 + ", authTokenType " + authTokenType
1515 + ", expectActivityLaunch " + expectActivityLaunch
1516 + ", caller's uid " + Binder.getCallingUid()
1517 + ", pid " + Binder.getCallingPid());
1518 }
Fred Quintana382601f2010-03-25 12:25:10 -07001519 if (response == null) throw new IllegalArgumentException("response is null");
1520 if (account == null) throw new IllegalArgumentException("account is null");
1521 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001522 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001523 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001524 long identityToken = clearCallingIdentity();
1525 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001526 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001527 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001528 public void run() throws RemoteException {
1529 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1530 }
1531 protected String toDebugString(long now) {
1532 if (loginOptions != null) loginOptions.keySet();
1533 return super.toDebugString(now) + ", updateCredentials"
1534 + ", " + account
1535 + ", authTokenType " + authTokenType
1536 + ", loginOptions " + loginOptions;
1537 }
1538 }.bind();
1539 } finally {
1540 restoreCallingIdentity(identityToken);
1541 }
Fred Quintana60307342009-03-24 22:48:12 -07001542 }
1543
Fred Quintanaa698f422009-04-08 19:14:54 -07001544 public void editProperties(IAccountManagerResponse response, final String accountType,
1545 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001546 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1547 Log.v(TAG, "editProperties: accountType " + accountType
1548 + ", response " + response
1549 + ", expectActivityLaunch " + expectActivityLaunch
1550 + ", caller's uid " + Binder.getCallingUid()
1551 + ", pid " + Binder.getCallingPid());
1552 }
Fred Quintana382601f2010-03-25 12:25:10 -07001553 if (response == null) throw new IllegalArgumentException("response is null");
1554 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001555 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001556 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001557 long identityToken = clearCallingIdentity();
1558 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001559 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001560 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001561 public void run() throws RemoteException {
1562 mAuthenticator.editProperties(this, mAccountType);
1563 }
1564 protected String toDebugString(long now) {
1565 return super.toDebugString(now) + ", editProperties"
1566 + ", accountType " + accountType;
1567 }
1568 }.bind();
1569 } finally {
1570 restoreCallingIdentity(identityToken);
1571 }
Fred Quintana60307342009-03-24 22:48:12 -07001572 }
1573
Fred Quintana33269202009-04-20 16:05:10 -07001574 private class GetAccountsByTypeAndFeatureSession extends Session {
1575 private final String[] mFeatures;
1576 private volatile Account[] mAccountsOfType = null;
1577 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1578 private volatile int mCurrentAccount = 0;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001579 private int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001580
Amith Yamasani04e0d262012-02-14 11:50:53 -08001581 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001582 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001583 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001584 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001585 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001586 mFeatures = features;
1587 }
1588
1589 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001590 synchronized (mAccounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001591 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001592 }
Fred Quintana33269202009-04-20 16:05:10 -07001593 // check whether each account matches the requested features
1594 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1595 mCurrentAccount = 0;
1596
1597 checkAccount();
1598 }
1599
1600 public void checkAccount() {
1601 if (mCurrentAccount >= mAccountsOfType.length) {
1602 sendResult();
1603 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001604 }
Fred Quintana33269202009-04-20 16:05:10 -07001605
Fred Quintana29e94b82010-03-10 12:11:51 -08001606 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1607 if (accountAuthenticator == null) {
1608 // It is possible that the authenticator has died, which is indicated by
1609 // mAuthenticator being set to null. If this happens then just abort.
1610 // There is no need to send back a result or error in this case since
1611 // that already happened when mAuthenticator was cleared.
1612 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1613 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1614 + " connected to the authenticator, " + toDebugString());
1615 }
1616 return;
1617 }
Fred Quintana33269202009-04-20 16:05:10 -07001618 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001619 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001620 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001621 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001622 }
1623 }
1624
1625 public void onResult(Bundle result) {
1626 mNumResults++;
1627 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001628 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001629 return;
1630 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001631 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001632 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1633 }
1634 mCurrentAccount++;
1635 checkAccount();
1636 }
1637
1638 public void sendResult() {
1639 IAccountManagerResponse response = getResponseAndClose();
1640 if (response != null) {
1641 try {
1642 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1643 for (int i = 0; i < accounts.length; i++) {
1644 accounts[i] = mAccountsWithFeatures.get(i);
1645 }
Fred Quintana56285a62010-12-02 14:20:51 -08001646 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1647 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1648 + response);
1649 }
Fred Quintana33269202009-04-20 16:05:10 -07001650 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001651 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001652 response.onResult(result);
1653 } catch (RemoteException e) {
1654 // if the caller is dead then there is no one to care about remote exceptions
1655 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1656 Log.v(TAG, "failure while notifying response", e);
1657 }
1658 }
1659 }
1660 }
1661
1662
1663 protected String toDebugString(long now) {
1664 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1665 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1666 }
1667 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001668
Amith Yamasani04e0d262012-02-14 11:50:53 -08001669 /**
1670 * Returns the accounts for a specific user
1671 * @hide
1672 */
1673 public Account[] getAccounts(int userId) {
1674 checkReadAccountsPermission();
1675 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001676 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001677 long identityToken = clearCallingIdentity();
1678 try {
1679 synchronized (accounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001680 return getAccountsFromCacheLocked(accounts, null, callingUid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001681 }
1682 } finally {
1683 restoreCallingIdentity(identityToken);
1684 }
1685 }
1686
Amith Yamasanif29f2362012-04-05 18:29:52 -07001687 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001688 * Returns accounts for all running users.
1689 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001690 * @hide
1691 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001692 public AccountAndUser[] getRunningAccounts() {
1693 final int[] runningUserIds;
1694 try {
1695 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1696 } catch (RemoteException e) {
1697 // Running in system_server; should never happen
1698 throw new RuntimeException(e);
1699 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001700 return getAccounts(runningUserIds);
1701 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001702
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001703 /** {@hide} */
1704 public AccountAndUser[] getAllAccounts() {
1705 final List<UserInfo> users = getUserManager().getUsers();
1706 final int[] userIds = new int[users.size()];
1707 for (int i = 0; i < userIds.length; i++) {
1708 userIds[i] = users.get(i).id;
1709 }
1710 return getAccounts(userIds);
1711 }
1712
1713 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001714 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1715 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001716 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001717 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001718 if (userAccounts == null) continue;
1719 synchronized (userAccounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001720 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
1721 Binder.getCallingUid());
Amith Yamasanif29f2362012-04-05 18:29:52 -07001722 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001723 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001724 }
1725 }
1726 }
1727 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001728
1729 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1730 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001731 }
1732
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001733 @Override
1734 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001735 final int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001736 // Only allow the system process to read accounts of other users
1737 if (userId != UserHandle.getCallingUserId()
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001738 && callingUid != android.os.Process.myUid()) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001739 throw new SecurityException("User " + UserHandle.getCallingUserId()
1740 + " trying to get account for " + userId);
1741 }
1742
Fred Quintana56285a62010-12-02 14:20:51 -08001743 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1744 Log.v(TAG, "getAccounts: accountType " + type
1745 + ", caller's uid " + Binder.getCallingUid()
1746 + ", pid " + Binder.getCallingPid());
1747 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001748 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001749 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001750 long identityToken = clearCallingIdentity();
1751 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001752 synchronized (accounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001753 return getAccountsFromCacheLocked(accounts, type, callingUid);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001754 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001755 } finally {
1756 restoreCallingIdentity(identityToken);
1757 }
1758 }
1759
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001760 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001761 public boolean addSharedAccountAsUser(Account account, int userId) {
1762 userId = handleIncomingUser(userId);
1763 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1764 ContentValues values = new ContentValues();
1765 values.put(ACCOUNTS_NAME, account.name);
1766 values.put(ACCOUNTS_TYPE, account.type);
1767 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1768 new String[] {account.name, account.type});
1769 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1770 if (accountId < 0) {
1771 Log.w(TAG, "insertAccountIntoDatabase: " + account
1772 + ", skipping the DB insert failed");
1773 return false;
1774 }
1775 return true;
1776 }
1777
1778 @Override
1779 public boolean removeSharedAccountAsUser(Account account, int userId) {
1780 userId = handleIncomingUser(userId);
1781 UserAccounts accounts = getUserAccounts(userId);
1782 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1783 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1784 new String[] {account.name, account.type});
1785 if (r > 0) {
1786 removeAccountInternal(accounts, account);
1787 }
1788 return r > 0;
1789 }
1790
1791 @Override
1792 public Account[] getSharedAccountsAsUser(int userId) {
1793 userId = handleIncomingUser(userId);
1794 UserAccounts accounts = getUserAccounts(userId);
1795 ArrayList<Account> accountList = new ArrayList<Account>();
1796 Cursor cursor = null;
1797 try {
1798 cursor = accounts.openHelper.getReadableDatabase()
1799 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1800 null, null, null, null, null);
1801 if (cursor != null && cursor.moveToFirst()) {
1802 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1803 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1804 do {
1805 accountList.add(new Account(cursor.getString(nameIndex),
1806 cursor.getString(typeIndex)));
1807 } while (cursor.moveToNext());
1808 }
1809 } finally {
1810 if (cursor != null) {
1811 cursor.close();
1812 }
1813 }
1814 Account[] accountArray = new Account[accountList.size()];
1815 accountList.toArray(accountArray);
1816 return accountArray;
1817 }
1818
1819 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001820 public Account[] getAccounts(String type) {
1821 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1822 }
1823
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001824 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001825 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001826 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1827 Log.v(TAG, "getAccounts: accountType " + type
1828 + ", response " + response
1829 + ", features " + stringArrayToString(features)
1830 + ", caller's uid " + Binder.getCallingUid()
1831 + ", pid " + Binder.getCallingPid());
1832 }
Fred Quintana382601f2010-03-25 12:25:10 -07001833 if (response == null) throw new IllegalArgumentException("response is null");
1834 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001835 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001836 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001837 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001838 long identityToken = clearCallingIdentity();
1839 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001840 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001841 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001842 synchronized (userAccounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001843 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001844 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001845 Bundle result = new Bundle();
1846 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1847 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001848 return;
1849 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001850 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
1851 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001852 } finally {
1853 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001854 }
1855 }
1856
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001857 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001858 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001859 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001860 try {
1861 if (cursor.moveToNext()) {
1862 return cursor.getLong(0);
1863 }
1864 return -1;
1865 } finally {
1866 cursor.close();
1867 }
1868 }
1869
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001870 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001871 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1872 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1873 new String[]{key}, null, null, null);
1874 try {
1875 if (cursor.moveToNext()) {
1876 return cursor.getLong(0);
1877 }
1878 return -1;
1879 } finally {
1880 cursor.close();
1881 }
1882 }
1883
Fred Quintanaa698f422009-04-08 19:14:54 -07001884 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001885 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001886 IAccountManagerResponse mResponse;
1887 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001888 final boolean mExpectActivityLaunch;
1889 final long mCreationTime;
1890
Fred Quintana33269202009-04-20 16:05:10 -07001891 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001892 private int mNumRequestContinued = 0;
1893 private int mNumErrors = 0;
1894
Fred Quintana60307342009-03-24 22:48:12 -07001895 IAccountAuthenticator mAuthenticator = null;
1896
Fred Quintana8570f742010-02-18 10:32:54 -08001897 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001898 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001899
Amith Yamasani04e0d262012-02-14 11:50:53 -08001900 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001901 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001902 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001903 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001904 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001905 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001906 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001907 mResponse = response;
1908 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001909 mExpectActivityLaunch = expectActivityLaunch;
1910 mCreationTime = SystemClock.elapsedRealtime();
1911 synchronized (mSessions) {
1912 mSessions.put(toString(), this);
1913 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001914 if (response != null) {
1915 try {
1916 response.asBinder().linkToDeath(this, 0 /* flags */);
1917 } catch (RemoteException e) {
1918 mResponse = null;
1919 binderDied();
1920 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001921 }
Fred Quintana60307342009-03-24 22:48:12 -07001922 }
1923
Fred Quintanaa698f422009-04-08 19:14:54 -07001924 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001925 if (mResponse == null) {
1926 // this session has already been closed
1927 return null;
1928 }
Fred Quintana60307342009-03-24 22:48:12 -07001929 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001930 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001931 return response;
1932 }
1933
Fred Quintanaa698f422009-04-08 19:14:54 -07001934 private void close() {
1935 synchronized (mSessions) {
1936 if (mSessions.remove(toString()) == null) {
1937 // the session was already closed, so bail out now
1938 return;
1939 }
1940 }
1941 if (mResponse != null) {
1942 // stop listening for response deaths
1943 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1944
1945 // clear this so that we don't accidentally send any further results
1946 mResponse = null;
1947 }
1948 cancelTimeout();
1949 unbind();
1950 }
1951
1952 public void binderDied() {
1953 mResponse = null;
1954 close();
1955 }
1956
1957 protected String toDebugString() {
1958 return toDebugString(SystemClock.elapsedRealtime());
1959 }
1960
1961 protected String toDebugString(long now) {
1962 return "Session: expectLaunch " + mExpectActivityLaunch
1963 + ", connected " + (mAuthenticator != null)
1964 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1965 + "/" + mNumErrors + ")"
1966 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1967 }
1968
Fred Quintana60307342009-03-24 22:48:12 -07001969 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001970 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1971 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1972 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001973 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001974 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001975 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001976 }
1977 }
1978
1979 private void unbind() {
1980 if (mAuthenticator != null) {
1981 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001982 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001983 }
1984 }
1985
1986 public void scheduleTimeout() {
1987 mMessageHandler.sendMessageDelayed(
1988 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1989 }
1990
1991 public void cancelTimeout() {
1992 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1993 }
1994
Fred Quintanab839afc2009-10-14 15:57:28 -07001995 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001996 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001997 try {
1998 run();
1999 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002000 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002001 "remote exception");
2002 }
Fred Quintana60307342009-03-24 22:48:12 -07002003 }
2004
Fred Quintanab839afc2009-10-14 15:57:28 -07002005 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002006 mAuthenticator = null;
2007 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002008 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002009 try {
2010 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2011 "disconnected");
2012 } catch (RemoteException e) {
2013 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2014 Log.v(TAG, "Session.onServiceDisconnected: "
2015 + "caught RemoteException while responding", e);
2016 }
2017 }
Fred Quintana60307342009-03-24 22:48:12 -07002018 }
2019 }
2020
Fred Quintanab839afc2009-10-14 15:57:28 -07002021 public abstract void run() throws RemoteException;
2022
Fred Quintana60307342009-03-24 22:48:12 -07002023 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002024 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002025 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002026 try {
2027 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2028 "timeout");
2029 } catch (RemoteException e) {
2030 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2031 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2032 e);
2033 }
2034 }
Fred Quintana60307342009-03-24 22:48:12 -07002035 }
2036 }
2037
Fred Quintanaa698f422009-04-08 19:14:54 -07002038 public void onResult(Bundle result) {
2039 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002040 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
2041 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2042 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002043 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2044 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002045 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2046 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002047 }
Fred Quintana60307342009-03-24 22:48:12 -07002048 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002049 IAccountManagerResponse response;
2050 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002051 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002052 response = mResponse;
2053 } else {
2054 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002055 }
Fred Quintana60307342009-03-24 22:48:12 -07002056 if (response != null) {
2057 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002058 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002059 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2060 Log.v(TAG, getClass().getSimpleName()
2061 + " calling onError() on response " + response);
2062 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002063 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002064 "null bundle returned");
2065 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002066 if (mStripAuthTokenFromResult) {
2067 result.remove(AccountManager.KEY_AUTHTOKEN);
2068 }
Fred Quintana56285a62010-12-02 14:20:51 -08002069 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2070 Log.v(TAG, getClass().getSimpleName()
2071 + " calling onResult() on response " + response);
2072 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002073 response.onResult(result);
2074 }
Fred Quintana60307342009-03-24 22:48:12 -07002075 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002076 // if the caller is dead then there is no one to care about remote exceptions
2077 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2078 Log.v(TAG, "failure while notifying response", e);
2079 }
Fred Quintana60307342009-03-24 22:48:12 -07002080 }
2081 }
2082 }
Fred Quintana60307342009-03-24 22:48:12 -07002083
Fred Quintanaa698f422009-04-08 19:14:54 -07002084 public void onRequestContinued() {
2085 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002086 }
2087
2088 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002089 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002090 IAccountManagerResponse response = getResponseAndClose();
2091 if (response != null) {
2092 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002093 Log.v(TAG, getClass().getSimpleName()
2094 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002095 }
2096 try {
2097 response.onError(errorCode, errorMessage);
2098 } catch (RemoteException e) {
2099 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2100 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2101 }
2102 }
2103 } else {
2104 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2105 Log.v(TAG, "Session.onError: already closed");
2106 }
Fred Quintana60307342009-03-24 22:48:12 -07002107 }
2108 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002109
2110 /**
2111 * find the component name for the authenticator and initiate a bind
2112 * if no authenticator or the bind fails then return false, otherwise return true
2113 */
2114 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002115 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2116 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2117 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002118 if (authenticatorInfo == null) {
2119 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2120 Log.v(TAG, "there is no authenticator for " + authenticatorType
2121 + ", bailing out");
2122 }
2123 return false;
2124 }
2125
2126 Intent intent = new Intent();
2127 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2128 intent.setComponent(authenticatorInfo.componentName);
2129 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2130 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2131 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002132 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2133 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002134 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2135 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2136 }
2137 return false;
2138 }
2139
2140
2141 return true;
2142 }
Fred Quintana60307342009-03-24 22:48:12 -07002143 }
2144
2145 private class MessageHandler extends Handler {
2146 MessageHandler(Looper looper) {
2147 super(looper);
2148 }
Costin Manolache3348f142009-09-29 18:58:36 -07002149
Fred Quintana60307342009-03-24 22:48:12 -07002150 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002151 switch (msg.what) {
2152 case MESSAGE_TIMED_OUT:
2153 Session session = (Session)msg.obj;
2154 session.onTimedOut();
2155 break;
2156
2157 default:
2158 throw new IllegalStateException("unhandled message: " + msg.what);
2159 }
2160 }
2161 }
2162
Amith Yamasani04e0d262012-02-14 11:50:53 -08002163 private static String getDatabaseName(int userId) {
2164 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002165 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002166 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002167 // Migrate old file, if it exists, to the new location.
2168 // Make sure the new file doesn't already exist. A dummy file could have been
2169 // accidentally created in the old location, causing the new one to become corrupted
2170 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002171 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002172 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002173 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002174 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002175 if (!userDir.exists()) {
2176 if (!userDir.mkdirs()) {
2177 throw new IllegalStateException("User dir cannot be created: " + userDir);
2178 }
2179 }
2180 if (!oldFile.renameTo(databaseFile)) {
2181 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2182 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002183 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002184 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002185 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002186 }
2187
Amith Yamasani04e0d262012-02-14 11:50:53 -08002188 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002189
Amith Yamasani04e0d262012-02-14 11:50:53 -08002190 public DatabaseHelper(Context context, int userId) {
2191 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002192 }
2193
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002194 /**
2195 * This call needs to be made while the mCacheLock is held. The way to
2196 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2197 * @param db The database.
2198 */
Fred Quintana60307342009-03-24 22:48:12 -07002199 @Override
2200 public void onCreate(SQLiteDatabase db) {
2201 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2202 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2203 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2204 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2205 + ACCOUNTS_PASSWORD + " TEXT, "
2206 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2207
2208 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2209 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2210 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2211 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2212 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2213 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2214
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002215 createGrantsTable(db);
2216
Fred Quintana60307342009-03-24 22:48:12 -07002217 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2218 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2219 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2220 + EXTRAS_KEY + " TEXT NOT NULL, "
2221 + EXTRAS_VALUE + " TEXT, "
2222 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2223
2224 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2225 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2226 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002227
Amith Yamasani67df64b2012-12-14 12:09:36 -08002228 createSharedAccountsTable(db);
2229
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002230 createAccountsDeletionTrigger(db);
2231 }
2232
Amith Yamasani67df64b2012-12-14 12:09:36 -08002233 private void createSharedAccountsTable(SQLiteDatabase db) {
2234 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2235 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2236 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2237 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2238 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2239 }
2240
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002241 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002242 db.execSQL(""
2243 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2244 + " BEGIN"
2245 + " DELETE FROM " + TABLE_AUTHTOKENS
2246 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2247 + " DELETE FROM " + TABLE_EXTRAS
2248 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002249 + " DELETE FROM " + TABLE_GRANTS
2250 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002251 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002252 }
2253
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002254 private void createGrantsTable(SQLiteDatabase db) {
2255 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2256 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2257 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2258 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2259 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2260 + "," + GRANTS_GRANTEE_UID + "))");
2261 }
2262
Fred Quintana60307342009-03-24 22:48:12 -07002263 @Override
2264 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002265 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002266
Fred Quintanaa698f422009-04-08 19:14:54 -07002267 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002268 // no longer need to do anything since the work is done
2269 // when upgrading from version 2
2270 oldVersion++;
2271 }
2272
2273 if (oldVersion == 2) {
2274 createGrantsTable(db);
2275 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2276 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002277 oldVersion++;
2278 }
Costin Manolache3348f142009-09-29 18:58:36 -07002279
2280 if (oldVersion == 3) {
2281 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2282 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2283 oldVersion++;
2284 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002285
2286 if (oldVersion == 4) {
2287 createSharedAccountsTable(db);
2288 oldVersion++;
2289 }
2290
2291 if (oldVersion != newVersion) {
2292 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2293 }
Fred Quintana60307342009-03-24 22:48:12 -07002294 }
2295
2296 @Override
2297 public void onOpen(SQLiteDatabase db) {
2298 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2299 }
2300 }
2301
Fred Quintana60307342009-03-24 22:48:12 -07002302 public IBinder onBind(Intent intent) {
2303 return asBinder();
2304 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002305
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002306 /**
2307 * Searches array of arguments for the specified string
2308 * @param args array of argument strings
2309 * @param value value to search for
2310 * @return true if the value is contained in the array
2311 */
2312 private static boolean scanArgs(String[] args, String value) {
2313 if (args != null) {
2314 for (String arg : args) {
2315 if (value.equals(arg)) {
2316 return true;
2317 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002318 }
2319 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002320 return false;
2321 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002322
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002323 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002324 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002325 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2326 != PackageManager.PERMISSION_GRANTED) {
2327 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2328 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2329 + " without permission " + android.Manifest.permission.DUMP);
2330 return;
2331 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002332 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002333 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002334
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002335 final List<UserInfo> users = getUserManager().getUsers();
2336 for (UserInfo user : users) {
2337 ipw.println("User " + user + ":");
2338 ipw.increaseIndent();
2339 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2340 ipw.println();
2341 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002342 }
2343 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002344
Amith Yamasani04e0d262012-02-14 11:50:53 -08002345 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2346 String[] args, boolean isCheckinRequest) {
2347 synchronized (userAccounts.cacheLock) {
2348 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002349
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002350 if (isCheckinRequest) {
2351 // This is a checkin request. *Only* upload the account types and the count of each.
2352 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2353 null, null, ACCOUNTS_TYPE, null, null);
2354 try {
2355 while (cursor.moveToNext()) {
2356 // print type,count
2357 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2358 }
2359 } finally {
2360 if (cursor != null) {
2361 cursor.close();
2362 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002363 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002364 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002365 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
2366 android.os.Process.myUid());
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002367 fout.println("Accounts: " + accounts.length);
2368 for (Account account : accounts) {
2369 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002370 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002371
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002372 fout.println();
2373 synchronized (mSessions) {
2374 final long now = SystemClock.elapsedRealtime();
2375 fout.println("Active Sessions: " + mSessions.size());
2376 for (Session session : mSessions.values()) {
2377 fout.println(" " + session.toDebugString(now));
2378 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002379 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002380
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002381 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002382 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002383 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002384 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002385 }
2386
Amith Yamasani04e0d262012-02-14 11:50:53 -08002387 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002388 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002389 long identityToken = clearCallingIdentity();
2390 try {
2391 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2392 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2393 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002394
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002395 if (intent.getComponent() != null &&
2396 GrantCredentialsPermissionActivity.class.getName().equals(
2397 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002398 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002399 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002400 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002401 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002402 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2403 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002404 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002405 final String notificationTitleFormat =
2406 mContext.getText(R.string.notification_title).toString();
2407 n.setLatestEventInfo(mContext,
2408 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002409 message, PendingIntent.getActivityAsUser(
2410 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002411 null, user));
2412 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002413 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002414 } finally {
2415 restoreCallingIdentity(identityToken);
2416 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002417 }
2418
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002419 protected void installNotification(final int notificationId, final Notification n,
2420 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002421 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002422 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002423 }
2424
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002425 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002426 long identityToken = clearCallingIdentity();
2427 try {
2428 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002429 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002430 } finally {
2431 restoreCallingIdentity(identityToken);
2432 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002433 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002434
Fred Quintanab38eb142010-02-24 13:40:54 -08002435 /** Succeeds if any of the specified permissions are granted. */
2436 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002437 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002438
2439 for (String perm : permissions) {
2440 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2441 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002442 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002443 }
2444 return;
2445 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002446 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002447
2448 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002449 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002450 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002451 }
2452
Amith Yamasani67df64b2012-12-14 12:09:36 -08002453 private int handleIncomingUser(int userId) {
2454 try {
2455 return ActivityManagerNative.getDefault().handleIncomingUser(
2456 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2457 } catch (RemoteException re) {
2458 // Shouldn't happen, local.
2459 }
2460 return userId;
2461 }
2462
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002463 private boolean inSystemImage(int callingUid) {
2464 final int callingUserId = UserHandle.getUserId(callingUid);
2465
2466 final PackageManager userPackageManager;
2467 try {
2468 userPackageManager = mContext.createPackageContextAsUser(
2469 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2470 } catch (NameNotFoundException e) {
2471 return false;
2472 }
2473
2474 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002475 for (String name : packages) {
2476 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002477 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002478 if (packageInfo != null
2479 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002480 return true;
2481 }
2482 } catch (PackageManager.NameNotFoundException e) {
2483 return false;
2484 }
2485 }
2486 return false;
2487 }
2488
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002489 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002490 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002491 final boolean fromAuthenticator = account != null
2492 && hasAuthenticatorUid(account.type, callerUid);
2493 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002494 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002495 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2496 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002497 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002498 + ": is authenticator? " + fromAuthenticator
2499 + ", has explicit permission? " + hasExplicitGrants);
2500 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002501 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002502 }
2503
Fred Quintana1a231912009-10-15 11:31:30 -07002504 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002505 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002506 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002507 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002508 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002509 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002510 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002511 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002512 }
2513 }
2514 return false;
2515 }
2516
Amith Yamasani04e0d262012-02-14 11:50:53 -08002517 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2518 int callerUid) {
2519 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002520 return true;
2521 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002522 UserAccounts accounts = getUserAccountsForCaller();
2523 synchronized (accounts.cacheLock) {
2524 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2525 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002526 account.name, account.type};
2527 final boolean permissionGranted =
2528 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2529 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2530 // TODO: Skip this check when running automated tests. Replace this
2531 // with a more general solution.
2532 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002533 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002534 + " but ignoring since device is in test harness.");
2535 return true;
2536 }
2537 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002538 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002539 }
2540
2541 private void checkCallingUidAgainstAuthenticator(Account account) {
2542 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002543 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002544 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2545 Log.w(TAG, msg);
2546 throw new SecurityException(msg);
2547 }
2548 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2549 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2550 }
2551 }
2552
2553 private void checkAuthenticateAccountsPermission(Account account) {
2554 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2555 checkCallingUidAgainstAuthenticator(account);
2556 }
2557
2558 private void checkReadAccountsPermission() {
2559 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2560 }
2561
2562 private void checkManageAccountsPermission() {
2563 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2564 }
2565
Fred Quintanab38eb142010-02-24 13:40:54 -08002566 private void checkManageAccountsOrUseCredentialsPermissions() {
2567 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2568 Manifest.permission.USE_CREDENTIALS);
2569 }
2570
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002571 private boolean canUserModifyAccounts(int callingUid) {
2572 if (callingUid != android.os.Process.myUid()) {
2573 Bundle restrictions = getUserManager().getUserRestrictions(
2574 new UserHandle(UserHandle.getUserId(callingUid)));
2575 if (!restrictions.getBoolean(UserManager.ALLOW_MODIFY_ACCOUNTS)) {
2576 return false;
2577 }
2578 }
2579 return true;
2580 }
2581
Fred Quintanad9640ec2012-05-23 12:37:00 -07002582 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2583 throws RemoteException {
2584 final int callingUid = getCallingUid();
2585
2586 if (callingUid != android.os.Process.SYSTEM_UID) {
2587 throw new SecurityException();
2588 }
2589
2590 if (value) {
2591 grantAppPermission(account, authTokenType, uid);
2592 } else {
2593 revokeAppPermission(account, authTokenType, uid);
2594 }
2595 }
2596
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002597 /**
2598 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2599 * <p>
2600 * Although this is public it can only be accessed via the AccountManagerService object
2601 * which is in the system. This means we don't need to protect it with permissions.
2602 * @hide
2603 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002604 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002605 if (account == null || authTokenType == null) {
2606 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002607 return;
2608 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002609 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002610 synchronized (accounts.cacheLock) {
2611 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002612 db.beginTransaction();
2613 try {
2614 long accountId = getAccountIdLocked(db, account);
2615 if (accountId >= 0) {
2616 ContentValues values = new ContentValues();
2617 values.put(GRANTS_ACCOUNTS_ID, accountId);
2618 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2619 values.put(GRANTS_GRANTEE_UID, uid);
2620 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2621 db.setTransactionSuccessful();
2622 }
2623 } finally {
2624 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002625 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002626 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2627 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002628 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002629 }
2630
2631 /**
2632 * Don't allow callers with the given uid permission to get credentials for
2633 * account/authTokenType.
2634 * <p>
2635 * Although this is public it can only be accessed via the AccountManagerService object
2636 * which is in the system. This means we don't need to protect it with permissions.
2637 * @hide
2638 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002639 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002640 if (account == null || authTokenType == null) {
2641 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002642 return;
2643 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002644 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002645 synchronized (accounts.cacheLock) {
2646 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002647 db.beginTransaction();
2648 try {
2649 long accountId = getAccountIdLocked(db, account);
2650 if (accountId >= 0) {
2651 db.delete(TABLE_GRANTS,
2652 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2653 + GRANTS_GRANTEE_UID + "=?",
2654 new String[]{String.valueOf(accountId), authTokenType,
2655 String.valueOf(uid)});
2656 db.setTransactionSuccessful();
2657 }
2658 } finally {
2659 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002660 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002661 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2662 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002663 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002664 }
Fred Quintana56285a62010-12-02 14:20:51 -08002665
2666 static final private String stringArrayToString(String[] value) {
2667 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2668 }
2669
Amith Yamasani04e0d262012-02-14 11:50:53 -08002670 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2671 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002672 if (oldAccountsForType != null) {
2673 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2674 for (Account curAccount : oldAccountsForType) {
2675 if (!curAccount.equals(account)) {
2676 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002677 }
2678 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002679 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002680 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002681 } else {
2682 Account[] newAccountsForType = new Account[newAccountsList.size()];
2683 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002684 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002685 }
Fred Quintana56285a62010-12-02 14:20:51 -08002686 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002687 accounts.userDataCache.remove(account);
2688 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002689 }
2690
2691 /**
2692 * This assumes that the caller has already checked that the account is not already present.
2693 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002694 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2695 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002696 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2697 Account[] newAccountsForType = new Account[oldLength + 1];
2698 if (accountsForType != null) {
2699 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002700 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002701 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002702 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002703 }
2704
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002705 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
2706 int callingUid) {
2707 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
2708 || callingUid == android.os.Process.myUid()) {
2709 return unfiltered;
2710 }
2711 if (mUserManager.getUserInfo(userAccounts.userId).isRestricted()) {
2712 String[] packages = mPackageManager.getPackagesForUid(callingUid);
2713 // If any of the packages includes a white listed package, return the full set,
2714 // otherwise return non-shared accounts only.
2715 // This might be a temporary way to specify a whitelist
2716 String whiteList = mContext.getResources().getString(
2717 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2718 for (String packageName : packages) {
2719 if (whiteList.contains(";" + packageName + ";")) {
2720 return unfiltered;
2721 }
2722 }
2723 ArrayList<Account> allowed = new ArrayList<Account>();
2724 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2725 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
2726 for (Account account : unfiltered) {
2727 boolean found = false;
2728 for (Account shared : sharedAccounts) {
2729 if (shared.equals(account)) {
2730 found = true;
2731 break;
2732 }
2733 }
2734 if (!found) {
2735 allowed.add(account);
2736 }
2737 }
2738 Account[] filtered = new Account[allowed.size()];
2739 allowed.toArray(filtered);
2740 return filtered;
2741 } else {
2742 return unfiltered;
2743 }
2744 }
2745
2746 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
2747 int callingUid) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002748 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002749 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002750 if (accounts == null) {
2751 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002752 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002753 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
2754 callingUid);
Fred Quintana56285a62010-12-02 14:20:51 -08002755 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002756 } else {
2757 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002758 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002759 totalLength += accounts.length;
2760 }
2761 if (totalLength == 0) {
2762 return EMPTY_ACCOUNT_ARRAY;
2763 }
2764 Account[] accounts = new Account[totalLength];
2765 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002766 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002767 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2768 accountsOfType.length);
2769 totalLength += accountsOfType.length;
2770 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002771 return filterSharedAccounts(userAccounts, accounts, callingUid);
Fred Quintana56285a62010-12-02 14:20:51 -08002772 }
2773 }
2774
Amith Yamasani04e0d262012-02-14 11:50:53 -08002775 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2776 Account account, String key, String value) {
2777 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002778 if (userDataForAccount == null) {
2779 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002780 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002781 }
2782 if (value == null) {
2783 userDataForAccount.remove(key);
2784 } else {
2785 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002786 }
2787 }
2788
Amith Yamasani04e0d262012-02-14 11:50:53 -08002789 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2790 Account account, String key, String value) {
2791 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002792 if (authTokensForAccount == null) {
2793 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002794 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002795 }
2796 if (value == null) {
2797 authTokensForAccount.remove(key);
2798 } else {
2799 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002800 }
2801 }
2802
Amith Yamasani04e0d262012-02-14 11:50:53 -08002803 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2804 String authTokenType) {
2805 synchronized (accounts.cacheLock) {
2806 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002807 if (authTokensForAccount == null) {
2808 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002809 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002810 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002811 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002812 }
2813 return authTokensForAccount.get(authTokenType);
2814 }
2815 }
2816
Amith Yamasani04e0d262012-02-14 11:50:53 -08002817 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2818 synchronized (accounts.cacheLock) {
2819 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002820 if (userDataForAccount == null) {
2821 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002822 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002823 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002824 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002825 }
2826 return userDataForAccount.get(key);
2827 }
2828 }
2829
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002830 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2831 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002832 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002833 Cursor cursor = db.query(TABLE_EXTRAS,
2834 COLUMNS_EXTRAS_KEY_AND_VALUE,
2835 SELECTION_USERDATA_BY_ACCOUNT,
2836 new String[]{account.name, account.type},
2837 null, null, null);
2838 try {
2839 while (cursor.moveToNext()) {
2840 final String tmpkey = cursor.getString(0);
2841 final String value = cursor.getString(1);
2842 userDataForAccount.put(tmpkey, value);
2843 }
2844 } finally {
2845 cursor.close();
2846 }
2847 return userDataForAccount;
2848 }
2849
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002850 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2851 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002852 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002853 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2854 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2855 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2856 new String[]{account.name, account.type},
2857 null, null, null);
2858 try {
2859 while (cursor.moveToNext()) {
2860 final String type = cursor.getString(0);
2861 final String authToken = cursor.getString(1);
2862 authTokensForAccount.put(type, authToken);
2863 }
2864 } finally {
2865 cursor.close();
2866 }
2867 return authTokensForAccount;
2868 }
Fred Quintana60307342009-03-24 22:48:12 -07002869}