blob: 150df9edf7bec454210d8071ee3cef37118dc9ba [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 Yamasani04e0d262012-02-14 11:50:53 -080072import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070073import com.google.android.collect.Lists;
74import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070075
Oscar Montemayora8529f62009-11-18 10:14:20 -080076import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070077import java.io.FileDescriptor;
78import java.io.PrintWriter;
79import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080080import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070081import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070082import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070083import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080084import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070085import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080086import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070087import java.util.concurrent.atomic.AtomicInteger;
88import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070089
Fred Quintana60307342009-03-24 22:48:12 -070090/**
91 * A system service that provides account, password, and authtoken management for all
92 * accounts on the device. Some of these calls are implemented with the help of the corresponding
93 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
94 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070095 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -070096 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070097 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070098public class AccountManagerService
99 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800100 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700101 private static final String TAG = "AccountManagerService";
102
103 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
104 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -0700105 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700106
107 private final Context mContext;
108
Fred Quintana56285a62010-12-02 14:20:51 -0800109 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700110 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800111
Fred Quintana60307342009-03-24 22:48:12 -0700112 private HandlerThread mMessageThread;
113 private final MessageHandler mMessageHandler;
114
115 // Messages that can be sent on mHandler
116 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700117
Fred Quintana56285a62010-12-02 14:20:51 -0800118 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700119
120 private static final String TABLE_ACCOUNTS = "accounts";
121 private static final String ACCOUNTS_ID = "_id";
122 private static final String ACCOUNTS_NAME = "name";
123 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700124 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700125 private static final String ACCOUNTS_PASSWORD = "password";
126
127 private static final String TABLE_AUTHTOKENS = "authtokens";
128 private static final String AUTHTOKENS_ID = "_id";
129 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
130 private static final String AUTHTOKENS_TYPE = "type";
131 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
132
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700133 private static final String TABLE_GRANTS = "grants";
134 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
135 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
136 private static final String GRANTS_GRANTEE_UID = "uid";
137
Fred Quintana60307342009-03-24 22:48:12 -0700138 private static final String TABLE_EXTRAS = "extras";
139 private static final String EXTRAS_ID = "_id";
140 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
141 private static final String EXTRAS_KEY = "key";
142 private static final String EXTRAS_VALUE = "value";
143
144 private static final String TABLE_META = "meta";
145 private static final String META_KEY = "key";
146 private static final String META_VALUE = "value";
147
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700148 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
149 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700150 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700151
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700152 private static final String COUNT_OF_MATCHING_GRANTS = ""
153 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
154 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
155 + " AND " + GRANTS_GRANTEE_UID + "=?"
156 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
157 + " AND " + ACCOUNTS_NAME + "=?"
158 + " AND " + ACCOUNTS_TYPE + "=?";
159
Fred Quintana56285a62010-12-02 14:20:51 -0800160 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
161 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
162 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
163 AUTHTOKENS_AUTHTOKEN};
164
165 private static final String SELECTION_USERDATA_BY_ACCOUNT =
166 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
167 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
168
Fred Quintanaa698f422009-04-08 19:14:54 -0700169 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700170 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
171
Amith Yamasani04e0d262012-02-14 11:50:53 -0800172 static class UserAccounts {
173 private final int userId;
174 private final DatabaseHelper openHelper;
175 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
176 credentialsPermissionNotificationIds =
177 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
178 private final HashMap<Account, Integer> signinRequiredNotificationIds =
179 new HashMap<Account, Integer>();
180 private final Object cacheLock = new Object();
181 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700182 private final HashMap<String, Account[]> accountCache =
183 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800184 /** protected by the {@link #cacheLock} */
185 private HashMap<Account, HashMap<String, String>> userDataCache =
186 new HashMap<Account, HashMap<String, String>>();
187 /** protected by the {@link #cacheLock} */
188 private HashMap<Account, HashMap<String, String>> authTokenCache =
189 new HashMap<Account, HashMap<String, String>>();
190
191 UserAccounts(Context context, int userId) {
192 this.userId = userId;
193 synchronized (cacheLock) {
194 openHelper = new DatabaseHelper(context, userId);
195 }
196 }
197 }
198
199 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
200
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700201 private static AtomicReference<AccountManagerService> sThis =
202 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700203 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700204
205 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700206 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700207 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
208 }
209
Fred Quintana56285a62010-12-02 14:20:51 -0800210
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700211 /**
212 * This should only be called by system code. One should only call this after the service
213 * has started.
214 * @return a reference to the AccountManagerService instance
215 * @hide
216 */
217 public static AccountManagerService getSingleton() {
218 return sThis.get();
219 }
Fred Quintana60307342009-03-24 22:48:12 -0700220
Fred Quintana56285a62010-12-02 14:20:51 -0800221 public AccountManagerService(Context context) {
222 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700223 }
224
Fred Quintana56285a62010-12-02 14:20:51 -0800225 public AccountManagerService(Context context, PackageManager packageManager,
226 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700227 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800228 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700229
Fred Quintana60307342009-03-24 22:48:12 -0700230 mMessageThread = new HandlerThread("AccountManagerService");
231 mMessageThread.start();
232 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
233
Fred Quintana56285a62010-12-02 14:20:51 -0800234 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800235 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700236
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700237 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800238
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800239 IntentFilter intentFilter = new IntentFilter();
240 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
241 intentFilter.addDataScheme("package");
242 mContext.registerReceiver(new BroadcastReceiver() {
243 @Override
244 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800245 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800246 }
247 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800248
Amith Yamasani13593602012-03-22 16:16:17 -0700249 IntentFilter userFilter = new IntentFilter();
250 userFilter.addAction(Intent.ACTION_USER_REMOVED);
251 mContext.registerReceiver(new BroadcastReceiver() {
252 @Override
253 public void onReceive(Context context, Intent intent) {
254 onUserRemoved(intent);
255 }
256 }, userFilter);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800257 }
258
Kenny Root26ff6622012-07-30 12:58:03 -0700259 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700260 }
261
Amith Yamasani258848d2012-08-10 17:06:33 -0700262 private UserManager getUserManager() {
263 if (mUserManager == null) {
264 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
265 }
266 return mUserManager;
267 }
268
Amith Yamasani04e0d262012-02-14 11:50:53 -0800269 private UserAccounts initUser(int userId) {
270 synchronized (mUsers) {
271 UserAccounts accounts = mUsers.get(userId);
272 if (accounts == null) {
273 accounts = new UserAccounts(mContext, userId);
274 mUsers.append(userId, accounts);
275 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700276 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800277 }
278 return accounts;
279 }
280 }
281
282 private void purgeOldGrantsAll() {
283 synchronized (mUsers) {
284 for (int i = 0; i < mUsers.size(); i++) {
285 purgeOldGrants(mUsers.valueAt(i));
286 }
287 }
288 }
289
290 private void purgeOldGrants(UserAccounts accounts) {
291 synchronized (accounts.cacheLock) {
292 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800293 final Cursor cursor = db.query(TABLE_GRANTS,
294 new String[]{GRANTS_GRANTEE_UID},
295 null, null, GRANTS_GRANTEE_UID, null, null);
296 try {
297 while (cursor.moveToNext()) {
298 final int uid = cursor.getInt(0);
299 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
300 if (packageExists) {
301 continue;
302 }
303 Log.d(TAG, "deleting grants for UID " + uid
304 + " because its package is no longer installed");
305 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
306 new String[]{Integer.toString(uid)});
307 }
308 } finally {
309 cursor.close();
310 }
311 }
312 }
313
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700314 /**
315 * Validate internal set of accounts against installed authenticators for
316 * given user. Clears cached authenticators before validating.
317 */
318 public void validateAccounts(int userId) {
319 final UserAccounts accounts = getUserAccounts(userId);
320
321 // Invalidate user-specific cache to make sure we catch any
322 // removed authenticators.
323 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
324 }
325
326 /**
327 * Validate internal set of accounts against installed authenticators for
328 * given user. Clear cached authenticators before validating when requested.
329 */
330 private void validateAccountsInternal(
331 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
332 if (invalidateAuthenticatorCache) {
333 mAuthenticatorCache.invalidateCache(accounts.userId);
334 }
335
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700336 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
337 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
338 mAuthenticatorCache.getAllServices(accounts.userId)) {
339 knownAuth.add(service.type);
340 }
341
Amith Yamasani04e0d262012-02-14 11:50:53 -0800342 synchronized (accounts.cacheLock) {
343 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800344 boolean accountDeleted = false;
345 Cursor cursor = db.query(TABLE_ACCOUNTS,
346 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
347 null, null, null, null, null);
348 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800349 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800350 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700351 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800352 while (cursor.moveToNext()) {
353 final long accountId = cursor.getLong(0);
354 final String accountType = cursor.getString(1);
355 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700356
357 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700358 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800359 + accountType + " no longer has a registered authenticator");
360 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
361 accountDeleted = true;
362 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800363 accounts.userDataCache.remove(account);
364 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800365 } else {
366 ArrayList<String> accountNames = accountNamesByType.get(accountType);
367 if (accountNames == null) {
368 accountNames = new ArrayList<String>();
369 accountNamesByType.put(accountType, accountNames);
370 }
371 accountNames.add(accountName);
372 }
373 }
Andy McFadden2f362292012-01-20 14:43:38 -0800374 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800375 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800376 final String accountType = cur.getKey();
377 final ArrayList<String> accountNames = cur.getValue();
378 final Account[] accountsForType = new Account[accountNames.size()];
379 int i = 0;
380 for (String accountName : accountNames) {
381 accountsForType[i] = new Account(accountName, accountType);
382 ++i;
383 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800384 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800385 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800386 } finally {
387 cursor.close();
388 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800389 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800390 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800391 }
392 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700393 }
394
Amith Yamasani04e0d262012-02-14 11:50:53 -0800395 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700396 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800397 }
398
399 protected UserAccounts getUserAccounts(int userId) {
400 synchronized (mUsers) {
401 UserAccounts accounts = mUsers.get(userId);
402 if (accounts == null) {
403 accounts = initUser(userId);
404 mUsers.append(userId, accounts);
405 }
406 return accounts;
407 }
408 }
409
Amith Yamasani13593602012-03-22 16:16:17 -0700410 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700411 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700412 if (userId < 1) return;
413
414 UserAccounts accounts;
415 synchronized (mUsers) {
416 accounts = mUsers.get(userId);
417 mUsers.remove(userId);
418 }
419 if (accounts == null) {
420 File dbFile = new File(getDatabaseName(userId));
421 dbFile.delete();
422 return;
423 }
424
425 synchronized (accounts.cacheLock) {
426 accounts.openHelper.close();
427 File dbFile = new File(getDatabaseName(userId));
428 dbFile.delete();
429 }
430 }
431
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700432 @Override
433 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700434 Slog.d(TAG, "onServiceChanged() for userId " + userId);
435 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700436 }
437
Fred Quintanaa698f422009-04-08 19:14:54 -0700438 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800439 if (Log.isLoggable(TAG, Log.VERBOSE)) {
440 Log.v(TAG, "getPassword: " + account
441 + ", caller's uid " + Binder.getCallingUid()
442 + ", pid " + Binder.getCallingPid());
443 }
Fred Quintana382601f2010-03-25 12:25:10 -0700444 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700445 checkAuthenticateAccountsPermission(account);
446
Amith Yamasani04e0d262012-02-14 11:50:53 -0800447 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700448 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700449 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800450 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700451 } finally {
452 restoreCallingIdentity(identityToken);
453 }
454 }
455
Amith Yamasani04e0d262012-02-14 11:50:53 -0800456 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700457 if (account == null) {
458 return null;
459 }
460
Amith Yamasani04e0d262012-02-14 11:50:53 -0800461 synchronized (accounts.cacheLock) {
462 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800463 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
464 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
465 new String[]{account.name, account.type}, null, null, null);
466 try {
467 if (cursor.moveToNext()) {
468 return cursor.getString(0);
469 }
470 return null;
471 } finally {
472 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700473 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700474 }
475 }
476
477 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800478 if (Log.isLoggable(TAG, Log.VERBOSE)) {
479 Log.v(TAG, "getUserData: " + account
480 + ", key " + key
481 + ", caller's uid " + Binder.getCallingUid()
482 + ", pid " + Binder.getCallingPid());
483 }
Fred Quintana382601f2010-03-25 12:25:10 -0700484 if (account == null) throw new IllegalArgumentException("account is null");
485 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700486 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800487 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700488 long identityToken = clearCallingIdentity();
489 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800490 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700491 } finally {
492 restoreCallingIdentity(identityToken);
493 }
494 }
495
Fred Quintana97889762009-06-15 12:29:24 -0700496 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800497 if (Log.isLoggable(TAG, Log.VERBOSE)) {
498 Log.v(TAG, "getAuthenticatorTypes: "
499 + "caller's uid " + Binder.getCallingUid()
500 + ", pid " + Binder.getCallingPid());
501 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700502 final int userId = UserHandle.getCallingUserId();
503 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700504 try {
Fred Quintana97889762009-06-15 12:29:24 -0700505 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700506 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700507 AuthenticatorDescription[] types =
508 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700509 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700510 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700511 : authenticatorCollection) {
512 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700513 i++;
514 }
515 return types;
516 } finally {
517 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700518 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700519 }
520
Fred Quintanaa698f422009-04-08 19:14:54 -0700521 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800522 if (Log.isLoggable(TAG, Log.VERBOSE)) {
523 Log.v(TAG, "addAccount: " + account
524 + ", caller's uid " + Binder.getCallingUid()
525 + ", pid " + Binder.getCallingPid());
526 }
Fred Quintana382601f2010-03-25 12:25:10 -0700527 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700528 checkAuthenticateAccountsPermission(account);
529
Amith Yamasani04e0d262012-02-14 11:50:53 -0800530 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700531 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700532 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700533 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800534 return addAccountInternal(accounts, account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700535 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700536 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700537 }
538 }
539
Amith Yamasani04e0d262012-02-14 11:50:53 -0800540 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
541 Bundle extras) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700542 if (account == null) {
543 return false;
544 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800545 synchronized (accounts.cacheLock) {
546 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800547 db.beginTransaction();
548 try {
549 long numMatches = DatabaseUtils.longForQuery(db,
550 "select count(*) from " + TABLE_ACCOUNTS
551 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
552 new String[]{account.name, account.type});
553 if (numMatches > 0) {
554 Log.w(TAG, "insertAccountIntoDatabase: " + account
555 + ", skipping since the account already exists");
556 return false;
557 }
558 ContentValues values = new ContentValues();
559 values.put(ACCOUNTS_NAME, account.name);
560 values.put(ACCOUNTS_TYPE, account.type);
561 values.put(ACCOUNTS_PASSWORD, password);
562 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
563 if (accountId < 0) {
564 Log.w(TAG, "insertAccountIntoDatabase: " + account
565 + ", skipping the DB insert failed");
566 return false;
567 }
568 if (extras != null) {
569 for (String key : extras.keySet()) {
570 final String value = extras.getString(key);
571 if (insertExtraLocked(db, accountId, key, value) < 0) {
572 Log.w(TAG, "insertAccountIntoDatabase: " + account
573 + ", skipping since insertExtra failed for key " + key);
574 return false;
575 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700576 }
577 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800578 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800579 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800580 } finally {
581 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700582 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800583 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800584 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700585 }
586 }
587
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800588 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700589 ContentValues values = new ContentValues();
590 values.put(EXTRAS_KEY, key);
591 values.put(EXTRAS_ACCOUNTS_ID, accountId);
592 values.put(EXTRAS_VALUE, value);
593 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
594 }
595
Fred Quintana3084a6f2010-01-14 18:02:03 -0800596 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800597 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800598 if (Log.isLoggable(TAG, Log.VERBOSE)) {
599 Log.v(TAG, "hasFeatures: " + account
600 + ", response " + response
601 + ", features " + stringArrayToString(features)
602 + ", caller's uid " + Binder.getCallingUid()
603 + ", pid " + Binder.getCallingPid());
604 }
Fred Quintana382601f2010-03-25 12:25:10 -0700605 if (response == null) throw new IllegalArgumentException("response is null");
606 if (account == null) throw new IllegalArgumentException("account is null");
607 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800608 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800609 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800610 long identityToken = clearCallingIdentity();
611 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800612 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800613 } finally {
614 restoreCallingIdentity(identityToken);
615 }
616 }
617
618 private class TestFeaturesSession extends Session {
619 private final String[] mFeatures;
620 private final Account mAccount;
621
Amith Yamasani04e0d262012-02-14 11:50:53 -0800622 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800623 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800624 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800625 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800626 mFeatures = features;
627 mAccount = account;
628 }
629
630 public void run() throws RemoteException {
631 try {
632 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
633 } catch (RemoteException e) {
634 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
635 }
636 }
637
638 public void onResult(Bundle result) {
639 IAccountManagerResponse response = getResponseAndClose();
640 if (response != null) {
641 try {
642 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700643 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800644 return;
645 }
Fred Quintana56285a62010-12-02 14:20:51 -0800646 if (Log.isLoggable(TAG, Log.VERBOSE)) {
647 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
648 + response);
649 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800650 final Bundle newResult = new Bundle();
651 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
652 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
653 response.onResult(newResult);
654 } catch (RemoteException e) {
655 // if the caller is dead then there is no one to care about remote exceptions
656 if (Log.isLoggable(TAG, Log.VERBOSE)) {
657 Log.v(TAG, "failure while notifying response", e);
658 }
659 }
660 }
661 }
662
663 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800664 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800665 + ", " + mAccount
666 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
667 }
668 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800669
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700670 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800671 if (Log.isLoggable(TAG, Log.VERBOSE)) {
672 Log.v(TAG, "removeAccount: " + account
673 + ", response " + response
674 + ", caller's uid " + Binder.getCallingUid()
675 + ", pid " + Binder.getCallingPid());
676 }
Fred Quintana382601f2010-03-25 12:25:10 -0700677 if (response == null) throw new IllegalArgumentException("response is null");
678 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700679 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700680 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800681 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700682 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800683
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700684 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800685 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800686 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800687 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800688 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800689 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700690 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800691 }
692 }
693 }
694
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700695 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800696 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700697 } finally {
698 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700699 }
Fred Quintana60307342009-03-24 22:48:12 -0700700 }
701
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700702 private class RemoveAccountSession extends Session {
703 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800704 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
705 Account account) {
706 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800707 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700708 mAccount = account;
709 }
710
711 protected String toDebugString(long now) {
712 return super.toDebugString(now) + ", removeAccount"
713 + ", account " + mAccount;
714 }
715
716 public void run() throws RemoteException {
717 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
718 }
719
720 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700721 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
722 && !result.containsKey(AccountManager.KEY_INTENT)) {
723 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700724 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800725 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700726 }
727 IAccountManagerResponse response = getResponseAndClose();
728 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800729 if (Log.isLoggable(TAG, Log.VERBOSE)) {
730 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
731 + response);
732 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700733 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700734 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700735 try {
736 response.onResult(result2);
737 } catch (RemoteException e) {
738 // ignore
739 }
740 }
741 }
742 super.onResult(result);
743 }
744 }
745
Amith Yamasani04e0d262012-02-14 11:50:53 -0800746 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800747 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800748 removeAccountInternal(getUserAccountsForCaller(), account);
749 }
750
751 private void removeAccountInternal(UserAccounts accounts, Account account) {
752 synchronized (accounts.cacheLock) {
753 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800754 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
755 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800756 removeAccountFromCacheLocked(accounts, account);
757 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800758 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700759 }
760
Fred Quintanaa698f422009-04-08 19:14:54 -0700761 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800762 if (Log.isLoggable(TAG, Log.VERBOSE)) {
763 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
764 + ", caller's uid " + Binder.getCallingUid()
765 + ", pid " + Binder.getCallingPid());
766 }
Fred Quintana382601f2010-03-25 12:25:10 -0700767 if (accountType == null) throw new IllegalArgumentException("accountType is null");
768 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800769 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800770 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700771 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700772 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800773 synchronized (accounts.cacheLock) {
774 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800775 db.beginTransaction();
776 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800777 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800778 db.setTransactionSuccessful();
779 } finally {
780 db.endTransaction();
781 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700782 }
Fred Quintana60307342009-03-24 22:48:12 -0700783 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700784 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700785 }
786 }
787
Amith Yamasani04e0d262012-02-14 11:50:53 -0800788 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
789 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700790 if (authToken == null || accountType == null) {
791 return;
792 }
Fred Quintana33269202009-04-20 16:05:10 -0700793 Cursor cursor = db.rawQuery(
794 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
795 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
796 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
797 + " FROM " + TABLE_ACCOUNTS
798 + " JOIN " + TABLE_AUTHTOKENS
799 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
800 + " = " + AUTHTOKENS_ACCOUNTS_ID
801 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
802 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
803 new String[]{authToken, accountType});
804 try {
805 while (cursor.moveToNext()) {
806 long authTokenId = cursor.getLong(0);
807 String accountName = cursor.getString(1);
808 String authTokenType = cursor.getString(2);
809 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800810 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800811 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700812 }
Fred Quintana33269202009-04-20 16:05:10 -0700813 } finally {
814 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700815 }
816 }
817
Amith Yamasani04e0d262012-02-14 11:50:53 -0800818 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
819 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700820 if (account == null || type == null) {
821 return false;
822 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700823 cancelNotification(getSigninRequiredNotificationId(accounts, account),
824 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800825 synchronized (accounts.cacheLock) {
826 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800827 db.beginTransaction();
828 try {
829 long accountId = getAccountIdLocked(db, account);
830 if (accountId < 0) {
831 return false;
832 }
833 db.delete(TABLE_AUTHTOKENS,
834 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
835 new String[]{type});
836 ContentValues values = new ContentValues();
837 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
838 values.put(AUTHTOKENS_TYPE, type);
839 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
840 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
841 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800842 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800843 return true;
844 }
Fred Quintana33269202009-04-20 16:05:10 -0700845 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800846 } finally {
847 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -0700848 }
Fred Quintana60307342009-03-24 22:48:12 -0700849 }
850 }
851
Fred Quintanaa698f422009-04-08 19:14:54 -0700852 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800853 if (Log.isLoggable(TAG, Log.VERBOSE)) {
854 Log.v(TAG, "peekAuthToken: " + account
855 + ", authTokenType " + authTokenType
856 + ", caller's uid " + Binder.getCallingUid()
857 + ", pid " + Binder.getCallingPid());
858 }
Fred Quintana382601f2010-03-25 12:25:10 -0700859 if (account == null) throw new IllegalArgumentException("account is null");
860 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700861 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800862 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700863 long identityToken = clearCallingIdentity();
864 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800865 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700866 } finally {
867 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700868 }
Fred Quintana60307342009-03-24 22:48:12 -0700869 }
870
Fred Quintanaa698f422009-04-08 19:14:54 -0700871 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800872 if (Log.isLoggable(TAG, Log.VERBOSE)) {
873 Log.v(TAG, "setAuthToken: " + account
874 + ", authTokenType " + authTokenType
875 + ", caller's uid " + Binder.getCallingUid()
876 + ", pid " + Binder.getCallingPid());
877 }
Fred Quintana382601f2010-03-25 12:25:10 -0700878 if (account == null) throw new IllegalArgumentException("account is null");
879 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700880 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800881 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700882 long identityToken = clearCallingIdentity();
883 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800884 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700885 } finally {
886 restoreCallingIdentity(identityToken);
887 }
Fred Quintana60307342009-03-24 22:48:12 -0700888 }
889
Fred Quintanaa698f422009-04-08 19:14:54 -0700890 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -0800891 if (Log.isLoggable(TAG, Log.VERBOSE)) {
892 Log.v(TAG, "setAuthToken: " + account
893 + ", caller's uid " + Binder.getCallingUid()
894 + ", pid " + Binder.getCallingPid());
895 }
Fred Quintana382601f2010-03-25 12:25:10 -0700896 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700897 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800898 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700899 long identityToken = clearCallingIdentity();
900 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800901 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700902 } finally {
903 restoreCallingIdentity(identityToken);
904 }
Fred Quintana60307342009-03-24 22:48:12 -0700905 }
906
Amith Yamasani04e0d262012-02-14 11:50:53 -0800907 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700908 if (account == null) {
909 return;
910 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800911 synchronized (accounts.cacheLock) {
912 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800913 db.beginTransaction();
914 try {
915 final ContentValues values = new ContentValues();
916 values.put(ACCOUNTS_PASSWORD, password);
917 final long accountId = getAccountIdLocked(db, account);
918 if (accountId >= 0) {
919 final String[] argsAccountId = {String.valueOf(accountId)};
920 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
921 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800922 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800923 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -0800924 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800925 } finally {
926 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800927 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800928 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800929 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700930 }
931
Amith Yamasani04e0d262012-02-14 11:50:53 -0800932 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800933 Log.i(TAG, "the accounts changed, sending broadcast of "
934 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700935 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -0700936 }
937
Fred Quintanaa698f422009-04-08 19:14:54 -0700938 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800939 if (Log.isLoggable(TAG, Log.VERBOSE)) {
940 Log.v(TAG, "clearPassword: " + account
941 + ", caller's uid " + Binder.getCallingUid()
942 + ", pid " + Binder.getCallingPid());
943 }
Fred Quintana382601f2010-03-25 12:25:10 -0700944 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700945 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800946 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700947 long identityToken = clearCallingIdentity();
948 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800949 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700950 } finally {
951 restoreCallingIdentity(identityToken);
952 }
Fred Quintana60307342009-03-24 22:48:12 -0700953 }
954
Fred Quintanaa698f422009-04-08 19:14:54 -0700955 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -0800956 if (Log.isLoggable(TAG, Log.VERBOSE)) {
957 Log.v(TAG, "setUserData: " + account
958 + ", key " + key
959 + ", caller's uid " + Binder.getCallingUid()
960 + ", pid " + Binder.getCallingPid());
961 }
Fred Quintana382601f2010-03-25 12:25:10 -0700962 if (key == null) throw new IllegalArgumentException("key is null");
963 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700964 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800965 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700966 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700967 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800968 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700969 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700970 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700971 }
972 }
973
Amith Yamasani04e0d262012-02-14 11:50:53 -0800974 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
975 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700976 if (account == null || key == null) {
977 return;
978 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800979 synchronized (accounts.cacheLock) {
980 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800981 db.beginTransaction();
982 try {
983 long accountId = getAccountIdLocked(db, account);
984 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700985 return;
986 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800987 long extrasId = getExtrasIdLocked(db, accountId, key);
988 if (extrasId < 0 ) {
989 extrasId = insertExtraLocked(db, accountId, key, value);
990 if (extrasId < 0) {
991 return;
992 }
993 } else {
994 ContentValues values = new ContentValues();
995 values.put(EXTRAS_VALUE, value);
996 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
997 return;
998 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700999
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001000 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001001 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001002 db.setTransactionSuccessful();
1003 } finally {
1004 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001005 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001006 }
1007 }
1008
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001009 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001010 if (result == null) {
1011 Log.e(TAG, "the result is unexpectedly null", new Exception());
1012 }
1013 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1014 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1015 + response);
1016 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001017 try {
1018 response.onResult(result);
1019 } catch (RemoteException e) {
1020 // if the caller is dead then there is no one to care about remote
1021 // exceptions
1022 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1023 Log.v(TAG, "failure while notifying response", e);
1024 }
1025 }
1026 }
1027
Fred Quintanad9640ec2012-05-23 12:37:00 -07001028 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1029 final String authTokenType)
1030 throws RemoteException {
1031 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001032 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1033
Fred Quintanad9640ec2012-05-23 12:37:00 -07001034 final int callingUid = getCallingUid();
1035 clearCallingIdentity();
1036 if (callingUid != android.os.Process.SYSTEM_UID) {
1037 throw new SecurityException("can only call from system");
1038 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001039 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001040 long identityToken = clearCallingIdentity();
1041 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001042 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001043 false /* stripAuthTokenFromResult */) {
1044 protected String toDebugString(long now) {
1045 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001046 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001047 + ", authTokenType " + authTokenType;
1048 }
1049
1050 public void run() throws RemoteException {
1051 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1052 }
1053
1054 public void onResult(Bundle result) {
1055 if (result != null) {
1056 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1057 Bundle bundle = new Bundle();
1058 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1059 super.onResult(bundle);
1060 return;
1061 } else {
1062 super.onResult(result);
1063 }
1064 }
1065 }.bind();
1066 } finally {
1067 restoreCallingIdentity(identityToken);
1068 }
1069 }
1070
Fred Quintanaa698f422009-04-08 19:14:54 -07001071 public void getAuthToken(IAccountManagerResponse response, final Account account,
1072 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001073 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001074 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1075 Log.v(TAG, "getAuthToken: " + account
1076 + ", response " + response
1077 + ", authTokenType " + authTokenType
1078 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1079 + ", expectActivityLaunch " + expectActivityLaunch
1080 + ", caller's uid " + Binder.getCallingUid()
1081 + ", pid " + Binder.getCallingPid());
1082 }
Fred Quintana382601f2010-03-25 12:25:10 -07001083 if (response == null) throw new IllegalArgumentException("response is null");
1084 if (account == null) throw new IllegalArgumentException("account is null");
1085 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001086 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001087 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001088 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1089 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1090 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001091 final boolean customTokens =
1092 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1093
1094 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001095 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001096 final boolean permissionGranted = customTokens ||
1097 permissionIsGranted(account, authTokenType, callerUid);
1098
Costin Manolachec6684f92011-01-14 11:25:39 -08001099 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1100 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001101 // let authenticator know the identity of the caller
1102 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1103 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1104 if (notifyOnAuthFailure) {
1105 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001106 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001107
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001108 long identityToken = clearCallingIdentity();
1109 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001110 // if the caller has permission, do the peek. otherwise go the more expensive
1111 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001112 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001113 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001114 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001115 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001116 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1117 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1118 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001119 onResult(response, result);
1120 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001121 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001122 }
1123
Amith Yamasani04e0d262012-02-14 11:50:53 -08001124 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001125 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001126 protected String toDebugString(long now) {
1127 if (loginOptions != null) loginOptions.keySet();
1128 return super.toDebugString(now) + ", getAuthToken"
1129 + ", " + account
1130 + ", authTokenType " + authTokenType
1131 + ", loginOptions " + loginOptions
1132 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1133 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001134
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001135 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001136 // If the caller doesn't have permission then create and return the
1137 // "grant permission" intent instead of the "getAuthToken" intent.
1138 if (!permissionGranted) {
1139 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1140 } else {
1141 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1142 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001143 }
1144
1145 public void onResult(Bundle result) {
1146 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001147 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001148 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1149 new AccountAuthenticatorResponse(this),
1150 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001151 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001152 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001153 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001154 onResult(bundle);
1155 return;
1156 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001157 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001158 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001159 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1160 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001161 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001162 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001163 "the type and name should not be empty");
1164 return;
1165 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001166 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001167 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001168 authTokenType, authToken);
1169 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001170 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001171
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001172 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001173 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001174 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001175 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001176 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001177 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001178 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001179 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001180 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001181 }.bind();
1182 } finally {
1183 restoreCallingIdentity(identityToken);
1184 }
Fred Quintana60307342009-03-24 22:48:12 -07001185 }
1186
Dianne Hackborn41203752012-08-31 14:05:51 -07001187 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1188 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001189 int uid = intent.getIntExtra(
1190 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1191 String authTokenType = intent.getStringExtra(
1192 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1193 String authTokenLabel = intent.getStringExtra(
1194 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1195
1196 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1197 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001198 final String titleAndSubtitle =
1199 mContext.getString(R.string.permission_request_notification_with_subtitle,
1200 account.name);
1201 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001202 String title = titleAndSubtitle;
1203 String subtitle = "";
1204 if (index > 0) {
1205 title = titleAndSubtitle.substring(0, index);
1206 subtitle = titleAndSubtitle.substring(index + 1);
1207 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001208 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001209 n.setLatestEventInfo(mContext, title, subtitle,
1210 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001211 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1212 installNotification(getCredentialPermissionNotificationId(
1213 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001214 }
1215
Costin Manolache5f383ad92010-12-02 16:44:46 -08001216 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1217 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001218
1219 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001220 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001221 // Since it was set in Eclair+ we can't change it without breaking apps using
1222 // the intent from a non-Activity context.
1223 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001224 intent.addCategory(
1225 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001226
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001227 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001228 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1229 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001230 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001231
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001232 return intent;
1233 }
1234
1235 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1236 int uid) {
1237 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001238 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001239 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001240 final Pair<Pair<Account, String>, Integer> key =
1241 new Pair<Pair<Account, String>, Integer>(
1242 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001243 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001244 if (id == null) {
1245 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001246 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001247 }
1248 }
1249 return id;
1250 }
1251
Amith Yamasani04e0d262012-02-14 11:50:53 -08001252 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001253 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001254 synchronized (accounts.signinRequiredNotificationIds) {
1255 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001256 if (id == null) {
1257 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001258 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001259 }
1260 }
1261 return id;
1262 }
1263
Fred Quintana33269202009-04-20 16:05:10 -07001264 public void addAcount(final IAccountManagerResponse response, final String accountType,
1265 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001266 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001267 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1268 Log.v(TAG, "addAccount: accountType " + accountType
1269 + ", response " + response
1270 + ", authTokenType " + authTokenType
1271 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1272 + ", expectActivityLaunch " + expectActivityLaunch
1273 + ", caller's uid " + Binder.getCallingUid()
1274 + ", pid " + Binder.getCallingPid());
1275 }
Fred Quintana382601f2010-03-25 12:25:10 -07001276 if (response == null) throw new IllegalArgumentException("response is null");
1277 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001278 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001279
Amith Yamasani04e0d262012-02-14 11:50:53 -08001280 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001281 final int pid = Binder.getCallingPid();
1282 final int uid = Binder.getCallingUid();
1283 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1284 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1285 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1286
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001287 long identityToken = clearCallingIdentity();
1288 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001289 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001290 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001291 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001292 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001293 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001294 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001295
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001296 protected String toDebugString(long now) {
1297 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001298 + ", accountType " + accountType
1299 + ", requiredFeatures "
1300 + (requiredFeatures != null
1301 ? TextUtils.join(",", requiredFeatures)
1302 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001303 }
1304 }.bind();
1305 } finally {
1306 restoreCallingIdentity(identityToken);
1307 }
Fred Quintana60307342009-03-24 22:48:12 -07001308 }
1309
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001310 @Override
1311 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1312 final Account account, final Bundle options, final boolean expectActivityLaunch,
1313 int userId) {
1314 // Only allow the system process to read accounts of other users
1315 if (userId != UserHandle.getCallingUserId()
1316 && Binder.getCallingUid() != android.os.Process.myUid()) {
1317 throw new SecurityException("User " + UserHandle.getCallingUserId()
1318 + " trying to confirm account credentials for " + userId);
1319 }
1320
Fred Quintana56285a62010-12-02 14:20:51 -08001321 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1322 Log.v(TAG, "confirmCredentials: " + account
1323 + ", response " + response
1324 + ", expectActivityLaunch " + expectActivityLaunch
1325 + ", caller's uid " + Binder.getCallingUid()
1326 + ", pid " + Binder.getCallingPid());
1327 }
Fred Quintana382601f2010-03-25 12:25:10 -07001328 if (response == null) throw new IllegalArgumentException("response is null");
1329 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001330 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001331 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001332 long identityToken = clearCallingIdentity();
1333 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001334 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001335 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001336 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001337 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001338 }
1339 protected String toDebugString(long now) {
1340 return super.toDebugString(now) + ", confirmCredentials"
1341 + ", " + account;
1342 }
1343 }.bind();
1344 } finally {
1345 restoreCallingIdentity(identityToken);
1346 }
Fred Quintana60307342009-03-24 22:48:12 -07001347 }
1348
Fred Quintanaa698f422009-04-08 19:14:54 -07001349 public void updateCredentials(IAccountManagerResponse response, final Account account,
1350 final String authTokenType, final boolean expectActivityLaunch,
1351 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001352 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1353 Log.v(TAG, "updateCredentials: " + account
1354 + ", response " + response
1355 + ", authTokenType " + authTokenType
1356 + ", expectActivityLaunch " + expectActivityLaunch
1357 + ", caller's uid " + Binder.getCallingUid()
1358 + ", pid " + Binder.getCallingPid());
1359 }
Fred Quintana382601f2010-03-25 12:25:10 -07001360 if (response == null) throw new IllegalArgumentException("response is null");
1361 if (account == null) throw new IllegalArgumentException("account is null");
1362 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001363 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001364 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001365 long identityToken = clearCallingIdentity();
1366 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001367 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001368 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001369 public void run() throws RemoteException {
1370 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1371 }
1372 protected String toDebugString(long now) {
1373 if (loginOptions != null) loginOptions.keySet();
1374 return super.toDebugString(now) + ", updateCredentials"
1375 + ", " + account
1376 + ", authTokenType " + authTokenType
1377 + ", loginOptions " + loginOptions;
1378 }
1379 }.bind();
1380 } finally {
1381 restoreCallingIdentity(identityToken);
1382 }
Fred Quintana60307342009-03-24 22:48:12 -07001383 }
1384
Fred Quintanaa698f422009-04-08 19:14:54 -07001385 public void editProperties(IAccountManagerResponse response, final String accountType,
1386 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001387 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1388 Log.v(TAG, "editProperties: accountType " + accountType
1389 + ", response " + response
1390 + ", expectActivityLaunch " + expectActivityLaunch
1391 + ", caller's uid " + Binder.getCallingUid()
1392 + ", pid " + Binder.getCallingPid());
1393 }
Fred Quintana382601f2010-03-25 12:25:10 -07001394 if (response == null) throw new IllegalArgumentException("response is null");
1395 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001396 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001397 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001398 long identityToken = clearCallingIdentity();
1399 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001400 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001401 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001402 public void run() throws RemoteException {
1403 mAuthenticator.editProperties(this, mAccountType);
1404 }
1405 protected String toDebugString(long now) {
1406 return super.toDebugString(now) + ", editProperties"
1407 + ", accountType " + accountType;
1408 }
1409 }.bind();
1410 } finally {
1411 restoreCallingIdentity(identityToken);
1412 }
Fred Quintana60307342009-03-24 22:48:12 -07001413 }
1414
Fred Quintana33269202009-04-20 16:05:10 -07001415 private class GetAccountsByTypeAndFeatureSession extends Session {
1416 private final String[] mFeatures;
1417 private volatile Account[] mAccountsOfType = null;
1418 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1419 private volatile int mCurrentAccount = 0;
1420
Amith Yamasani04e0d262012-02-14 11:50:53 -08001421 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
1422 IAccountManagerResponse response, String type, String[] features) {
1423 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001424 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001425 mFeatures = features;
1426 }
1427
1428 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001429 synchronized (mAccounts.cacheLock) {
1430 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001431 }
Fred Quintana33269202009-04-20 16:05:10 -07001432 // check whether each account matches the requested features
1433 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1434 mCurrentAccount = 0;
1435
1436 checkAccount();
1437 }
1438
1439 public void checkAccount() {
1440 if (mCurrentAccount >= mAccountsOfType.length) {
1441 sendResult();
1442 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001443 }
Fred Quintana33269202009-04-20 16:05:10 -07001444
Fred Quintana29e94b82010-03-10 12:11:51 -08001445 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1446 if (accountAuthenticator == null) {
1447 // It is possible that the authenticator has died, which is indicated by
1448 // mAuthenticator being set to null. If this happens then just abort.
1449 // There is no need to send back a result or error in this case since
1450 // that already happened when mAuthenticator was cleared.
1451 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1452 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1453 + " connected to the authenticator, " + toDebugString());
1454 }
1455 return;
1456 }
Fred Quintana33269202009-04-20 16:05:10 -07001457 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001458 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001459 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001460 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001461 }
1462 }
1463
1464 public void onResult(Bundle result) {
1465 mNumResults++;
1466 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001467 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001468 return;
1469 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001470 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001471 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1472 }
1473 mCurrentAccount++;
1474 checkAccount();
1475 }
1476
1477 public void sendResult() {
1478 IAccountManagerResponse response = getResponseAndClose();
1479 if (response != null) {
1480 try {
1481 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1482 for (int i = 0; i < accounts.length; i++) {
1483 accounts[i] = mAccountsWithFeatures.get(i);
1484 }
Fred Quintana56285a62010-12-02 14:20:51 -08001485 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1486 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1487 + response);
1488 }
Fred Quintana33269202009-04-20 16:05:10 -07001489 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001490 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001491 response.onResult(result);
1492 } catch (RemoteException e) {
1493 // if the caller is dead then there is no one to care about remote exceptions
1494 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1495 Log.v(TAG, "failure while notifying response", e);
1496 }
1497 }
1498 }
1499 }
1500
1501
1502 protected String toDebugString(long now) {
1503 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1504 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1505 }
1506 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001507
Amith Yamasani04e0d262012-02-14 11:50:53 -08001508 /**
1509 * Returns the accounts for a specific user
1510 * @hide
1511 */
1512 public Account[] getAccounts(int userId) {
1513 checkReadAccountsPermission();
1514 UserAccounts accounts = getUserAccounts(userId);
1515 long identityToken = clearCallingIdentity();
1516 try {
1517 synchronized (accounts.cacheLock) {
1518 return getAccountsFromCacheLocked(accounts, null);
1519 }
1520 } finally {
1521 restoreCallingIdentity(identityToken);
1522 }
1523 }
1524
Amith Yamasanif29f2362012-04-05 18:29:52 -07001525 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001526 * Returns accounts for all running users.
1527 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001528 * @hide
1529 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001530 public AccountAndUser[] getRunningAccounts() {
1531 final int[] runningUserIds;
1532 try {
1533 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1534 } catch (RemoteException e) {
1535 // Running in system_server; should never happen
1536 throw new RuntimeException(e);
1537 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001538 return getAccounts(runningUserIds);
1539 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001540
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001541 /** {@hide} */
1542 public AccountAndUser[] getAllAccounts() {
1543 final List<UserInfo> users = getUserManager().getUsers();
1544 final int[] userIds = new int[users.size()];
1545 for (int i = 0; i < userIds.length; i++) {
1546 userIds[i] = users.get(i).id;
1547 }
1548 return getAccounts(userIds);
1549 }
1550
1551 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001552 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1553 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001554 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001555 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001556 if (userAccounts == null) continue;
1557 synchronized (userAccounts.cacheLock) {
1558 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null);
1559 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001560 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001561 }
1562 }
1563 }
1564 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001565
1566 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1567 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001568 }
1569
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001570 @Override
1571 public Account[] getAccountsAsUser(String type, int userId) {
1572 // Only allow the system process to read accounts of other users
1573 if (userId != UserHandle.getCallingUserId()
1574 && Binder.getCallingUid() != android.os.Process.myUid()) {
1575 throw new SecurityException("User " + UserHandle.getCallingUserId()
1576 + " trying to get account for " + userId);
1577 }
1578
Fred Quintana56285a62010-12-02 14:20:51 -08001579 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1580 Log.v(TAG, "getAccounts: accountType " + type
1581 + ", caller's uid " + Binder.getCallingUid()
1582 + ", pid " + Binder.getCallingPid());
1583 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001584 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001585 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001586 long identityToken = clearCallingIdentity();
1587 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001588 synchronized (accounts.cacheLock) {
1589 return getAccountsFromCacheLocked(accounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001590 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001591 } finally {
1592 restoreCallingIdentity(identityToken);
1593 }
1594 }
1595
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001596 @Override
1597 public Account[] getAccounts(String type) {
1598 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1599 }
1600
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001601 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001602 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001603 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1604 Log.v(TAG, "getAccounts: accountType " + type
1605 + ", response " + response
1606 + ", features " + stringArrayToString(features)
1607 + ", caller's uid " + Binder.getCallingUid()
1608 + ", pid " + Binder.getCallingPid());
1609 }
Fred Quintana382601f2010-03-25 12:25:10 -07001610 if (response == null) throw new IllegalArgumentException("response is null");
1611 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001612 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001613 UserAccounts userAccounts = getUserAccountsForCaller();
Fred Quintana33269202009-04-20 16:05:10 -07001614 long identityToken = clearCallingIdentity();
1615 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001616 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001617 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001618 synchronized (userAccounts.cacheLock) {
1619 accounts = getAccountsFromCacheLocked(userAccounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001620 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001621 Bundle result = new Bundle();
1622 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1623 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001624 return;
1625 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001626 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001627 } finally {
1628 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001629 }
1630 }
1631
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001632 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001633 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001634 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001635 try {
1636 if (cursor.moveToNext()) {
1637 return cursor.getLong(0);
1638 }
1639 return -1;
1640 } finally {
1641 cursor.close();
1642 }
1643 }
1644
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001645 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001646 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1647 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1648 new String[]{key}, null, null, null);
1649 try {
1650 if (cursor.moveToNext()) {
1651 return cursor.getLong(0);
1652 }
1653 return -1;
1654 } finally {
1655 cursor.close();
1656 }
1657 }
1658
Fred Quintanaa698f422009-04-08 19:14:54 -07001659 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001660 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001661 IAccountManagerResponse mResponse;
1662 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001663 final boolean mExpectActivityLaunch;
1664 final long mCreationTime;
1665
Fred Quintana33269202009-04-20 16:05:10 -07001666 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001667 private int mNumRequestContinued = 0;
1668 private int mNumErrors = 0;
1669
Fred Quintana60307342009-03-24 22:48:12 -07001670
1671 IAccountAuthenticator mAuthenticator = null;
1672
Fred Quintana8570f742010-02-18 10:32:54 -08001673 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001674 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001675
Amith Yamasani04e0d262012-02-14 11:50:53 -08001676 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001677 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001678 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001679 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001680 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001681 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001682 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001683 mResponse = response;
1684 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001685 mExpectActivityLaunch = expectActivityLaunch;
1686 mCreationTime = SystemClock.elapsedRealtime();
1687 synchronized (mSessions) {
1688 mSessions.put(toString(), this);
1689 }
1690 try {
1691 response.asBinder().linkToDeath(this, 0 /* flags */);
1692 } catch (RemoteException e) {
1693 mResponse = null;
1694 binderDied();
1695 }
Fred Quintana60307342009-03-24 22:48:12 -07001696 }
1697
Fred Quintanaa698f422009-04-08 19:14:54 -07001698 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001699 if (mResponse == null) {
1700 // this session has already been closed
1701 return null;
1702 }
Fred Quintana60307342009-03-24 22:48:12 -07001703 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001704 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001705 return response;
1706 }
1707
Fred Quintanaa698f422009-04-08 19:14:54 -07001708 private void close() {
1709 synchronized (mSessions) {
1710 if (mSessions.remove(toString()) == null) {
1711 // the session was already closed, so bail out now
1712 return;
1713 }
1714 }
1715 if (mResponse != null) {
1716 // stop listening for response deaths
1717 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1718
1719 // clear this so that we don't accidentally send any further results
1720 mResponse = null;
1721 }
1722 cancelTimeout();
1723 unbind();
1724 }
1725
1726 public void binderDied() {
1727 mResponse = null;
1728 close();
1729 }
1730
1731 protected String toDebugString() {
1732 return toDebugString(SystemClock.elapsedRealtime());
1733 }
1734
1735 protected String toDebugString(long now) {
1736 return "Session: expectLaunch " + mExpectActivityLaunch
1737 + ", connected " + (mAuthenticator != null)
1738 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1739 + "/" + mNumErrors + ")"
1740 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1741 }
1742
Fred Quintana60307342009-03-24 22:48:12 -07001743 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001744 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1745 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1746 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001747 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001748 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001749 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001750 }
1751 }
1752
1753 private void unbind() {
1754 if (mAuthenticator != null) {
1755 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001756 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001757 }
1758 }
1759
1760 public void scheduleTimeout() {
1761 mMessageHandler.sendMessageDelayed(
1762 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1763 }
1764
1765 public void cancelTimeout() {
1766 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1767 }
1768
Fred Quintanab839afc2009-10-14 15:57:28 -07001769 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001770 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001771 try {
1772 run();
1773 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001774 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001775 "remote exception");
1776 }
Fred Quintana60307342009-03-24 22:48:12 -07001777 }
1778
Fred Quintanab839afc2009-10-14 15:57:28 -07001779 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001780 mAuthenticator = null;
1781 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001782 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001783 try {
1784 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1785 "disconnected");
1786 } catch (RemoteException e) {
1787 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1788 Log.v(TAG, "Session.onServiceDisconnected: "
1789 + "caught RemoteException while responding", e);
1790 }
1791 }
Fred Quintana60307342009-03-24 22:48:12 -07001792 }
1793 }
1794
Fred Quintanab839afc2009-10-14 15:57:28 -07001795 public abstract void run() throws RemoteException;
1796
Fred Quintana60307342009-03-24 22:48:12 -07001797 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001798 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001799 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001800 try {
1801 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1802 "timeout");
1803 } catch (RemoteException e) {
1804 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1805 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
1806 e);
1807 }
1808 }
Fred Quintana60307342009-03-24 22:48:12 -07001809 }
1810 }
1811
Fred Quintanaa698f422009-04-08 19:14:54 -07001812 public void onResult(Bundle result) {
1813 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001814 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1815 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1816 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001817 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1818 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001819 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
1820 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001821 }
Fred Quintana60307342009-03-24 22:48:12 -07001822 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001823 IAccountManagerResponse response;
1824 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001825 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001826 response = mResponse;
1827 } else {
1828 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001829 }
Fred Quintana60307342009-03-24 22:48:12 -07001830 if (response != null) {
1831 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001832 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001833 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1834 Log.v(TAG, getClass().getSimpleName()
1835 + " calling onError() on response " + response);
1836 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001837 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001838 "null bundle returned");
1839 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001840 if (mStripAuthTokenFromResult) {
1841 result.remove(AccountManager.KEY_AUTHTOKEN);
1842 }
Fred Quintana56285a62010-12-02 14:20:51 -08001843 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1844 Log.v(TAG, getClass().getSimpleName()
1845 + " calling onResult() on response " + response);
1846 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001847 response.onResult(result);
1848 }
Fred Quintana60307342009-03-24 22:48:12 -07001849 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001850 // if the caller is dead then there is no one to care about remote exceptions
1851 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1852 Log.v(TAG, "failure while notifying response", e);
1853 }
Fred Quintana60307342009-03-24 22:48:12 -07001854 }
1855 }
1856 }
Fred Quintana60307342009-03-24 22:48:12 -07001857
Fred Quintanaa698f422009-04-08 19:14:54 -07001858 public void onRequestContinued() {
1859 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001860 }
1861
1862 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001863 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001864 IAccountManagerResponse response = getResponseAndClose();
1865 if (response != null) {
1866 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001867 Log.v(TAG, getClass().getSimpleName()
1868 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001869 }
1870 try {
1871 response.onError(errorCode, errorMessage);
1872 } catch (RemoteException e) {
1873 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1874 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1875 }
1876 }
1877 } else {
1878 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1879 Log.v(TAG, "Session.onError: already closed");
1880 }
Fred Quintana60307342009-03-24 22:48:12 -07001881 }
1882 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001883
1884 /**
1885 * find the component name for the authenticator and initiate a bind
1886 * if no authenticator or the bind fails then return false, otherwise return true
1887 */
1888 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001889 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1890 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1891 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07001892 if (authenticatorInfo == null) {
1893 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1894 Log.v(TAG, "there is no authenticator for " + authenticatorType
1895 + ", bailing out");
1896 }
1897 return false;
1898 }
1899
1900 Intent intent = new Intent();
1901 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1902 intent.setComponent(authenticatorInfo.componentName);
1903 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1904 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1905 }
Amith Yamasani34daa752012-03-19 16:14:23 -07001906 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE, mAccounts.userId)) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001907 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1908 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1909 }
1910 return false;
1911 }
1912
1913
1914 return true;
1915 }
Fred Quintana60307342009-03-24 22:48:12 -07001916 }
1917
1918 private class MessageHandler extends Handler {
1919 MessageHandler(Looper looper) {
1920 super(looper);
1921 }
Costin Manolache3348f142009-09-29 18:58:36 -07001922
Fred Quintana60307342009-03-24 22:48:12 -07001923 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001924 switch (msg.what) {
1925 case MESSAGE_TIMED_OUT:
1926 Session session = (Session)msg.obj;
1927 session.onTimedOut();
1928 break;
1929
1930 default:
1931 throw new IllegalStateException("unhandled message: " + msg.what);
1932 }
1933 }
1934 }
1935
Amith Yamasani04e0d262012-02-14 11:50:53 -08001936 private static String getDatabaseName(int userId) {
1937 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07001938 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001939 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07001940 // Migrate old file, if it exists, to the new location.
1941 // Make sure the new file doesn't already exist. A dummy file could have been
1942 // accidentally created in the old location, causing the new one to become corrupted
1943 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08001944 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07001945 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07001946 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07001947 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07001948 if (!userDir.exists()) {
1949 if (!userDir.mkdirs()) {
1950 throw new IllegalStateException("User dir cannot be created: " + userDir);
1951 }
1952 }
1953 if (!oldFile.renameTo(databaseFile)) {
1954 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
1955 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001956 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08001957 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001958 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08001959 }
1960
Amith Yamasani04e0d262012-02-14 11:50:53 -08001961 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001962
Amith Yamasani04e0d262012-02-14 11:50:53 -08001963 public DatabaseHelper(Context context, int userId) {
1964 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001965 }
1966
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001967 /**
1968 * This call needs to be made while the mCacheLock is held. The way to
1969 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
1970 * @param db The database.
1971 */
Fred Quintana60307342009-03-24 22:48:12 -07001972 @Override
1973 public void onCreate(SQLiteDatabase db) {
1974 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1975 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1976 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1977 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1978 + ACCOUNTS_PASSWORD + " TEXT, "
1979 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1980
1981 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1982 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1983 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1984 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1985 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1986 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1987
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001988 createGrantsTable(db);
1989
Fred Quintana60307342009-03-24 22:48:12 -07001990 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1991 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1992 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1993 + EXTRAS_KEY + " TEXT NOT NULL, "
1994 + EXTRAS_VALUE + " TEXT, "
1995 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1996
1997 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1998 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1999 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002000
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002001 createAccountsDeletionTrigger(db);
2002 }
2003
2004 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002005 db.execSQL(""
2006 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2007 + " BEGIN"
2008 + " DELETE FROM " + TABLE_AUTHTOKENS
2009 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2010 + " DELETE FROM " + TABLE_EXTRAS
2011 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002012 + " DELETE FROM " + TABLE_GRANTS
2013 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002014 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002015 }
2016
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002017 private void createGrantsTable(SQLiteDatabase db) {
2018 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2019 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2020 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2021 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2022 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2023 + "," + GRANTS_GRANTEE_UID + "))");
2024 }
2025
Fred Quintana60307342009-03-24 22:48:12 -07002026 @Override
2027 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002028 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002029
Fred Quintanaa698f422009-04-08 19:14:54 -07002030 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002031 // no longer need to do anything since the work is done
2032 // when upgrading from version 2
2033 oldVersion++;
2034 }
2035
2036 if (oldVersion == 2) {
2037 createGrantsTable(db);
2038 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2039 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002040 oldVersion++;
2041 }
Costin Manolache3348f142009-09-29 18:58:36 -07002042
2043 if (oldVersion == 3) {
2044 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2045 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2046 oldVersion++;
2047 }
Fred Quintana60307342009-03-24 22:48:12 -07002048 }
2049
2050 @Override
2051 public void onOpen(SQLiteDatabase db) {
2052 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2053 }
2054 }
2055
Fred Quintana60307342009-03-24 22:48:12 -07002056 public IBinder onBind(Intent intent) {
2057 return asBinder();
2058 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002059
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002060 /**
2061 * Searches array of arguments for the specified string
2062 * @param args array of argument strings
2063 * @param value value to search for
2064 * @return true if the value is contained in the array
2065 */
2066 private static boolean scanArgs(String[] args, String value) {
2067 if (args != null) {
2068 for (String arg : args) {
2069 if (value.equals(arg)) {
2070 return true;
2071 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002072 }
2073 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002074 return false;
2075 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002076
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002077 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002078 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002079 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2080 != PackageManager.PERMISSION_GRANTED) {
2081 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2082 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2083 + " without permission " + android.Manifest.permission.DUMP);
2084 return;
2085 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002086 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002087 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002088
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002089 final List<UserInfo> users = getUserManager().getUsers();
2090 for (UserInfo user : users) {
2091 ipw.println("User " + user + ":");
2092 ipw.increaseIndent();
2093 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2094 ipw.println();
2095 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002096 }
2097 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002098
Amith Yamasani04e0d262012-02-14 11:50:53 -08002099 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2100 String[] args, boolean isCheckinRequest) {
2101 synchronized (userAccounts.cacheLock) {
2102 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002103
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002104 if (isCheckinRequest) {
2105 // This is a checkin request. *Only* upload the account types and the count of each.
2106 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2107 null, null, ACCOUNTS_TYPE, null, null);
2108 try {
2109 while (cursor.moveToNext()) {
2110 // print type,count
2111 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2112 }
2113 } finally {
2114 if (cursor != null) {
2115 cursor.close();
2116 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002117 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002118 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002119 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002120 fout.println("Accounts: " + accounts.length);
2121 for (Account account : accounts) {
2122 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002123 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002124
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002125 fout.println();
2126 synchronized (mSessions) {
2127 final long now = SystemClock.elapsedRealtime();
2128 fout.println("Active Sessions: " + mSessions.size());
2129 for (Session session : mSessions.values()) {
2130 fout.println(" " + session.toDebugString(now));
2131 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002132 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002133
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002134 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002135 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002136 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002137 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002138 }
2139
Amith Yamasani04e0d262012-02-14 11:50:53 -08002140 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002141 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002142 long identityToken = clearCallingIdentity();
2143 try {
2144 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2145 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2146 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002147
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002148 if (intent.getComponent() != null &&
2149 GrantCredentialsPermissionActivity.class.getName().equals(
2150 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002151 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002152 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002153 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002154 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002155 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2156 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002157 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002158 final String notificationTitleFormat =
2159 mContext.getText(R.string.notification_title).toString();
2160 n.setLatestEventInfo(mContext,
2161 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002162 message, PendingIntent.getActivityAsUser(
2163 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002164 null, user));
2165 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002166 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002167 } finally {
2168 restoreCallingIdentity(identityToken);
2169 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002170 }
2171
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002172 protected void installNotification(final int notificationId, final Notification n,
2173 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002174 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002175 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002176 }
2177
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002178 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002179 long identityToken = clearCallingIdentity();
2180 try {
2181 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002182 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002183 } finally {
2184 restoreCallingIdentity(identityToken);
2185 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002186 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002187
Fred Quintanab38eb142010-02-24 13:40:54 -08002188 /** Succeeds if any of the specified permissions are granted. */
2189 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002190 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002191
2192 for (String perm : permissions) {
2193 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2194 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002195 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002196 }
2197 return;
2198 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002199 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002200
2201 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002202 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002203 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002204 }
2205
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002206 private boolean inSystemImage(int callingUid) {
2207 final int callingUserId = UserHandle.getUserId(callingUid);
2208
2209 final PackageManager userPackageManager;
2210 try {
2211 userPackageManager = mContext.createPackageContextAsUser(
2212 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2213 } catch (NameNotFoundException e) {
2214 return false;
2215 }
2216
2217 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002218 for (String name : packages) {
2219 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002220 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002221 if (packageInfo != null
2222 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002223 return true;
2224 }
2225 } catch (PackageManager.NameNotFoundException e) {
2226 return false;
2227 }
2228 }
2229 return false;
2230 }
2231
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002232 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002233 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002234 final boolean fromAuthenticator = account != null
2235 && hasAuthenticatorUid(account.type, callerUid);
2236 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002237 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002238 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2239 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002240 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002241 + ": is authenticator? " + fromAuthenticator
2242 + ", has explicit permission? " + hasExplicitGrants);
2243 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002244 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002245 }
2246
Fred Quintana1a231912009-10-15 11:31:30 -07002247 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002248 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002249 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002250 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002251 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002252 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002253 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002254 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002255 }
2256 }
2257 return false;
2258 }
2259
Amith Yamasani04e0d262012-02-14 11:50:53 -08002260 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2261 int callerUid) {
2262 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002263 return true;
2264 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002265 UserAccounts accounts = getUserAccountsForCaller();
2266 synchronized (accounts.cacheLock) {
2267 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2268 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002269 account.name, account.type};
2270 final boolean permissionGranted =
2271 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2272 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2273 // TODO: Skip this check when running automated tests. Replace this
2274 // with a more general solution.
2275 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002276 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002277 + " but ignoring since device is in test harness.");
2278 return true;
2279 }
2280 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002281 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002282 }
2283
2284 private void checkCallingUidAgainstAuthenticator(Account account) {
2285 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002286 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002287 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2288 Log.w(TAG, msg);
2289 throw new SecurityException(msg);
2290 }
2291 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2292 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2293 }
2294 }
2295
2296 private void checkAuthenticateAccountsPermission(Account account) {
2297 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2298 checkCallingUidAgainstAuthenticator(account);
2299 }
2300
2301 private void checkReadAccountsPermission() {
2302 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2303 }
2304
2305 private void checkManageAccountsPermission() {
2306 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2307 }
2308
Fred Quintanab38eb142010-02-24 13:40:54 -08002309 private void checkManageAccountsOrUseCredentialsPermissions() {
2310 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2311 Manifest.permission.USE_CREDENTIALS);
2312 }
2313
Fred Quintanad9640ec2012-05-23 12:37:00 -07002314 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2315 throws RemoteException {
2316 final int callingUid = getCallingUid();
2317
2318 if (callingUid != android.os.Process.SYSTEM_UID) {
2319 throw new SecurityException();
2320 }
2321
2322 if (value) {
2323 grantAppPermission(account, authTokenType, uid);
2324 } else {
2325 revokeAppPermission(account, authTokenType, uid);
2326 }
2327 }
2328
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002329 /**
2330 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2331 * <p>
2332 * Although this is public it can only be accessed via the AccountManagerService object
2333 * which is in the system. This means we don't need to protect it with permissions.
2334 * @hide
2335 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002336 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002337 if (account == null || authTokenType == null) {
2338 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002339 return;
2340 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002341 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002342 synchronized (accounts.cacheLock) {
2343 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002344 db.beginTransaction();
2345 try {
2346 long accountId = getAccountIdLocked(db, account);
2347 if (accountId >= 0) {
2348 ContentValues values = new ContentValues();
2349 values.put(GRANTS_ACCOUNTS_ID, accountId);
2350 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2351 values.put(GRANTS_GRANTEE_UID, uid);
2352 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2353 db.setTransactionSuccessful();
2354 }
2355 } finally {
2356 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002357 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002358 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2359 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002360 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002361 }
2362
2363 /**
2364 * Don't allow callers with the given uid permission to get credentials for
2365 * account/authTokenType.
2366 * <p>
2367 * Although this is public it can only be accessed via the AccountManagerService object
2368 * which is in the system. This means we don't need to protect it with permissions.
2369 * @hide
2370 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002371 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002372 if (account == null || authTokenType == null) {
2373 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002374 return;
2375 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002376 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002377 synchronized (accounts.cacheLock) {
2378 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002379 db.beginTransaction();
2380 try {
2381 long accountId = getAccountIdLocked(db, account);
2382 if (accountId >= 0) {
2383 db.delete(TABLE_GRANTS,
2384 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2385 + GRANTS_GRANTEE_UID + "=?",
2386 new String[]{String.valueOf(accountId), authTokenType,
2387 String.valueOf(uid)});
2388 db.setTransactionSuccessful();
2389 }
2390 } finally {
2391 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002392 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002393 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2394 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002395 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002396 }
Fred Quintana56285a62010-12-02 14:20:51 -08002397
2398 static final private String stringArrayToString(String[] value) {
2399 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2400 }
2401
Amith Yamasani04e0d262012-02-14 11:50:53 -08002402 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2403 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002404 if (oldAccountsForType != null) {
2405 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2406 for (Account curAccount : oldAccountsForType) {
2407 if (!curAccount.equals(account)) {
2408 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002409 }
2410 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002411 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002412 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002413 } else {
2414 Account[] newAccountsForType = new Account[newAccountsList.size()];
2415 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002416 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002417 }
Fred Quintana56285a62010-12-02 14:20:51 -08002418 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002419 accounts.userDataCache.remove(account);
2420 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002421 }
2422
2423 /**
2424 * This assumes that the caller has already checked that the account is not already present.
2425 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002426 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2427 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002428 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2429 Account[] newAccountsForType = new Account[oldLength + 1];
2430 if (accountsForType != null) {
2431 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002432 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002433 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002434 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002435 }
2436
Amith Yamasani04e0d262012-02-14 11:50:53 -08002437 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002438 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002439 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002440 if (accounts == null) {
2441 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002442 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002443 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002444 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002445 } else {
2446 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002447 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002448 totalLength += accounts.length;
2449 }
2450 if (totalLength == 0) {
2451 return EMPTY_ACCOUNT_ARRAY;
2452 }
2453 Account[] accounts = new Account[totalLength];
2454 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002455 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002456 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2457 accountsOfType.length);
2458 totalLength += accountsOfType.length;
2459 }
2460 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002461 }
2462 }
2463
Amith Yamasani04e0d262012-02-14 11:50:53 -08002464 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2465 Account account, String key, String value) {
2466 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002467 if (userDataForAccount == null) {
2468 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002469 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002470 }
2471 if (value == null) {
2472 userDataForAccount.remove(key);
2473 } else {
2474 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002475 }
2476 }
2477
Amith Yamasani04e0d262012-02-14 11:50:53 -08002478 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2479 Account account, String key, String value) {
2480 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002481 if (authTokensForAccount == null) {
2482 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002483 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002484 }
2485 if (value == null) {
2486 authTokensForAccount.remove(key);
2487 } else {
2488 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002489 }
2490 }
2491
Amith Yamasani04e0d262012-02-14 11:50:53 -08002492 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2493 String authTokenType) {
2494 synchronized (accounts.cacheLock) {
2495 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002496 if (authTokensForAccount == null) {
2497 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002498 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002499 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002500 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002501 }
2502 return authTokensForAccount.get(authTokenType);
2503 }
2504 }
2505
Amith Yamasani04e0d262012-02-14 11:50:53 -08002506 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2507 synchronized (accounts.cacheLock) {
2508 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002509 if (userDataForAccount == null) {
2510 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002511 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002512 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002513 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002514 }
2515 return userDataForAccount.get(key);
2516 }
2517 }
2518
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002519 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2520 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002521 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002522 Cursor cursor = db.query(TABLE_EXTRAS,
2523 COLUMNS_EXTRAS_KEY_AND_VALUE,
2524 SELECTION_USERDATA_BY_ACCOUNT,
2525 new String[]{account.name, account.type},
2526 null, null, null);
2527 try {
2528 while (cursor.moveToNext()) {
2529 final String tmpkey = cursor.getString(0);
2530 final String value = cursor.getString(1);
2531 userDataForAccount.put(tmpkey, value);
2532 }
2533 } finally {
2534 cursor.close();
2535 }
2536 return userDataForAccount;
2537 }
2538
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002539 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2540 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002541 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002542 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2543 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2544 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2545 new String[]{account.name, account.type},
2546 null, null, null);
2547 try {
2548 while (cursor.moveToNext()) {
2549 final String type = cursor.getString(0);
2550 final String authToken = cursor.getString(1);
2551 authTokensForAccount.put(type, authToken);
2552 }
2553 } finally {
2554 cursor.close();
2555 }
2556 return authTokensForAccount;
2557 }
Fred Quintana60307342009-03-24 22:48:12 -07002558}