blob: 49295f56b3e29ac2193bc37417c9c17b9813e1ed [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 Slog.d(TAG, "onServiceChanged() for userId " + userId);
459 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700460 }
461
Fred Quintanaa698f422009-04-08 19:14:54 -0700462 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800463 if (Log.isLoggable(TAG, Log.VERBOSE)) {
464 Log.v(TAG, "getPassword: " + account
465 + ", caller's uid " + Binder.getCallingUid()
466 + ", pid " + Binder.getCallingPid());
467 }
Fred Quintana382601f2010-03-25 12:25:10 -0700468 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700469 checkAuthenticateAccountsPermission(account);
470
Amith Yamasani04e0d262012-02-14 11:50:53 -0800471 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700472 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700473 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800474 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700475 } finally {
476 restoreCallingIdentity(identityToken);
477 }
478 }
479
Amith Yamasani04e0d262012-02-14 11:50:53 -0800480 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700481 if (account == null) {
482 return null;
483 }
484
Amith Yamasani04e0d262012-02-14 11:50:53 -0800485 synchronized (accounts.cacheLock) {
486 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800487 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
488 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
489 new String[]{account.name, account.type}, null, null, null);
490 try {
491 if (cursor.moveToNext()) {
492 return cursor.getString(0);
493 }
494 return null;
495 } finally {
496 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700497 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700498 }
499 }
500
501 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800502 if (Log.isLoggable(TAG, Log.VERBOSE)) {
503 Log.v(TAG, "getUserData: " + account
504 + ", key " + key
505 + ", caller's uid " + Binder.getCallingUid()
506 + ", pid " + Binder.getCallingPid());
507 }
Fred Quintana382601f2010-03-25 12:25:10 -0700508 if (account == null) throw new IllegalArgumentException("account is null");
509 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700510 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800511 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700512 long identityToken = clearCallingIdentity();
513 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800514 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 } finally {
516 restoreCallingIdentity(identityToken);
517 }
518 }
519
Fred Quintana97889762009-06-15 12:29:24 -0700520 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800521 if (Log.isLoggable(TAG, Log.VERBOSE)) {
522 Log.v(TAG, "getAuthenticatorTypes: "
523 + "caller's uid " + Binder.getCallingUid()
524 + ", pid " + Binder.getCallingPid());
525 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700526 final int userId = UserHandle.getCallingUserId();
527 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700528 try {
Fred Quintana97889762009-06-15 12:29:24 -0700529 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700530 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700531 AuthenticatorDescription[] types =
532 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700533 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700534 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700535 : authenticatorCollection) {
536 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700537 i++;
538 }
539 return types;
540 } finally {
541 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700542 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700543 }
544
Fred Quintanaa698f422009-04-08 19:14:54 -0700545 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800546 if (Log.isLoggable(TAG, Log.VERBOSE)) {
547 Log.v(TAG, "addAccount: " + account
548 + ", caller's uid " + Binder.getCallingUid()
549 + ", pid " + Binder.getCallingPid());
550 }
Fred Quintana382601f2010-03-25 12:25:10 -0700551 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700552 checkAuthenticateAccountsPermission(account);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800553 if (!canUserModifyAccounts(Binder.getCallingUid())) {
554 return false;
555 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700556
Amith Yamasani04e0d262012-02-14 11:50:53 -0800557 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700558 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700559 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700560 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800561 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700562 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700563 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700564 }
565 }
566
Amith Yamasani67df64b2012-12-14 12:09:36 -0800567 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
568 final UserAccounts fromAccounts = getUserAccounts(userFrom);
569 final UserAccounts toAccounts = getUserAccounts(userTo);
570 if (fromAccounts == null || toAccounts == null) {
571 return false;
572 }
573
574 long identityToken = clearCallingIdentity();
575 try {
576 new Session(fromAccounts, null, account.type, false,
577 false /* stripAuthTokenFromResult */) {
578 protected String toDebugString(long now) {
579 return super.toDebugString(now) + ", getAccountCredentialsForClone"
580 + ", " + account.type;
581 }
582
583 public void run() throws RemoteException {
584 mAuthenticator.getAccountCredentialsForCloning(this, account);
585 }
586
587 public void onResult(Bundle result) {
588 if (result != null) {
589 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
590 // Create a Session for the target user and pass in the bundle
591 Slog.i(TAG, "getAccountCredentialsForCloning returned success, "
592 + "sending result to target user");
593 completeCloningAccount(result, account, toAccounts);
594 } else {
595 Slog.e(TAG, "getAccountCredentialsForCloning returned failure");
596 clonePassword(fromAccounts, toAccounts, account);
597 }
598 return;
599 } else {
600 Slog.e(TAG, "getAccountCredentialsForCloning returned null");
601 clonePassword(fromAccounts, toAccounts, account);
602 super.onResult(result);
603 }
604 }
605 }.bind();
606 } finally {
607 restoreCallingIdentity(identityToken);
608 }
609 return true;
610 }
611
612 // TODO: Remove fallback - move to authenticator
613 private void clonePassword(UserAccounts fromAccounts, UserAccounts toAccounts,
614 Account account) {
615 long id = clearCallingIdentity();
616 try {
617 String password = readPasswordInternal(fromAccounts, account);
618 String extraFlags = readUserDataInternal(fromAccounts, account, "flags");
619 String extraServices = readUserDataInternal(fromAccounts, account, "services");
620 Bundle extras = new Bundle();
621 extras.putString("flags", extraFlags);
622 extras.putString("services", extraServices);
623 addAccountInternal(toAccounts, account, password, extras, true);
624 } finally {
625 restoreCallingIdentity(id);
626 }
627 }
628
629 void completeCloningAccount(final Bundle result, final Account account,
630 final UserAccounts targetUser) {
631 long id = clearCallingIdentity();
632 try {
633 new Session(targetUser, null, account.type, false,
634 false /* stripAuthTokenFromResult */) {
635 protected String toDebugString(long now) {
636 return super.toDebugString(now) + ", getAccountCredentialsForClone"
637 + ", " + account.type;
638 }
639
640 public void run() throws RemoteException {
641 mAuthenticator.addAccountFromCredentials(this, account, result);
642 }
643
644 public void onResult(Bundle result) {
645 if (result != null) {
646 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
647 // TODO: Anything?
648 Slog.i(TAG, "addAccount returned success");
649 } else {
650 // TODO: Show error notification
651 // TODO: Should we remove the shadow account to avoid retries?
652 Slog.e(TAG, "addAccountFromCredentials returned failure");
653 }
654 return;
655 } else {
656 Slog.e(TAG, "addAccountFromCredentials returned null");
657 super.onResult(result);
658 }
659 }
660
661 public void onError(int errorCode, String errorMessage) {
662 super.onError(errorCode, errorMessage);
663 // TODO: Show error notification to user
664 // TODO: Should we remove the shadow account so that it doesn't keep trying?
665 }
666
667 }.bind();
668 } finally {
669 restoreCallingIdentity(id);
670 }
671 }
672
Amith Yamasani04e0d262012-02-14 11:50:53 -0800673 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800674 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700675 if (account == null) {
676 return false;
677 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800678 synchronized (accounts.cacheLock) {
679 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800680 db.beginTransaction();
681 try {
682 long numMatches = DatabaseUtils.longForQuery(db,
683 "select count(*) from " + TABLE_ACCOUNTS
684 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
685 new String[]{account.name, account.type});
686 if (numMatches > 0) {
687 Log.w(TAG, "insertAccountIntoDatabase: " + account
688 + ", skipping since the account already exists");
689 return false;
690 }
691 ContentValues values = new ContentValues();
692 values.put(ACCOUNTS_NAME, account.name);
693 values.put(ACCOUNTS_TYPE, account.type);
694 values.put(ACCOUNTS_PASSWORD, password);
695 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
696 if (accountId < 0) {
697 Log.w(TAG, "insertAccountIntoDatabase: " + account
698 + ", skipping the DB insert failed");
699 return false;
700 }
701 if (extras != null) {
702 for (String key : extras.keySet()) {
703 final String value = extras.getString(key);
704 if (insertExtraLocked(db, accountId, key, value) < 0) {
705 Log.w(TAG, "insertAccountIntoDatabase: " + account
706 + ", skipping since insertExtra failed for key " + key);
707 return false;
708 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700709 }
710 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800711 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800712 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800713 } finally {
714 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700715 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800716 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800717 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700718 }
719 }
720
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800721 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700722 ContentValues values = new ContentValues();
723 values.put(EXTRAS_KEY, key);
724 values.put(EXTRAS_ACCOUNTS_ID, accountId);
725 values.put(EXTRAS_VALUE, value);
726 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
727 }
728
Fred Quintana3084a6f2010-01-14 18:02:03 -0800729 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800730 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800731 if (Log.isLoggable(TAG, Log.VERBOSE)) {
732 Log.v(TAG, "hasFeatures: " + account
733 + ", response " + response
734 + ", features " + stringArrayToString(features)
735 + ", caller's uid " + Binder.getCallingUid()
736 + ", pid " + Binder.getCallingPid());
737 }
Fred Quintana382601f2010-03-25 12:25:10 -0700738 if (response == null) throw new IllegalArgumentException("response is null");
739 if (account == null) throw new IllegalArgumentException("account is null");
740 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800741 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800742 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800743 long identityToken = clearCallingIdentity();
744 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800745 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800746 } finally {
747 restoreCallingIdentity(identityToken);
748 }
749 }
750
751 private class TestFeaturesSession extends Session {
752 private final String[] mFeatures;
753 private final Account mAccount;
754
Amith Yamasani04e0d262012-02-14 11:50:53 -0800755 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800756 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800757 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800758 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800759 mFeatures = features;
760 mAccount = account;
761 }
762
763 public void run() throws RemoteException {
764 try {
765 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
766 } catch (RemoteException e) {
767 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
768 }
769 }
770
771 public void onResult(Bundle result) {
772 IAccountManagerResponse response = getResponseAndClose();
773 if (response != null) {
774 try {
775 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700776 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800777 return;
778 }
Fred Quintana56285a62010-12-02 14:20:51 -0800779 if (Log.isLoggable(TAG, Log.VERBOSE)) {
780 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
781 + response);
782 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800783 final Bundle newResult = new Bundle();
784 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
785 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
786 response.onResult(newResult);
787 } catch (RemoteException e) {
788 // if the caller is dead then there is no one to care about remote exceptions
789 if (Log.isLoggable(TAG, Log.VERBOSE)) {
790 Log.v(TAG, "failure while notifying response", e);
791 }
792 }
793 }
794 }
795
796 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800797 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800798 + ", " + mAccount
799 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
800 }
801 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800802
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700803 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800804 if (Log.isLoggable(TAG, Log.VERBOSE)) {
805 Log.v(TAG, "removeAccount: " + account
806 + ", response " + response
807 + ", caller's uid " + Binder.getCallingUid()
808 + ", pid " + Binder.getCallingPid());
809 }
Fred Quintana382601f2010-03-25 12:25:10 -0700810 if (response == null) throw new IllegalArgumentException("response is null");
811 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700812 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700813 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800814 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800815 if (!canUserModifyAccounts(Binder.getCallingUid())) {
816 try {
817 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
818 "User cannot modify accounts");
819 } catch (RemoteException re) {
820 }
821 }
822
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700823 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800824
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700825 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800826 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800827 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800828 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800829 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800830 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700831 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800832 }
833 }
834 }
835
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700836 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800837 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700838 } finally {
839 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700840 }
Fred Quintana60307342009-03-24 22:48:12 -0700841 }
842
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700843 private class RemoveAccountSession extends Session {
844 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800845 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
846 Account account) {
847 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800848 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700849 mAccount = account;
850 }
851
852 protected String toDebugString(long now) {
853 return super.toDebugString(now) + ", removeAccount"
854 + ", account " + mAccount;
855 }
856
857 public void run() throws RemoteException {
858 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
859 }
860
861 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700862 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
863 && !result.containsKey(AccountManager.KEY_INTENT)) {
864 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700865 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800866 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700867 }
868 IAccountManagerResponse response = getResponseAndClose();
869 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800870 if (Log.isLoggable(TAG, Log.VERBOSE)) {
871 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
872 + response);
873 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700874 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700875 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700876 try {
877 response.onResult(result2);
878 } catch (RemoteException e) {
879 // ignore
880 }
881 }
882 }
883 super.onResult(result);
884 }
885 }
886
Amith Yamasani04e0d262012-02-14 11:50:53 -0800887 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800888 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800889 removeAccountInternal(getUserAccountsForCaller(), account);
890 }
891
892 private void removeAccountInternal(UserAccounts accounts, Account account) {
893 synchronized (accounts.cacheLock) {
894 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800895 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
896 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800897 removeAccountFromCacheLocked(accounts, account);
898 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800899 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800900 if (accounts.userId == UserHandle.USER_OWNER) {
901 // Owner's account was removed, remove from any users that are sharing
902 // this account.
903 long id = Binder.clearCallingIdentity();
904 try {
905 List<UserInfo> users = mUserManager.getUsers(true);
906 for (UserInfo user : users) {
907 if (!user.isPrimary() && user.isRestricted()) {
908 removeSharedAccountAsUser(account, user.id);
909 }
910 }
911 } finally {
912 Binder.restoreCallingIdentity(id);
913 }
914 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700915 }
916
Fred Quintanaa698f422009-04-08 19:14:54 -0700917 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800918 if (Log.isLoggable(TAG, Log.VERBOSE)) {
919 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
920 + ", caller's uid " + Binder.getCallingUid()
921 + ", pid " + Binder.getCallingPid());
922 }
Fred Quintana382601f2010-03-25 12:25:10 -0700923 if (accountType == null) throw new IllegalArgumentException("accountType is null");
924 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800925 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800926 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700927 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700928 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800929 synchronized (accounts.cacheLock) {
930 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800931 db.beginTransaction();
932 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800933 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800934 db.setTransactionSuccessful();
935 } finally {
936 db.endTransaction();
937 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700938 }
Fred Quintana60307342009-03-24 22:48:12 -0700939 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700940 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700941 }
942 }
943
Amith Yamasani04e0d262012-02-14 11:50:53 -0800944 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
945 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700946 if (authToken == null || accountType == null) {
947 return;
948 }
Fred Quintana33269202009-04-20 16:05:10 -0700949 Cursor cursor = db.rawQuery(
950 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
951 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
952 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
953 + " FROM " + TABLE_ACCOUNTS
954 + " JOIN " + TABLE_AUTHTOKENS
955 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
956 + " = " + AUTHTOKENS_ACCOUNTS_ID
957 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
958 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
959 new String[]{authToken, accountType});
960 try {
961 while (cursor.moveToNext()) {
962 long authTokenId = cursor.getLong(0);
963 String accountName = cursor.getString(1);
964 String authTokenType = cursor.getString(2);
965 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800966 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800967 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700968 }
Fred Quintana33269202009-04-20 16:05:10 -0700969 } finally {
970 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700971 }
972 }
973
Amith Yamasani04e0d262012-02-14 11:50:53 -0800974 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
975 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700976 if (account == null || type == null) {
977 return false;
978 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700979 cancelNotification(getSigninRequiredNotificationId(accounts, account),
980 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800981 synchronized (accounts.cacheLock) {
982 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800983 db.beginTransaction();
984 try {
985 long accountId = getAccountIdLocked(db, account);
986 if (accountId < 0) {
987 return false;
988 }
989 db.delete(TABLE_AUTHTOKENS,
990 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
991 new String[]{type});
992 ContentValues values = new ContentValues();
993 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
994 values.put(AUTHTOKENS_TYPE, type);
995 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
996 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
997 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800998 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800999 return true;
1000 }
Fred Quintana33269202009-04-20 16:05:10 -07001001 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001002 } finally {
1003 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001004 }
Fred Quintana60307342009-03-24 22:48:12 -07001005 }
1006 }
1007
Fred Quintanaa698f422009-04-08 19:14:54 -07001008 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001009 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1010 Log.v(TAG, "peekAuthToken: " + account
1011 + ", authTokenType " + authTokenType
1012 + ", caller's uid " + Binder.getCallingUid()
1013 + ", pid " + Binder.getCallingPid());
1014 }
Fred Quintana382601f2010-03-25 12:25:10 -07001015 if (account == null) throw new IllegalArgumentException("account is null");
1016 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001017 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001018 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001019 long identityToken = clearCallingIdentity();
1020 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001021 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001022 } finally {
1023 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001024 }
Fred Quintana60307342009-03-24 22:48:12 -07001025 }
1026
Fred Quintanaa698f422009-04-08 19:14:54 -07001027 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001028 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1029 Log.v(TAG, "setAuthToken: " + account
1030 + ", authTokenType " + authTokenType
1031 + ", caller's uid " + Binder.getCallingUid()
1032 + ", pid " + Binder.getCallingPid());
1033 }
Fred Quintana382601f2010-03-25 12:25:10 -07001034 if (account == null) throw new IllegalArgumentException("account is null");
1035 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001036 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001037 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001038 long identityToken = clearCallingIdentity();
1039 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001040 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001041 } finally {
1042 restoreCallingIdentity(identityToken);
1043 }
Fred Quintana60307342009-03-24 22:48:12 -07001044 }
1045
Fred Quintanaa698f422009-04-08 19:14:54 -07001046 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001047 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1048 Log.v(TAG, "setAuthToken: " + account
1049 + ", caller's uid " + Binder.getCallingUid()
1050 + ", pid " + Binder.getCallingPid());
1051 }
Fred Quintana382601f2010-03-25 12:25:10 -07001052 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001053 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001054 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001055 long identityToken = clearCallingIdentity();
1056 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001057 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001058 } finally {
1059 restoreCallingIdentity(identityToken);
1060 }
Fred Quintana60307342009-03-24 22:48:12 -07001061 }
1062
Amith Yamasani04e0d262012-02-14 11:50:53 -08001063 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001064 if (account == null) {
1065 return;
1066 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001067 synchronized (accounts.cacheLock) {
1068 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001069 db.beginTransaction();
1070 try {
1071 final ContentValues values = new ContentValues();
1072 values.put(ACCOUNTS_PASSWORD, password);
1073 final long accountId = getAccountIdLocked(db, account);
1074 if (accountId >= 0) {
1075 final String[] argsAccountId = {String.valueOf(accountId)};
1076 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1077 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001078 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001079 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001080 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001081 } finally {
1082 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001083 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001084 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001085 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001086 }
1087
Amith Yamasani04e0d262012-02-14 11:50:53 -08001088 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001089 Log.i(TAG, "the accounts changed, sending broadcast of "
1090 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001091 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001092 }
1093
Fred Quintanaa698f422009-04-08 19:14:54 -07001094 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001095 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1096 Log.v(TAG, "clearPassword: " + account
1097 + ", caller's uid " + Binder.getCallingUid()
1098 + ", pid " + Binder.getCallingPid());
1099 }
Fred Quintana382601f2010-03-25 12:25:10 -07001100 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001101 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001102 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001103 long identityToken = clearCallingIdentity();
1104 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001105 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001106 } finally {
1107 restoreCallingIdentity(identityToken);
1108 }
Fred Quintana60307342009-03-24 22:48:12 -07001109 }
1110
Fred Quintanaa698f422009-04-08 19:14:54 -07001111 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001112 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1113 Log.v(TAG, "setUserData: " + account
1114 + ", key " + key
1115 + ", caller's uid " + Binder.getCallingUid()
1116 + ", pid " + Binder.getCallingPid());
1117 }
Fred Quintana382601f2010-03-25 12:25:10 -07001118 if (key == null) throw new IllegalArgumentException("key is null");
1119 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001120 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001121 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001122 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001123 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001124 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001125 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001126 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001127 }
1128 }
1129
Amith Yamasani04e0d262012-02-14 11:50:53 -08001130 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1131 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001132 if (account == null || key == null) {
1133 return;
1134 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001135 synchronized (accounts.cacheLock) {
1136 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001137 db.beginTransaction();
1138 try {
1139 long accountId = getAccountIdLocked(db, account);
1140 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001141 return;
1142 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001143 long extrasId = getExtrasIdLocked(db, accountId, key);
1144 if (extrasId < 0 ) {
1145 extrasId = insertExtraLocked(db, accountId, key, value);
1146 if (extrasId < 0) {
1147 return;
1148 }
1149 } else {
1150 ContentValues values = new ContentValues();
1151 values.put(EXTRAS_VALUE, value);
1152 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1153 return;
1154 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001155
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001156 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001157 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001158 db.setTransactionSuccessful();
1159 } finally {
1160 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001161 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001162 }
1163 }
1164
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001165 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001166 if (result == null) {
1167 Log.e(TAG, "the result is unexpectedly null", new Exception());
1168 }
1169 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1170 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1171 + response);
1172 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001173 try {
1174 response.onResult(result);
1175 } catch (RemoteException e) {
1176 // if the caller is dead then there is no one to care about remote
1177 // exceptions
1178 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1179 Log.v(TAG, "failure while notifying response", e);
1180 }
1181 }
1182 }
1183
Fred Quintanad9640ec2012-05-23 12:37:00 -07001184 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1185 final String authTokenType)
1186 throws RemoteException {
1187 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001188 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1189
Fred Quintanad9640ec2012-05-23 12:37:00 -07001190 final int callingUid = getCallingUid();
1191 clearCallingIdentity();
1192 if (callingUid != android.os.Process.SYSTEM_UID) {
1193 throw new SecurityException("can only call from system");
1194 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001195 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001196 long identityToken = clearCallingIdentity();
1197 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001198 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001199 false /* stripAuthTokenFromResult */) {
1200 protected String toDebugString(long now) {
1201 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001202 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001203 + ", authTokenType " + authTokenType;
1204 }
1205
1206 public void run() throws RemoteException {
1207 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1208 }
1209
1210 public void onResult(Bundle result) {
1211 if (result != null) {
1212 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1213 Bundle bundle = new Bundle();
1214 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1215 super.onResult(bundle);
1216 return;
1217 } else {
1218 super.onResult(result);
1219 }
1220 }
1221 }.bind();
1222 } finally {
1223 restoreCallingIdentity(identityToken);
1224 }
1225 }
1226
Fred Quintanaa698f422009-04-08 19:14:54 -07001227 public void getAuthToken(IAccountManagerResponse response, final Account account,
1228 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001229 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001230 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1231 Log.v(TAG, "getAuthToken: " + account
1232 + ", response " + response
1233 + ", authTokenType " + authTokenType
1234 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1235 + ", expectActivityLaunch " + expectActivityLaunch
1236 + ", caller's uid " + Binder.getCallingUid()
1237 + ", pid " + Binder.getCallingPid());
1238 }
Fred Quintana382601f2010-03-25 12:25:10 -07001239 if (response == null) throw new IllegalArgumentException("response is null");
1240 if (account == null) throw new IllegalArgumentException("account is null");
1241 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001242 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001243 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001244 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1245 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1246 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001247 final boolean customTokens =
1248 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1249
1250 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001251 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001252 final boolean permissionGranted = customTokens ||
1253 permissionIsGranted(account, authTokenType, callerUid);
1254
Costin Manolachec6684f92011-01-14 11:25:39 -08001255 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1256 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001257 // let authenticator know the identity of the caller
1258 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1259 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1260 if (notifyOnAuthFailure) {
1261 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001262 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001263
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001264 long identityToken = clearCallingIdentity();
1265 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001266 // if the caller has permission, do the peek. otherwise go the more expensive
1267 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001268 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001269 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001270 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001271 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001272 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1273 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1274 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001275 onResult(response, result);
1276 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001277 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001278 }
1279
Amith Yamasani04e0d262012-02-14 11:50:53 -08001280 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001281 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001282 protected String toDebugString(long now) {
1283 if (loginOptions != null) loginOptions.keySet();
1284 return super.toDebugString(now) + ", getAuthToken"
1285 + ", " + account
1286 + ", authTokenType " + authTokenType
1287 + ", loginOptions " + loginOptions
1288 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1289 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001290
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001291 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001292 // If the caller doesn't have permission then create and return the
1293 // "grant permission" intent instead of the "getAuthToken" intent.
1294 if (!permissionGranted) {
1295 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1296 } else {
1297 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1298 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001299 }
1300
1301 public void onResult(Bundle result) {
1302 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001303 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001304 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1305 new AccountAuthenticatorResponse(this),
1306 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001307 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001308 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001309 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001310 onResult(bundle);
1311 return;
1312 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001313 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001314 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001315 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1316 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001317 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001318 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001319 "the type and name should not be empty");
1320 return;
1321 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001322 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001323 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001324 authTokenType, authToken);
1325 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001326 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001327
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001328 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001329 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001330 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001331 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001332 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001333 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001334 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001335 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001336 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001337 }.bind();
1338 } finally {
1339 restoreCallingIdentity(identityToken);
1340 }
Fred Quintana60307342009-03-24 22:48:12 -07001341 }
1342
Dianne Hackborn41203752012-08-31 14:05:51 -07001343 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1344 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001345 int uid = intent.getIntExtra(
1346 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1347 String authTokenType = intent.getStringExtra(
1348 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1349 String authTokenLabel = intent.getStringExtra(
1350 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1351
1352 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1353 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001354 final String titleAndSubtitle =
1355 mContext.getString(R.string.permission_request_notification_with_subtitle,
1356 account.name);
1357 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001358 String title = titleAndSubtitle;
1359 String subtitle = "";
1360 if (index > 0) {
1361 title = titleAndSubtitle.substring(0, index);
1362 subtitle = titleAndSubtitle.substring(index + 1);
1363 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001364 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001365 n.setLatestEventInfo(mContext, title, subtitle,
1366 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001367 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1368 installNotification(getCredentialPermissionNotificationId(
1369 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001370 }
1371
Costin Manolache5f383ad92010-12-02 16:44:46 -08001372 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1373 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001374
1375 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001376 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001377 // Since it was set in Eclair+ we can't change it without breaking apps using
1378 // the intent from a non-Activity context.
1379 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001380 intent.addCategory(
1381 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001382
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001383 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001384 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1385 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001386 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001387
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001388 return intent;
1389 }
1390
1391 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1392 int uid) {
1393 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001394 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001395 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001396 final Pair<Pair<Account, String>, Integer> key =
1397 new Pair<Pair<Account, String>, Integer>(
1398 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001399 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001400 if (id == null) {
1401 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001402 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001403 }
1404 }
1405 return id;
1406 }
1407
Amith Yamasani04e0d262012-02-14 11:50:53 -08001408 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001409 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001410 synchronized (accounts.signinRequiredNotificationIds) {
1411 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001412 if (id == null) {
1413 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001414 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001415 }
1416 }
1417 return id;
1418 }
1419
Fred Quintana33269202009-04-20 16:05:10 -07001420 public void addAcount(final IAccountManagerResponse response, final String accountType,
1421 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001422 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001423 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1424 Log.v(TAG, "addAccount: accountType " + accountType
1425 + ", response " + response
1426 + ", authTokenType " + authTokenType
1427 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1428 + ", expectActivityLaunch " + expectActivityLaunch
1429 + ", caller's uid " + Binder.getCallingUid()
1430 + ", pid " + Binder.getCallingPid());
1431 }
Fred Quintana382601f2010-03-25 12:25:10 -07001432 if (response == null) throw new IllegalArgumentException("response is null");
1433 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001434 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001435
Amith Yamasani04e0d262012-02-14 11:50:53 -08001436 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001437 final int pid = Binder.getCallingPid();
1438 final int uid = Binder.getCallingUid();
1439 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1440 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1441 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1442
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001443 long identityToken = clearCallingIdentity();
1444 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001445 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001446 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001447 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001448 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001449 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001450 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001451
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001452 protected String toDebugString(long now) {
1453 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001454 + ", accountType " + accountType
1455 + ", requiredFeatures "
1456 + (requiredFeatures != null
1457 ? TextUtils.join(",", requiredFeatures)
1458 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001459 }
1460 }.bind();
1461 } finally {
1462 restoreCallingIdentity(identityToken);
1463 }
Fred Quintana60307342009-03-24 22:48:12 -07001464 }
1465
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001466 @Override
1467 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1468 final Account account, final Bundle options, final boolean expectActivityLaunch,
1469 int userId) {
1470 // Only allow the system process to read accounts of other users
1471 if (userId != UserHandle.getCallingUserId()
1472 && Binder.getCallingUid() != android.os.Process.myUid()) {
1473 throw new SecurityException("User " + UserHandle.getCallingUserId()
1474 + " trying to confirm account credentials for " + userId);
1475 }
1476
Fred Quintana56285a62010-12-02 14:20:51 -08001477 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1478 Log.v(TAG, "confirmCredentials: " + account
1479 + ", response " + response
1480 + ", expectActivityLaunch " + expectActivityLaunch
1481 + ", caller's uid " + Binder.getCallingUid()
1482 + ", pid " + Binder.getCallingPid());
1483 }
Fred Quintana382601f2010-03-25 12:25:10 -07001484 if (response == null) throw new IllegalArgumentException("response is null");
1485 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001486 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001487 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001488 long identityToken = clearCallingIdentity();
1489 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001490 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001491 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001492 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001493 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001494 }
1495 protected String toDebugString(long now) {
1496 return super.toDebugString(now) + ", confirmCredentials"
1497 + ", " + account;
1498 }
1499 }.bind();
1500 } finally {
1501 restoreCallingIdentity(identityToken);
1502 }
Fred Quintana60307342009-03-24 22:48:12 -07001503 }
1504
Fred Quintanaa698f422009-04-08 19:14:54 -07001505 public void updateCredentials(IAccountManagerResponse response, final Account account,
1506 final String authTokenType, final boolean expectActivityLaunch,
1507 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001508 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1509 Log.v(TAG, "updateCredentials: " + account
1510 + ", response " + response
1511 + ", authTokenType " + authTokenType
1512 + ", expectActivityLaunch " + expectActivityLaunch
1513 + ", caller's uid " + Binder.getCallingUid()
1514 + ", pid " + Binder.getCallingPid());
1515 }
Fred Quintana382601f2010-03-25 12:25:10 -07001516 if (response == null) throw new IllegalArgumentException("response is null");
1517 if (account == null) throw new IllegalArgumentException("account is null");
1518 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001519 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001520 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001521 long identityToken = clearCallingIdentity();
1522 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001523 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001524 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001525 public void run() throws RemoteException {
1526 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1527 }
1528 protected String toDebugString(long now) {
1529 if (loginOptions != null) loginOptions.keySet();
1530 return super.toDebugString(now) + ", updateCredentials"
1531 + ", " + account
1532 + ", authTokenType " + authTokenType
1533 + ", loginOptions " + loginOptions;
1534 }
1535 }.bind();
1536 } finally {
1537 restoreCallingIdentity(identityToken);
1538 }
Fred Quintana60307342009-03-24 22:48:12 -07001539 }
1540
Fred Quintanaa698f422009-04-08 19:14:54 -07001541 public void editProperties(IAccountManagerResponse response, final String accountType,
1542 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001543 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1544 Log.v(TAG, "editProperties: accountType " + accountType
1545 + ", response " + response
1546 + ", expectActivityLaunch " + expectActivityLaunch
1547 + ", caller's uid " + Binder.getCallingUid()
1548 + ", pid " + Binder.getCallingPid());
1549 }
Fred Quintana382601f2010-03-25 12:25:10 -07001550 if (response == null) throw new IllegalArgumentException("response is null");
1551 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001552 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001553 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001554 long identityToken = clearCallingIdentity();
1555 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001556 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001557 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001558 public void run() throws RemoteException {
1559 mAuthenticator.editProperties(this, mAccountType);
1560 }
1561 protected String toDebugString(long now) {
1562 return super.toDebugString(now) + ", editProperties"
1563 + ", accountType " + accountType;
1564 }
1565 }.bind();
1566 } finally {
1567 restoreCallingIdentity(identityToken);
1568 }
Fred Quintana60307342009-03-24 22:48:12 -07001569 }
1570
Fred Quintana33269202009-04-20 16:05:10 -07001571 private class GetAccountsByTypeAndFeatureSession extends Session {
1572 private final String[] mFeatures;
1573 private volatile Account[] mAccountsOfType = null;
1574 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1575 private volatile int mCurrentAccount = 0;
1576
Amith Yamasani04e0d262012-02-14 11:50:53 -08001577 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
1578 IAccountManagerResponse response, String type, String[] features) {
1579 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001580 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001581 mFeatures = features;
1582 }
1583
1584 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001585 synchronized (mAccounts.cacheLock) {
1586 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001587 }
Fred Quintana33269202009-04-20 16:05:10 -07001588 // check whether each account matches the requested features
1589 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1590 mCurrentAccount = 0;
1591
1592 checkAccount();
1593 }
1594
1595 public void checkAccount() {
1596 if (mCurrentAccount >= mAccountsOfType.length) {
1597 sendResult();
1598 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001599 }
Fred Quintana33269202009-04-20 16:05:10 -07001600
Fred Quintana29e94b82010-03-10 12:11:51 -08001601 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1602 if (accountAuthenticator == null) {
1603 // It is possible that the authenticator has died, which is indicated by
1604 // mAuthenticator being set to null. If this happens then just abort.
1605 // There is no need to send back a result or error in this case since
1606 // that already happened when mAuthenticator was cleared.
1607 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1608 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1609 + " connected to the authenticator, " + toDebugString());
1610 }
1611 return;
1612 }
Fred Quintana33269202009-04-20 16:05:10 -07001613 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001614 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001615 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001616 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001617 }
1618 }
1619
1620 public void onResult(Bundle result) {
1621 mNumResults++;
1622 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001623 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001624 return;
1625 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001626 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001627 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1628 }
1629 mCurrentAccount++;
1630 checkAccount();
1631 }
1632
1633 public void sendResult() {
1634 IAccountManagerResponse response = getResponseAndClose();
1635 if (response != null) {
1636 try {
1637 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1638 for (int i = 0; i < accounts.length; i++) {
1639 accounts[i] = mAccountsWithFeatures.get(i);
1640 }
Fred Quintana56285a62010-12-02 14:20:51 -08001641 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1642 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1643 + response);
1644 }
Fred Quintana33269202009-04-20 16:05:10 -07001645 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001646 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001647 response.onResult(result);
1648 } catch (RemoteException e) {
1649 // if the caller is dead then there is no one to care about remote exceptions
1650 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1651 Log.v(TAG, "failure while notifying response", e);
1652 }
1653 }
1654 }
1655 }
1656
1657
1658 protected String toDebugString(long now) {
1659 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1660 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1661 }
1662 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001663
Amith Yamasani04e0d262012-02-14 11:50:53 -08001664 /**
1665 * Returns the accounts for a specific user
1666 * @hide
1667 */
1668 public Account[] getAccounts(int userId) {
1669 checkReadAccountsPermission();
1670 UserAccounts accounts = getUserAccounts(userId);
1671 long identityToken = clearCallingIdentity();
1672 try {
1673 synchronized (accounts.cacheLock) {
1674 return getAccountsFromCacheLocked(accounts, null);
1675 }
1676 } finally {
1677 restoreCallingIdentity(identityToken);
1678 }
1679 }
1680
Amith Yamasanif29f2362012-04-05 18:29:52 -07001681 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001682 * Returns accounts for all running users.
1683 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001684 * @hide
1685 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001686 public AccountAndUser[] getRunningAccounts() {
1687 final int[] runningUserIds;
1688 try {
1689 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1690 } catch (RemoteException e) {
1691 // Running in system_server; should never happen
1692 throw new RuntimeException(e);
1693 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001694 return getAccounts(runningUserIds);
1695 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001696
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001697 /** {@hide} */
1698 public AccountAndUser[] getAllAccounts() {
1699 final List<UserInfo> users = getUserManager().getUsers();
1700 final int[] userIds = new int[users.size()];
1701 for (int i = 0; i < userIds.length; i++) {
1702 userIds[i] = users.get(i).id;
1703 }
1704 return getAccounts(userIds);
1705 }
1706
1707 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001708 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1709 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001710 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001711 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001712 if (userAccounts == null) continue;
1713 synchronized (userAccounts.cacheLock) {
1714 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null);
1715 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001716 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001717 }
1718 }
1719 }
1720 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001721
1722 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1723 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001724 }
1725
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001726 @Override
1727 public Account[] getAccountsAsUser(String type, int userId) {
1728 // Only allow the system process to read accounts of other users
1729 if (userId != UserHandle.getCallingUserId()
1730 && Binder.getCallingUid() != android.os.Process.myUid()) {
1731 throw new SecurityException("User " + UserHandle.getCallingUserId()
1732 + " trying to get account for " + userId);
1733 }
1734
Fred Quintana56285a62010-12-02 14:20:51 -08001735 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1736 Log.v(TAG, "getAccounts: accountType " + type
1737 + ", caller's uid " + Binder.getCallingUid()
1738 + ", pid " + Binder.getCallingPid());
1739 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001740 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001741 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001742 long identityToken = clearCallingIdentity();
1743 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001744 synchronized (accounts.cacheLock) {
1745 return getAccountsFromCacheLocked(accounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001746 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001747 } finally {
1748 restoreCallingIdentity(identityToken);
1749 }
1750 }
1751
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001752 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001753 public boolean addSharedAccountAsUser(Account account, int userId) {
1754 userId = handleIncomingUser(userId);
1755 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1756 ContentValues values = new ContentValues();
1757 values.put(ACCOUNTS_NAME, account.name);
1758 values.put(ACCOUNTS_TYPE, account.type);
1759 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1760 new String[] {account.name, account.type});
1761 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1762 if (accountId < 0) {
1763 Log.w(TAG, "insertAccountIntoDatabase: " + account
1764 + ", skipping the DB insert failed");
1765 return false;
1766 }
1767 return true;
1768 }
1769
1770 @Override
1771 public boolean removeSharedAccountAsUser(Account account, int userId) {
1772 userId = handleIncomingUser(userId);
1773 UserAccounts accounts = getUserAccounts(userId);
1774 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1775 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1776 new String[] {account.name, account.type});
1777 if (r > 0) {
1778 removeAccountInternal(accounts, account);
1779 }
1780 return r > 0;
1781 }
1782
1783 @Override
1784 public Account[] getSharedAccountsAsUser(int userId) {
1785 userId = handleIncomingUser(userId);
1786 UserAccounts accounts = getUserAccounts(userId);
1787 ArrayList<Account> accountList = new ArrayList<Account>();
1788 Cursor cursor = null;
1789 try {
1790 cursor = accounts.openHelper.getReadableDatabase()
1791 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1792 null, null, null, null, null);
1793 if (cursor != null && cursor.moveToFirst()) {
1794 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1795 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1796 do {
1797 accountList.add(new Account(cursor.getString(nameIndex),
1798 cursor.getString(typeIndex)));
1799 } while (cursor.moveToNext());
1800 }
1801 } finally {
1802 if (cursor != null) {
1803 cursor.close();
1804 }
1805 }
1806 Account[] accountArray = new Account[accountList.size()];
1807 accountList.toArray(accountArray);
1808 return accountArray;
1809 }
1810
1811 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001812 public Account[] getAccounts(String type) {
1813 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1814 }
1815
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001816 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001817 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001818 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1819 Log.v(TAG, "getAccounts: accountType " + type
1820 + ", response " + response
1821 + ", features " + stringArrayToString(features)
1822 + ", caller's uid " + Binder.getCallingUid()
1823 + ", pid " + Binder.getCallingPid());
1824 }
Fred Quintana382601f2010-03-25 12:25:10 -07001825 if (response == null) throw new IllegalArgumentException("response is null");
1826 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001827 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001828 UserAccounts userAccounts = getUserAccountsForCaller();
Fred Quintana33269202009-04-20 16:05:10 -07001829 long identityToken = clearCallingIdentity();
1830 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001831 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001832 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001833 synchronized (userAccounts.cacheLock) {
1834 accounts = getAccountsFromCacheLocked(userAccounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001835 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001836 Bundle result = new Bundle();
1837 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1838 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001839 return;
1840 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001841 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001842 } finally {
1843 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001844 }
1845 }
1846
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001847 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001848 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001849 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001850 try {
1851 if (cursor.moveToNext()) {
1852 return cursor.getLong(0);
1853 }
1854 return -1;
1855 } finally {
1856 cursor.close();
1857 }
1858 }
1859
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001860 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001861 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1862 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1863 new String[]{key}, null, null, null);
1864 try {
1865 if (cursor.moveToNext()) {
1866 return cursor.getLong(0);
1867 }
1868 return -1;
1869 } finally {
1870 cursor.close();
1871 }
1872 }
1873
Fred Quintanaa698f422009-04-08 19:14:54 -07001874 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001875 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001876 IAccountManagerResponse mResponse;
1877 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001878 final boolean mExpectActivityLaunch;
1879 final long mCreationTime;
1880
Fred Quintana33269202009-04-20 16:05:10 -07001881 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001882 private int mNumRequestContinued = 0;
1883 private int mNumErrors = 0;
1884
Fred Quintana60307342009-03-24 22:48:12 -07001885 IAccountAuthenticator mAuthenticator = null;
1886
Fred Quintana8570f742010-02-18 10:32:54 -08001887 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001888 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001889
Amith Yamasani04e0d262012-02-14 11:50:53 -08001890 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001891 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001892 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001893 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001894 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001895 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001896 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001897 mResponse = response;
1898 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001899 mExpectActivityLaunch = expectActivityLaunch;
1900 mCreationTime = SystemClock.elapsedRealtime();
1901 synchronized (mSessions) {
1902 mSessions.put(toString(), this);
1903 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001904 if (response != null) {
1905 try {
1906 response.asBinder().linkToDeath(this, 0 /* flags */);
1907 } catch (RemoteException e) {
1908 mResponse = null;
1909 binderDied();
1910 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001911 }
Fred Quintana60307342009-03-24 22:48:12 -07001912 }
1913
Fred Quintanaa698f422009-04-08 19:14:54 -07001914 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001915 if (mResponse == null) {
1916 // this session has already been closed
1917 return null;
1918 }
Fred Quintana60307342009-03-24 22:48:12 -07001919 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001920 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001921 return response;
1922 }
1923
Fred Quintanaa698f422009-04-08 19:14:54 -07001924 private void close() {
1925 synchronized (mSessions) {
1926 if (mSessions.remove(toString()) == null) {
1927 // the session was already closed, so bail out now
1928 return;
1929 }
1930 }
1931 if (mResponse != null) {
1932 // stop listening for response deaths
1933 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1934
1935 // clear this so that we don't accidentally send any further results
1936 mResponse = null;
1937 }
1938 cancelTimeout();
1939 unbind();
1940 }
1941
1942 public void binderDied() {
1943 mResponse = null;
1944 close();
1945 }
1946
1947 protected String toDebugString() {
1948 return toDebugString(SystemClock.elapsedRealtime());
1949 }
1950
1951 protected String toDebugString(long now) {
1952 return "Session: expectLaunch " + mExpectActivityLaunch
1953 + ", connected " + (mAuthenticator != null)
1954 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1955 + "/" + mNumErrors + ")"
1956 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1957 }
1958
Fred Quintana60307342009-03-24 22:48:12 -07001959 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001960 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1961 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1962 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001963 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001964 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001965 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001966 }
1967 }
1968
1969 private void unbind() {
1970 if (mAuthenticator != null) {
1971 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001972 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001973 }
1974 }
1975
1976 public void scheduleTimeout() {
1977 mMessageHandler.sendMessageDelayed(
1978 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1979 }
1980
1981 public void cancelTimeout() {
1982 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1983 }
1984
Fred Quintanab839afc2009-10-14 15:57:28 -07001985 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001986 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001987 try {
1988 run();
1989 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001990 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001991 "remote exception");
1992 }
Fred Quintana60307342009-03-24 22:48:12 -07001993 }
1994
Fred Quintanab839afc2009-10-14 15:57:28 -07001995 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001996 mAuthenticator = null;
1997 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001998 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001999 try {
2000 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2001 "disconnected");
2002 } catch (RemoteException e) {
2003 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2004 Log.v(TAG, "Session.onServiceDisconnected: "
2005 + "caught RemoteException while responding", e);
2006 }
2007 }
Fred Quintana60307342009-03-24 22:48:12 -07002008 }
2009 }
2010
Fred Quintanab839afc2009-10-14 15:57:28 -07002011 public abstract void run() throws RemoteException;
2012
Fred Quintana60307342009-03-24 22:48:12 -07002013 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002014 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002015 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002016 try {
2017 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2018 "timeout");
2019 } catch (RemoteException e) {
2020 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2021 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2022 e);
2023 }
2024 }
Fred Quintana60307342009-03-24 22:48:12 -07002025 }
2026 }
2027
Fred Quintanaa698f422009-04-08 19:14:54 -07002028 public void onResult(Bundle result) {
2029 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002030 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
2031 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2032 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002033 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2034 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002035 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2036 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002037 }
Fred Quintana60307342009-03-24 22:48:12 -07002038 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002039 IAccountManagerResponse response;
2040 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002041 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002042 response = mResponse;
2043 } else {
2044 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002045 }
Fred Quintana60307342009-03-24 22:48:12 -07002046 if (response != null) {
2047 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002048 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002049 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2050 Log.v(TAG, getClass().getSimpleName()
2051 + " calling onError() on response " + response);
2052 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002053 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002054 "null bundle returned");
2055 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002056 if (mStripAuthTokenFromResult) {
2057 result.remove(AccountManager.KEY_AUTHTOKEN);
2058 }
Fred Quintana56285a62010-12-02 14:20:51 -08002059 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2060 Log.v(TAG, getClass().getSimpleName()
2061 + " calling onResult() on response " + response);
2062 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002063 response.onResult(result);
2064 }
Fred Quintana60307342009-03-24 22:48:12 -07002065 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002066 // if the caller is dead then there is no one to care about remote exceptions
2067 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2068 Log.v(TAG, "failure while notifying response", e);
2069 }
Fred Quintana60307342009-03-24 22:48:12 -07002070 }
2071 }
2072 }
Fred Quintana60307342009-03-24 22:48:12 -07002073
Fred Quintanaa698f422009-04-08 19:14:54 -07002074 public void onRequestContinued() {
2075 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002076 }
2077
2078 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002079 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002080 IAccountManagerResponse response = getResponseAndClose();
2081 if (response != null) {
2082 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002083 Log.v(TAG, getClass().getSimpleName()
2084 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002085 }
2086 try {
2087 response.onError(errorCode, errorMessage);
2088 } catch (RemoteException e) {
2089 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2090 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2091 }
2092 }
2093 } else {
2094 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2095 Log.v(TAG, "Session.onError: already closed");
2096 }
Fred Quintana60307342009-03-24 22:48:12 -07002097 }
2098 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002099
2100 /**
2101 * find the component name for the authenticator and initiate a bind
2102 * if no authenticator or the bind fails then return false, otherwise return true
2103 */
2104 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002105 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2106 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2107 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002108 if (authenticatorInfo == null) {
2109 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2110 Log.v(TAG, "there is no authenticator for " + authenticatorType
2111 + ", bailing out");
2112 }
2113 return false;
2114 }
2115
2116 Intent intent = new Intent();
2117 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2118 intent.setComponent(authenticatorInfo.componentName);
2119 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2120 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2121 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002122 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2123 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002124 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2125 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2126 }
2127 return false;
2128 }
2129
2130
2131 return true;
2132 }
Fred Quintana60307342009-03-24 22:48:12 -07002133 }
2134
2135 private class MessageHandler extends Handler {
2136 MessageHandler(Looper looper) {
2137 super(looper);
2138 }
Costin Manolache3348f142009-09-29 18:58:36 -07002139
Fred Quintana60307342009-03-24 22:48:12 -07002140 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002141 switch (msg.what) {
2142 case MESSAGE_TIMED_OUT:
2143 Session session = (Session)msg.obj;
2144 session.onTimedOut();
2145 break;
2146
2147 default:
2148 throw new IllegalStateException("unhandled message: " + msg.what);
2149 }
2150 }
2151 }
2152
Amith Yamasani04e0d262012-02-14 11:50:53 -08002153 private static String getDatabaseName(int userId) {
2154 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002155 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002156 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002157 // Migrate old file, if it exists, to the new location.
2158 // Make sure the new file doesn't already exist. A dummy file could have been
2159 // accidentally created in the old location, causing the new one to become corrupted
2160 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002161 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002162 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002163 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002164 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002165 if (!userDir.exists()) {
2166 if (!userDir.mkdirs()) {
2167 throw new IllegalStateException("User dir cannot be created: " + userDir);
2168 }
2169 }
2170 if (!oldFile.renameTo(databaseFile)) {
2171 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2172 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002173 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002174 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002175 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002176 }
2177
Amith Yamasani04e0d262012-02-14 11:50:53 -08002178 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002179
Amith Yamasani04e0d262012-02-14 11:50:53 -08002180 public DatabaseHelper(Context context, int userId) {
2181 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002182 }
2183
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002184 /**
2185 * This call needs to be made while the mCacheLock is held. The way to
2186 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2187 * @param db The database.
2188 */
Fred Quintana60307342009-03-24 22:48:12 -07002189 @Override
2190 public void onCreate(SQLiteDatabase db) {
2191 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2192 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2193 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2194 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2195 + ACCOUNTS_PASSWORD + " TEXT, "
2196 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2197
2198 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2199 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2200 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2201 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2202 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2203 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2204
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002205 createGrantsTable(db);
2206
Fred Quintana60307342009-03-24 22:48:12 -07002207 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2208 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2209 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2210 + EXTRAS_KEY + " TEXT NOT NULL, "
2211 + EXTRAS_VALUE + " TEXT, "
2212 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2213
2214 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2215 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2216 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002217
Amith Yamasani67df64b2012-12-14 12:09:36 -08002218 createSharedAccountsTable(db);
2219
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002220 createAccountsDeletionTrigger(db);
2221 }
2222
Amith Yamasani67df64b2012-12-14 12:09:36 -08002223 private void createSharedAccountsTable(SQLiteDatabase db) {
2224 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2225 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2226 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2227 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2228 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2229 }
2230
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002231 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002232 db.execSQL(""
2233 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2234 + " BEGIN"
2235 + " DELETE FROM " + TABLE_AUTHTOKENS
2236 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2237 + " DELETE FROM " + TABLE_EXTRAS
2238 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002239 + " DELETE FROM " + TABLE_GRANTS
2240 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002241 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002242 }
2243
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002244 private void createGrantsTable(SQLiteDatabase db) {
2245 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2246 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2247 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2248 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2249 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2250 + "," + GRANTS_GRANTEE_UID + "))");
2251 }
2252
Fred Quintana60307342009-03-24 22:48:12 -07002253 @Override
2254 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002255 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002256
Fred Quintanaa698f422009-04-08 19:14:54 -07002257 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002258 // no longer need to do anything since the work is done
2259 // when upgrading from version 2
2260 oldVersion++;
2261 }
2262
2263 if (oldVersion == 2) {
2264 createGrantsTable(db);
2265 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2266 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002267 oldVersion++;
2268 }
Costin Manolache3348f142009-09-29 18:58:36 -07002269
2270 if (oldVersion == 3) {
2271 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2272 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2273 oldVersion++;
2274 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002275
2276 if (oldVersion == 4) {
2277 createSharedAccountsTable(db);
2278 oldVersion++;
2279 }
2280
2281 if (oldVersion != newVersion) {
2282 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2283 }
Fred Quintana60307342009-03-24 22:48:12 -07002284 }
2285
2286 @Override
2287 public void onOpen(SQLiteDatabase db) {
2288 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2289 }
2290 }
2291
Fred Quintana60307342009-03-24 22:48:12 -07002292 public IBinder onBind(Intent intent) {
2293 return asBinder();
2294 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002295
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002296 /**
2297 * Searches array of arguments for the specified string
2298 * @param args array of argument strings
2299 * @param value value to search for
2300 * @return true if the value is contained in the array
2301 */
2302 private static boolean scanArgs(String[] args, String value) {
2303 if (args != null) {
2304 for (String arg : args) {
2305 if (value.equals(arg)) {
2306 return true;
2307 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002308 }
2309 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002310 return false;
2311 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002312
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002313 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002314 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002315 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2316 != PackageManager.PERMISSION_GRANTED) {
2317 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2318 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2319 + " without permission " + android.Manifest.permission.DUMP);
2320 return;
2321 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002322 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002323 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002324
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002325 final List<UserInfo> users = getUserManager().getUsers();
2326 for (UserInfo user : users) {
2327 ipw.println("User " + user + ":");
2328 ipw.increaseIndent();
2329 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2330 ipw.println();
2331 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002332 }
2333 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002334
Amith Yamasani04e0d262012-02-14 11:50:53 -08002335 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2336 String[] args, boolean isCheckinRequest) {
2337 synchronized (userAccounts.cacheLock) {
2338 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002339
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002340 if (isCheckinRequest) {
2341 // This is a checkin request. *Only* upload the account types and the count of each.
2342 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2343 null, null, ACCOUNTS_TYPE, null, null);
2344 try {
2345 while (cursor.moveToNext()) {
2346 // print type,count
2347 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2348 }
2349 } finally {
2350 if (cursor != null) {
2351 cursor.close();
2352 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002353 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002354 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002355 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002356 fout.println("Accounts: " + accounts.length);
2357 for (Account account : accounts) {
2358 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002359 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002360
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002361 fout.println();
2362 synchronized (mSessions) {
2363 final long now = SystemClock.elapsedRealtime();
2364 fout.println("Active Sessions: " + mSessions.size());
2365 for (Session session : mSessions.values()) {
2366 fout.println(" " + session.toDebugString(now));
2367 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002368 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002369
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002370 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002371 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002372 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002373 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002374 }
2375
Amith Yamasani04e0d262012-02-14 11:50:53 -08002376 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002377 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002378 long identityToken = clearCallingIdentity();
2379 try {
2380 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2381 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2382 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002383
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002384 if (intent.getComponent() != null &&
2385 GrantCredentialsPermissionActivity.class.getName().equals(
2386 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002387 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002388 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002389 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002390 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002391 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2392 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002393 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002394 final String notificationTitleFormat =
2395 mContext.getText(R.string.notification_title).toString();
2396 n.setLatestEventInfo(mContext,
2397 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002398 message, PendingIntent.getActivityAsUser(
2399 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002400 null, user));
2401 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002402 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002403 } finally {
2404 restoreCallingIdentity(identityToken);
2405 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002406 }
2407
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002408 protected void installNotification(final int notificationId, final Notification n,
2409 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002410 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002411 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002412 }
2413
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002414 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002415 long identityToken = clearCallingIdentity();
2416 try {
2417 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002418 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002419 } finally {
2420 restoreCallingIdentity(identityToken);
2421 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002422 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002423
Fred Quintanab38eb142010-02-24 13:40:54 -08002424 /** Succeeds if any of the specified permissions are granted. */
2425 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002426 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002427
2428 for (String perm : permissions) {
2429 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2430 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002431 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002432 }
2433 return;
2434 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002435 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002436
2437 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002438 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002439 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002440 }
2441
Amith Yamasani67df64b2012-12-14 12:09:36 -08002442 private int handleIncomingUser(int userId) {
2443 try {
2444 return ActivityManagerNative.getDefault().handleIncomingUser(
2445 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2446 } catch (RemoteException re) {
2447 // Shouldn't happen, local.
2448 }
2449 return userId;
2450 }
2451
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002452 private boolean inSystemImage(int callingUid) {
2453 final int callingUserId = UserHandle.getUserId(callingUid);
2454
2455 final PackageManager userPackageManager;
2456 try {
2457 userPackageManager = mContext.createPackageContextAsUser(
2458 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2459 } catch (NameNotFoundException e) {
2460 return false;
2461 }
2462
2463 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002464 for (String name : packages) {
2465 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002466 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002467 if (packageInfo != null
2468 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002469 return true;
2470 }
2471 } catch (PackageManager.NameNotFoundException e) {
2472 return false;
2473 }
2474 }
2475 return false;
2476 }
2477
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002478 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002479 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002480 final boolean fromAuthenticator = account != null
2481 && hasAuthenticatorUid(account.type, callerUid);
2482 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002483 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002484 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2485 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002486 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002487 + ": is authenticator? " + fromAuthenticator
2488 + ", has explicit permission? " + hasExplicitGrants);
2489 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002490 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002491 }
2492
Fred Quintana1a231912009-10-15 11:31:30 -07002493 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002494 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002495 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002496 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002497 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002498 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002499 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002500 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002501 }
2502 }
2503 return false;
2504 }
2505
Amith Yamasani04e0d262012-02-14 11:50:53 -08002506 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2507 int callerUid) {
2508 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002509 return true;
2510 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002511 UserAccounts accounts = getUserAccountsForCaller();
2512 synchronized (accounts.cacheLock) {
2513 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2514 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002515 account.name, account.type};
2516 final boolean permissionGranted =
2517 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2518 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2519 // TODO: Skip this check when running automated tests. Replace this
2520 // with a more general solution.
2521 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002522 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002523 + " but ignoring since device is in test harness.");
2524 return true;
2525 }
2526 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002527 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002528 }
2529
2530 private void checkCallingUidAgainstAuthenticator(Account account) {
2531 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002532 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002533 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2534 Log.w(TAG, msg);
2535 throw new SecurityException(msg);
2536 }
2537 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2538 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2539 }
2540 }
2541
2542 private void checkAuthenticateAccountsPermission(Account account) {
2543 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2544 checkCallingUidAgainstAuthenticator(account);
2545 }
2546
2547 private void checkReadAccountsPermission() {
2548 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2549 }
2550
2551 private void checkManageAccountsPermission() {
2552 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2553 }
2554
Fred Quintanab38eb142010-02-24 13:40:54 -08002555 private void checkManageAccountsOrUseCredentialsPermissions() {
2556 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2557 Manifest.permission.USE_CREDENTIALS);
2558 }
2559
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002560 private boolean canUserModifyAccounts(int callingUid) {
2561 if (callingUid != android.os.Process.myUid()) {
2562 Bundle restrictions = getUserManager().getUserRestrictions(
2563 new UserHandle(UserHandle.getUserId(callingUid)));
2564 if (!restrictions.getBoolean(UserManager.ALLOW_MODIFY_ACCOUNTS)) {
2565 return false;
2566 }
2567 }
2568 return true;
2569 }
2570
Fred Quintanad9640ec2012-05-23 12:37:00 -07002571 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2572 throws RemoteException {
2573 final int callingUid = getCallingUid();
2574
2575 if (callingUid != android.os.Process.SYSTEM_UID) {
2576 throw new SecurityException();
2577 }
2578
2579 if (value) {
2580 grantAppPermission(account, authTokenType, uid);
2581 } else {
2582 revokeAppPermission(account, authTokenType, uid);
2583 }
2584 }
2585
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002586 /**
2587 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2588 * <p>
2589 * Although this is public it can only be accessed via the AccountManagerService object
2590 * which is in the system. This means we don't need to protect it with permissions.
2591 * @hide
2592 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002593 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002594 if (account == null || authTokenType == null) {
2595 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002596 return;
2597 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002598 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002599 synchronized (accounts.cacheLock) {
2600 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002601 db.beginTransaction();
2602 try {
2603 long accountId = getAccountIdLocked(db, account);
2604 if (accountId >= 0) {
2605 ContentValues values = new ContentValues();
2606 values.put(GRANTS_ACCOUNTS_ID, accountId);
2607 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2608 values.put(GRANTS_GRANTEE_UID, uid);
2609 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2610 db.setTransactionSuccessful();
2611 }
2612 } finally {
2613 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002614 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002615 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2616 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002617 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002618 }
2619
2620 /**
2621 * Don't allow callers with the given uid permission to get credentials for
2622 * account/authTokenType.
2623 * <p>
2624 * Although this is public it can only be accessed via the AccountManagerService object
2625 * which is in the system. This means we don't need to protect it with permissions.
2626 * @hide
2627 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002628 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002629 if (account == null || authTokenType == null) {
2630 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002631 return;
2632 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002633 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002634 synchronized (accounts.cacheLock) {
2635 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002636 db.beginTransaction();
2637 try {
2638 long accountId = getAccountIdLocked(db, account);
2639 if (accountId >= 0) {
2640 db.delete(TABLE_GRANTS,
2641 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2642 + GRANTS_GRANTEE_UID + "=?",
2643 new String[]{String.valueOf(accountId), authTokenType,
2644 String.valueOf(uid)});
2645 db.setTransactionSuccessful();
2646 }
2647 } finally {
2648 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002649 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002650 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2651 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002652 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002653 }
Fred Quintana56285a62010-12-02 14:20:51 -08002654
2655 static final private String stringArrayToString(String[] value) {
2656 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2657 }
2658
Amith Yamasani04e0d262012-02-14 11:50:53 -08002659 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2660 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002661 if (oldAccountsForType != null) {
2662 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2663 for (Account curAccount : oldAccountsForType) {
2664 if (!curAccount.equals(account)) {
2665 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002666 }
2667 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002668 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002669 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002670 } else {
2671 Account[] newAccountsForType = new Account[newAccountsList.size()];
2672 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002673 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002674 }
Fred Quintana56285a62010-12-02 14:20:51 -08002675 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002676 accounts.userDataCache.remove(account);
2677 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002678 }
2679
2680 /**
2681 * This assumes that the caller has already checked that the account is not already present.
2682 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002683 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2684 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002685 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2686 Account[] newAccountsForType = new Account[oldLength + 1];
2687 if (accountsForType != null) {
2688 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002689 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002690 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002691 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002692 }
2693
Amith Yamasani04e0d262012-02-14 11:50:53 -08002694 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002695 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002696 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002697 if (accounts == null) {
2698 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002699 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002700 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002701 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002702 } else {
2703 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002704 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002705 totalLength += accounts.length;
2706 }
2707 if (totalLength == 0) {
2708 return EMPTY_ACCOUNT_ARRAY;
2709 }
2710 Account[] accounts = new Account[totalLength];
2711 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002712 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002713 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2714 accountsOfType.length);
2715 totalLength += accountsOfType.length;
2716 }
2717 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002718 }
2719 }
2720
Amith Yamasani04e0d262012-02-14 11:50:53 -08002721 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2722 Account account, String key, String value) {
2723 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002724 if (userDataForAccount == null) {
2725 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002726 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002727 }
2728 if (value == null) {
2729 userDataForAccount.remove(key);
2730 } else {
2731 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002732 }
2733 }
2734
Amith Yamasani04e0d262012-02-14 11:50:53 -08002735 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2736 Account account, String key, String value) {
2737 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002738 if (authTokensForAccount == null) {
2739 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002740 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002741 }
2742 if (value == null) {
2743 authTokensForAccount.remove(key);
2744 } else {
2745 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002746 }
2747 }
2748
Amith Yamasani04e0d262012-02-14 11:50:53 -08002749 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2750 String authTokenType) {
2751 synchronized (accounts.cacheLock) {
2752 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002753 if (authTokensForAccount == null) {
2754 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002755 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002756 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002757 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002758 }
2759 return authTokensForAccount.get(authTokenType);
2760 }
2761 }
2762
Amith Yamasani04e0d262012-02-14 11:50:53 -08002763 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2764 synchronized (accounts.cacheLock) {
2765 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002766 if (userDataForAccount == null) {
2767 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002768 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002769 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002770 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002771 }
2772 return userDataForAccount.get(key);
2773 }
2774 }
2775
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002776 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2777 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002778 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002779 Cursor cursor = db.query(TABLE_EXTRAS,
2780 COLUMNS_EXTRAS_KEY_AND_VALUE,
2781 SELECTION_USERDATA_BY_ACCOUNT,
2782 new String[]{account.name, account.type},
2783 null, null, null);
2784 try {
2785 while (cursor.moveToNext()) {
2786 final String tmpkey = cursor.getString(0);
2787 final String value = cursor.getString(1);
2788 userDataForAccount.put(tmpkey, value);
2789 }
2790 } finally {
2791 cursor.close();
2792 }
2793 return userDataForAccount;
2794 }
2795
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002796 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2797 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002798 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002799 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2800 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2801 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2802 new String[]{account.name, account.type},
2803 null, null, null);
2804 try {
2805 while (cursor.moveToNext()) {
2806 final String type = cursor.getString(0);
2807 final String authToken = cursor.getString(1);
2808 authTokensForAccount.put(type, authToken);
2809 }
2810 } finally {
2811 cursor.close();
2812 }
2813 return authTokensForAccount;
2814 }
Fred Quintana60307342009-03-24 22:48:12 -07002815}