blob: ad4b58f64ea859724610b1c21f3d1bcec1ec8a99 [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.accounts;
18
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080020import android.app.ActivityManager;
Amith Yamasani04e0d262012-02-14 11:50:53 -080021import android.app.AppGlobals;
Doug Zongker885cfc232009-10-21 16:52:44 -070022import android.app.Notification;
23import android.app.NotificationManager;
24import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070025import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070026import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070031import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070032import android.content.pm.ApplicationInfo;
33import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070034import android.content.pm.PackageManager;
35import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070036import android.content.pm.RegisteredServicesCacheListener;
Amith Yamasani04e0d262012-02-14 11:50:53 -080037import android.content.pm.UserInfo;
Brian Carlstrom46703b02011-04-06 15:41:29 -070038import android.content.res.Resources;
Fred Quintana60307342009-03-24 22:48:12 -070039import android.database.Cursor;
40import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070041import android.database.sqlite.SQLiteDatabase;
42import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070043import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070044import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080045import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070046import android.os.Handler;
47import android.os.HandlerThread;
48import android.os.IBinder;
49import android.os.Looper;
50import android.os.Message;
51import android.os.RemoteException;
52import android.os.SystemClock;
Amith Yamasani04e0d262012-02-14 11:50:53 -080053import android.os.UserId;
Fred Quintanaa698f422009-04-08 19:14:54 -070054import android.text.TextUtils;
55import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070056import android.util.Pair;
Amith Yamasani04e0d262012-02-14 11:50:53 -080057import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070058
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070059import com.android.internal.R;
Amith Yamasani04e0d262012-02-14 11:50:53 -080060import com.android.internal.util.IndentingPrintWriter;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070061
Oscar Montemayora8529f62009-11-18 10:14:20 -080062import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070063import java.io.FileDescriptor;
64import java.io.PrintWriter;
65import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080066import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070067import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070068import java.util.HashMap;
Fred Quintana56285a62010-12-02 14:20:51 -080069import java.util.LinkedHashMap;
Amith Yamasani04e0d262012-02-14 11:50:53 -080070import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080071import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070072import java.util.concurrent.atomic.AtomicInteger;
73import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070074
Fred Quintana60307342009-03-24 22:48:12 -070075/**
76 * A system service that provides account, password, and authtoken management for all
77 * accounts on the device. Some of these calls are implemented with the help of the corresponding
78 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
79 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070080 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -070081 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070082 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070083public class AccountManagerService
84 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080085 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -070086 private static final String TAG = "AccountManagerService";
87
88 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
89 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070090 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070091
92 private final Context mContext;
93
Fred Quintana56285a62010-12-02 14:20:51 -080094 private final PackageManager mPackageManager;
95
Fred Quintana60307342009-03-24 22:48:12 -070096 private HandlerThread mMessageThread;
97 private final MessageHandler mMessageHandler;
98
99 // Messages that can be sent on mHandler
100 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700101
Fred Quintana56285a62010-12-02 14:20:51 -0800102 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700103
104 private static final String TABLE_ACCOUNTS = "accounts";
105 private static final String ACCOUNTS_ID = "_id";
106 private static final String ACCOUNTS_NAME = "name";
107 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700108 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700109 private static final String ACCOUNTS_PASSWORD = "password";
110
111 private static final String TABLE_AUTHTOKENS = "authtokens";
112 private static final String AUTHTOKENS_ID = "_id";
113 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
114 private static final String AUTHTOKENS_TYPE = "type";
115 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
116
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700117 private static final String TABLE_GRANTS = "grants";
118 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
119 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
120 private static final String GRANTS_GRANTEE_UID = "uid";
121
Fred Quintana60307342009-03-24 22:48:12 -0700122 private static final String TABLE_EXTRAS = "extras";
123 private static final String EXTRAS_ID = "_id";
124 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
125 private static final String EXTRAS_KEY = "key";
126 private static final String EXTRAS_VALUE = "value";
127
128 private static final String TABLE_META = "meta";
129 private static final String META_KEY = "key";
130 private static final String META_VALUE = "value";
131
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700132 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
133 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700134 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700135
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700136 private static final String COUNT_OF_MATCHING_GRANTS = ""
137 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
138 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
139 + " AND " + GRANTS_GRANTEE_UID + "=?"
140 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
141 + " AND " + ACCOUNTS_NAME + "=?"
142 + " AND " + ACCOUNTS_TYPE + "=?";
143
Fred Quintana56285a62010-12-02 14:20:51 -0800144 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
145 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
146 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
147 AUTHTOKENS_AUTHTOKEN};
148
149 private static final String SELECTION_USERDATA_BY_ACCOUNT =
150 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
151 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
152
Fred Quintanaa698f422009-04-08 19:14:54 -0700153 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700154 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
155
Amith Yamasani04e0d262012-02-14 11:50:53 -0800156 static class UserAccounts {
157 private final int userId;
158 private final DatabaseHelper openHelper;
159 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
160 credentialsPermissionNotificationIds =
161 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
162 private final HashMap<Account, Integer> signinRequiredNotificationIds =
163 new HashMap<Account, Integer>();
164 private final Object cacheLock = new Object();
165 /** protected by the {@link #cacheLock} */
166 private final HashMap<String, Account[]> accountCache = new HashMap<String, Account[]>();
167 /** protected by the {@link #cacheLock} */
168 private HashMap<Account, HashMap<String, String>> userDataCache =
169 new HashMap<Account, HashMap<String, String>>();
170 /** protected by the {@link #cacheLock} */
171 private HashMap<Account, HashMap<String, String>> authTokenCache =
172 new HashMap<Account, HashMap<String, String>>();
173
174 UserAccounts(Context context, int userId) {
175 this.userId = userId;
176 synchronized (cacheLock) {
177 openHelper = new DatabaseHelper(context, userId);
178 }
179 }
180 }
181
182 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
183
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700184 private static AtomicReference<AccountManagerService> sThis =
185 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700186 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700187
188 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700189 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700190 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
191 }
192
Fred Quintana56285a62010-12-02 14:20:51 -0800193
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700194 /**
195 * This should only be called by system code. One should only call this after the service
196 * has started.
197 * @return a reference to the AccountManagerService instance
198 * @hide
199 */
200 public static AccountManagerService getSingleton() {
201 return sThis.get();
202 }
Fred Quintana60307342009-03-24 22:48:12 -0700203
Fred Quintana56285a62010-12-02 14:20:51 -0800204 public AccountManagerService(Context context) {
205 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700206 }
207
Fred Quintana56285a62010-12-02 14:20:51 -0800208 public AccountManagerService(Context context, PackageManager packageManager,
209 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700210 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800211 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700212
Fred Quintana60307342009-03-24 22:48:12 -0700213 mMessageThread = new HandlerThread("AccountManagerService");
214 mMessageThread.start();
215 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
216
Fred Quintana56285a62010-12-02 14:20:51 -0800217 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800218 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700219
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700220 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800221
Fred Quintana70e61902012-03-20 14:10:16 -0700222 UserAccounts accounts = initUser(0);
223
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800224 IntentFilter intentFilter = new IntentFilter();
225 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
226 intentFilter.addDataScheme("package");
227 mContext.registerReceiver(new BroadcastReceiver() {
228 @Override
229 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800230 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800231 }
232 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800233
Amith Yamasani13593602012-03-22 16:16:17 -0700234 IntentFilter userFilter = new IntentFilter();
235 userFilter.addAction(Intent.ACTION_USER_REMOVED);
236 mContext.registerReceiver(new BroadcastReceiver() {
237 @Override
238 public void onReceive(Context context, Intent intent) {
239 onUserRemoved(intent);
240 }
241 }, userFilter);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800242 }
243
Amith Yamasani04e0d262012-02-14 11:50:53 -0800244 private UserAccounts initUser(int userId) {
245 synchronized (mUsers) {
246 UserAccounts accounts = mUsers.get(userId);
247 if (accounts == null) {
248 accounts = new UserAccounts(mContext, userId);
249 mUsers.append(userId, accounts);
250 purgeOldGrants(accounts);
251 validateAccountsAndPopulateCache(accounts);
252 }
253 return accounts;
254 }
255 }
256
257 private void purgeOldGrantsAll() {
258 synchronized (mUsers) {
259 for (int i = 0; i < mUsers.size(); i++) {
260 purgeOldGrants(mUsers.valueAt(i));
261 }
262 }
263 }
264
265 private void purgeOldGrants(UserAccounts accounts) {
266 synchronized (accounts.cacheLock) {
267 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800268 final Cursor cursor = db.query(TABLE_GRANTS,
269 new String[]{GRANTS_GRANTEE_UID},
270 null, null, GRANTS_GRANTEE_UID, null, null);
271 try {
272 while (cursor.moveToNext()) {
273 final int uid = cursor.getInt(0);
274 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
275 if (packageExists) {
276 continue;
277 }
278 Log.d(TAG, "deleting grants for UID " + uid
279 + " because its package is no longer installed");
280 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
281 new String[]{Integer.toString(uid)});
282 }
283 } finally {
284 cursor.close();
285 }
286 }
287 }
288
Amith Yamasani04e0d262012-02-14 11:50:53 -0800289 private void validateAccountsAndPopulateCache(UserAccounts accounts) {
290 synchronized (accounts.cacheLock) {
291 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800292 boolean accountDeleted = false;
293 Cursor cursor = db.query(TABLE_ACCOUNTS,
294 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
295 null, null, null, null, null);
296 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800297 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800298 final HashMap<String, ArrayList<String>> accountNamesByType =
299 new HashMap<String, ArrayList<String>>();
300 while (cursor.moveToNext()) {
301 final long accountId = cursor.getLong(0);
302 final String accountType = cursor.getString(1);
303 final String accountName = cursor.getString(2);
304 if (mAuthenticatorCache.getServiceInfo(
305 AuthenticatorDescription.newKey(accountType)) == null) {
306 Log.d(TAG, "deleting account " + accountName + " because type "
307 + accountType + " no longer has a registered authenticator");
308 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
309 accountDeleted = true;
310 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800311 accounts.userDataCache.remove(account);
312 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800313 } else {
314 ArrayList<String> accountNames = accountNamesByType.get(accountType);
315 if (accountNames == null) {
316 accountNames = new ArrayList<String>();
317 accountNamesByType.put(accountType, accountNames);
318 }
319 accountNames.add(accountName);
320 }
321 }
Andy McFadden2f362292012-01-20 14:43:38 -0800322 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800323 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800324 final String accountType = cur.getKey();
325 final ArrayList<String> accountNames = cur.getValue();
326 final Account[] accountsForType = new Account[accountNames.size()];
327 int i = 0;
328 for (String accountName : accountNames) {
329 accountsForType[i] = new Account(accountName, accountType);
330 ++i;
331 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800332 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800333 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800334 } finally {
335 cursor.close();
336 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800337 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800338 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800339 }
340 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700341 }
342
Amith Yamasani04e0d262012-02-14 11:50:53 -0800343 private UserAccounts getUserAccountsForCaller() {
344 return getUserAccounts(UserId.getCallingUserId());
345 }
346
347 protected UserAccounts getUserAccounts(int userId) {
348 synchronized (mUsers) {
349 UserAccounts accounts = mUsers.get(userId);
350 if (accounts == null) {
351 accounts = initUser(userId);
352 mUsers.append(userId, accounts);
353 }
354 return accounts;
355 }
356 }
357
Amith Yamasani13593602012-03-22 16:16:17 -0700358 private void onUserRemoved(Intent intent) {
359 int userId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
360 if (userId < 1) return;
361
362 UserAccounts accounts;
363 synchronized (mUsers) {
364 accounts = mUsers.get(userId);
365 mUsers.remove(userId);
366 }
367 if (accounts == null) {
368 File dbFile = new File(getDatabaseName(userId));
369 dbFile.delete();
370 return;
371 }
372
373 synchronized (accounts.cacheLock) {
374 accounts.openHelper.close();
375 File dbFile = new File(getDatabaseName(userId));
376 dbFile.delete();
377 }
378 }
379
Amith Yamasani04e0d262012-02-14 11:50:53 -0800380 private List<UserInfo> getAllUsers() {
381 try {
382 return AppGlobals.getPackageManager().getUsers();
383 } catch (RemoteException re) {
384 // Local to system process, shouldn't happen
385 }
386 return null;
387 }
388
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800389 public void onServiceChanged(AuthenticatorDescription desc, boolean removed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800390 // Validate accounts for all users
391 List<UserInfo> users = getAllUsers();
392 if (users == null) {
393 validateAccountsAndPopulateCache(getUserAccountsForCaller());
394 } else {
395 for (UserInfo user : users) {
396 validateAccountsAndPopulateCache(getUserAccounts(user.id));
397 }
398 }
Fred Quintana60307342009-03-24 22:48:12 -0700399 }
400
Fred Quintanaa698f422009-04-08 19:14:54 -0700401 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800402 if (Log.isLoggable(TAG, Log.VERBOSE)) {
403 Log.v(TAG, "getPassword: " + account
404 + ", caller's uid " + Binder.getCallingUid()
405 + ", pid " + Binder.getCallingPid());
406 }
Fred Quintana382601f2010-03-25 12:25:10 -0700407 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700408 checkAuthenticateAccountsPermission(account);
409
Amith Yamasani04e0d262012-02-14 11:50:53 -0800410 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700411 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700412 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800413 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700414 } finally {
415 restoreCallingIdentity(identityToken);
416 }
417 }
418
Amith Yamasani04e0d262012-02-14 11:50:53 -0800419 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700420 if (account == null) {
421 return null;
422 }
423
Amith Yamasani04e0d262012-02-14 11:50:53 -0800424 synchronized (accounts.cacheLock) {
425 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800426 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
427 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
428 new String[]{account.name, account.type}, null, null, null);
429 try {
430 if (cursor.moveToNext()) {
431 return cursor.getString(0);
432 }
433 return null;
434 } finally {
435 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700436 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700437 }
438 }
439
440 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800441 if (Log.isLoggable(TAG, Log.VERBOSE)) {
442 Log.v(TAG, "getUserData: " + account
443 + ", key " + key
444 + ", caller's uid " + Binder.getCallingUid()
445 + ", pid " + Binder.getCallingPid());
446 }
Fred Quintana382601f2010-03-25 12:25:10 -0700447 if (account == null) throw new IllegalArgumentException("account is null");
448 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700449 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800450 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700451 long identityToken = clearCallingIdentity();
452 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800453 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700454 } finally {
455 restoreCallingIdentity(identityToken);
456 }
457 }
458
Fred Quintana97889762009-06-15 12:29:24 -0700459 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800460 if (Log.isLoggable(TAG, Log.VERBOSE)) {
461 Log.v(TAG, "getAuthenticatorTypes: "
462 + "caller's uid " + Binder.getCallingUid()
463 + ", pid " + Binder.getCallingPid());
464 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700465 long identityToken = clearCallingIdentity();
466 try {
Fred Quintana97889762009-06-15 12:29:24 -0700467 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
468 authenticatorCollection = mAuthenticatorCache.getAllServices();
469 AuthenticatorDescription[] types =
470 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700471 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700472 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700473 : authenticatorCollection) {
474 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700475 i++;
476 }
477 return types;
478 } finally {
479 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700480 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700481 }
482
Fred Quintanaa698f422009-04-08 19:14:54 -0700483 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800484 if (Log.isLoggable(TAG, Log.VERBOSE)) {
485 Log.v(TAG, "addAccount: " + account
486 + ", caller's uid " + Binder.getCallingUid()
487 + ", pid " + Binder.getCallingPid());
488 }
Fred Quintana382601f2010-03-25 12:25:10 -0700489 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700490 checkAuthenticateAccountsPermission(account);
491
Amith Yamasani04e0d262012-02-14 11:50:53 -0800492 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700493 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700494 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700495 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800496 return addAccountInternal(accounts, account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700497 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700498 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700499 }
500 }
501
Amith Yamasani04e0d262012-02-14 11:50:53 -0800502 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
503 Bundle extras) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700504 if (account == null) {
505 return false;
506 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800507 synchronized (accounts.cacheLock) {
508 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800509 db.beginTransaction();
510 try {
511 long numMatches = DatabaseUtils.longForQuery(db,
512 "select count(*) from " + TABLE_ACCOUNTS
513 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
514 new String[]{account.name, account.type});
515 if (numMatches > 0) {
516 Log.w(TAG, "insertAccountIntoDatabase: " + account
517 + ", skipping since the account already exists");
518 return false;
519 }
520 ContentValues values = new ContentValues();
521 values.put(ACCOUNTS_NAME, account.name);
522 values.put(ACCOUNTS_TYPE, account.type);
523 values.put(ACCOUNTS_PASSWORD, password);
524 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
525 if (accountId < 0) {
526 Log.w(TAG, "insertAccountIntoDatabase: " + account
527 + ", skipping the DB insert failed");
528 return false;
529 }
530 if (extras != null) {
531 for (String key : extras.keySet()) {
532 final String value = extras.getString(key);
533 if (insertExtraLocked(db, accountId, key, value) < 0) {
534 Log.w(TAG, "insertAccountIntoDatabase: " + account
535 + ", skipping since insertExtra failed for key " + key);
536 return false;
537 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700538 }
539 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800540 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800541 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800542 } finally {
543 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700544 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800545 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800546 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700547 }
548 }
549
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800550 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700551 ContentValues values = new ContentValues();
552 values.put(EXTRAS_KEY, key);
553 values.put(EXTRAS_ACCOUNTS_ID, accountId);
554 values.put(EXTRAS_VALUE, value);
555 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
556 }
557
Fred Quintana3084a6f2010-01-14 18:02:03 -0800558 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800559 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800560 if (Log.isLoggable(TAG, Log.VERBOSE)) {
561 Log.v(TAG, "hasFeatures: " + account
562 + ", response " + response
563 + ", features " + stringArrayToString(features)
564 + ", caller's uid " + Binder.getCallingUid()
565 + ", pid " + Binder.getCallingPid());
566 }
Fred Quintana382601f2010-03-25 12:25:10 -0700567 if (response == null) throw new IllegalArgumentException("response is null");
568 if (account == null) throw new IllegalArgumentException("account is null");
569 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800570 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800571 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800572 long identityToken = clearCallingIdentity();
573 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800574 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800575 } finally {
576 restoreCallingIdentity(identityToken);
577 }
578 }
579
580 private class TestFeaturesSession extends Session {
581 private final String[] mFeatures;
582 private final Account mAccount;
583
Amith Yamasani04e0d262012-02-14 11:50:53 -0800584 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800585 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800586 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800587 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800588 mFeatures = features;
589 mAccount = account;
590 }
591
592 public void run() throws RemoteException {
593 try {
594 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
595 } catch (RemoteException e) {
596 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
597 }
598 }
599
600 public void onResult(Bundle result) {
601 IAccountManagerResponse response = getResponseAndClose();
602 if (response != null) {
603 try {
604 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700605 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800606 return;
607 }
Fred Quintana56285a62010-12-02 14:20:51 -0800608 if (Log.isLoggable(TAG, Log.VERBOSE)) {
609 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
610 + response);
611 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800612 final Bundle newResult = new Bundle();
613 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
614 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
615 response.onResult(newResult);
616 } catch (RemoteException e) {
617 // if the caller is dead then there is no one to care about remote exceptions
618 if (Log.isLoggable(TAG, Log.VERBOSE)) {
619 Log.v(TAG, "failure while notifying response", e);
620 }
621 }
622 }
623 }
624
625 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800626 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800627 + ", " + mAccount
628 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
629 }
630 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800631
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700632 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800633 if (Log.isLoggable(TAG, Log.VERBOSE)) {
634 Log.v(TAG, "removeAccount: " + account
635 + ", response " + response
636 + ", caller's uid " + Binder.getCallingUid()
637 + ", pid " + Binder.getCallingPid());
638 }
Fred Quintana382601f2010-03-25 12:25:10 -0700639 if (response == null) throw new IllegalArgumentException("response is null");
640 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700641 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800642 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700643 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800644
Amith Yamasani04e0d262012-02-14 11:50:53 -0800645 cancelNotification(getSigninRequiredNotificationId(accounts, account));
646 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800647 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800648 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800649 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800650 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800651 cancelNotification(id);
652 }
653 }
654 }
655
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700656 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800657 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700658 } finally {
659 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700660 }
Fred Quintana60307342009-03-24 22:48:12 -0700661 }
662
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700663 private class RemoveAccountSession extends Session {
664 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800665 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
666 Account account) {
667 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800668 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700669 mAccount = account;
670 }
671
672 protected String toDebugString(long now) {
673 return super.toDebugString(now) + ", removeAccount"
674 + ", account " + mAccount;
675 }
676
677 public void run() throws RemoteException {
678 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
679 }
680
681 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700682 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
683 && !result.containsKey(AccountManager.KEY_INTENT)) {
684 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700685 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800686 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700687 }
688 IAccountManagerResponse response = getResponseAndClose();
689 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800690 if (Log.isLoggable(TAG, Log.VERBOSE)) {
691 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
692 + response);
693 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700694 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700695 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700696 try {
697 response.onResult(result2);
698 } catch (RemoteException e) {
699 // ignore
700 }
701 }
702 }
703 super.onResult(result);
704 }
705 }
706
Amith Yamasani04e0d262012-02-14 11:50:53 -0800707 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800708 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800709 removeAccountInternal(getUserAccountsForCaller(), account);
710 }
711
712 private void removeAccountInternal(UserAccounts accounts, Account account) {
713 synchronized (accounts.cacheLock) {
714 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800715 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
716 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800717 removeAccountFromCacheLocked(accounts, account);
718 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800719 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700720 }
721
Fred Quintanaa698f422009-04-08 19:14:54 -0700722 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800723 if (Log.isLoggable(TAG, Log.VERBOSE)) {
724 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
725 + ", caller's uid " + Binder.getCallingUid()
726 + ", pid " + Binder.getCallingPid());
727 }
Fred Quintana382601f2010-03-25 12:25:10 -0700728 if (accountType == null) throw new IllegalArgumentException("accountType is null");
729 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800730 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800731 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700732 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700733 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800734 synchronized (accounts.cacheLock) {
735 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800736 db.beginTransaction();
737 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800738 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800739 db.setTransactionSuccessful();
740 } finally {
741 db.endTransaction();
742 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700743 }
Fred Quintana60307342009-03-24 22:48:12 -0700744 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700745 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700746 }
747 }
748
Amith Yamasani04e0d262012-02-14 11:50:53 -0800749 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
750 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700751 if (authToken == null || accountType == null) {
752 return;
753 }
Fred Quintana33269202009-04-20 16:05:10 -0700754 Cursor cursor = db.rawQuery(
755 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
756 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
757 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
758 + " FROM " + TABLE_ACCOUNTS
759 + " JOIN " + TABLE_AUTHTOKENS
760 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
761 + " = " + AUTHTOKENS_ACCOUNTS_ID
762 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
763 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
764 new String[]{authToken, accountType});
765 try {
766 while (cursor.moveToNext()) {
767 long authTokenId = cursor.getLong(0);
768 String accountName = cursor.getString(1);
769 String authTokenType = cursor.getString(2);
770 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800771 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800772 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700773 }
Fred Quintana33269202009-04-20 16:05:10 -0700774 } finally {
775 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700776 }
777 }
778
Amith Yamasani04e0d262012-02-14 11:50:53 -0800779 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
780 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700781 if (account == null || type == null) {
782 return false;
783 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800784 cancelNotification(getSigninRequiredNotificationId(accounts, account));
785 synchronized (accounts.cacheLock) {
786 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800787 db.beginTransaction();
788 try {
789 long accountId = getAccountIdLocked(db, account);
790 if (accountId < 0) {
791 return false;
792 }
793 db.delete(TABLE_AUTHTOKENS,
794 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
795 new String[]{type});
796 ContentValues values = new ContentValues();
797 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
798 values.put(AUTHTOKENS_TYPE, type);
799 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
800 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
801 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800802 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800803 return true;
804 }
Fred Quintana33269202009-04-20 16:05:10 -0700805 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800806 } finally {
807 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -0700808 }
Fred Quintana60307342009-03-24 22:48:12 -0700809 }
810 }
811
Fred Quintanaa698f422009-04-08 19:14:54 -0700812 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800813 if (Log.isLoggable(TAG, Log.VERBOSE)) {
814 Log.v(TAG, "peekAuthToken: " + account
815 + ", authTokenType " + authTokenType
816 + ", caller's uid " + Binder.getCallingUid()
817 + ", pid " + Binder.getCallingPid());
818 }
Fred Quintana382601f2010-03-25 12:25:10 -0700819 if (account == null) throw new IllegalArgumentException("account is null");
820 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700821 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800822 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700823 long identityToken = clearCallingIdentity();
824 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800825 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700826 } finally {
827 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700828 }
Fred Quintana60307342009-03-24 22:48:12 -0700829 }
830
Fred Quintanaa698f422009-04-08 19:14:54 -0700831 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800832 if (Log.isLoggable(TAG, Log.VERBOSE)) {
833 Log.v(TAG, "setAuthToken: " + account
834 + ", authTokenType " + authTokenType
835 + ", caller's uid " + Binder.getCallingUid()
836 + ", pid " + Binder.getCallingPid());
837 }
Fred Quintana382601f2010-03-25 12:25:10 -0700838 if (account == null) throw new IllegalArgumentException("account is null");
839 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700840 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800841 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700842 long identityToken = clearCallingIdentity();
843 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800844 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700845 } finally {
846 restoreCallingIdentity(identityToken);
847 }
Fred Quintana60307342009-03-24 22:48:12 -0700848 }
849
Fred Quintanaa698f422009-04-08 19:14:54 -0700850 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -0800851 if (Log.isLoggable(TAG, Log.VERBOSE)) {
852 Log.v(TAG, "setAuthToken: " + account
853 + ", caller's uid " + Binder.getCallingUid()
854 + ", pid " + Binder.getCallingPid());
855 }
Fred Quintana382601f2010-03-25 12:25:10 -0700856 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700857 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800858 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700859 long identityToken = clearCallingIdentity();
860 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800861 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700862 } finally {
863 restoreCallingIdentity(identityToken);
864 }
Fred Quintana60307342009-03-24 22:48:12 -0700865 }
866
Amith Yamasani04e0d262012-02-14 11:50:53 -0800867 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700868 if (account == null) {
869 return;
870 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800871 synchronized (accounts.cacheLock) {
872 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800873 db.beginTransaction();
874 try {
875 final ContentValues values = new ContentValues();
876 values.put(ACCOUNTS_PASSWORD, password);
877 final long accountId = getAccountIdLocked(db, account);
878 if (accountId >= 0) {
879 final String[] argsAccountId = {String.valueOf(accountId)};
880 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
881 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800882 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800883 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -0800884 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800885 } finally {
886 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800887 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800888 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800889 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700890 }
891
Amith Yamasani04e0d262012-02-14 11:50:53 -0800892 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800893 Log.i(TAG, "the accounts changed, sending broadcast of "
894 + ACCOUNTS_CHANGED_INTENT.getAction());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800895 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT, userId);
Fred Quintana33269202009-04-20 16:05:10 -0700896 }
897
Fred Quintanaa698f422009-04-08 19:14:54 -0700898 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800899 if (Log.isLoggable(TAG, Log.VERBOSE)) {
900 Log.v(TAG, "clearPassword: " + account
901 + ", caller's uid " + Binder.getCallingUid()
902 + ", pid " + Binder.getCallingPid());
903 }
Fred Quintana382601f2010-03-25 12:25:10 -0700904 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700905 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800906 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700907 long identityToken = clearCallingIdentity();
908 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800909 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700910 } finally {
911 restoreCallingIdentity(identityToken);
912 }
Fred Quintana60307342009-03-24 22:48:12 -0700913 }
914
Fred Quintanaa698f422009-04-08 19:14:54 -0700915 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -0800916 if (Log.isLoggable(TAG, Log.VERBOSE)) {
917 Log.v(TAG, "setUserData: " + account
918 + ", key " + key
919 + ", caller's uid " + Binder.getCallingUid()
920 + ", pid " + Binder.getCallingPid());
921 }
Fred Quintana382601f2010-03-25 12:25:10 -0700922 if (key == null) throw new IllegalArgumentException("key is null");
923 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700924 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800925 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700926 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700927 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800928 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700929 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700930 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700931 }
932 }
933
Amith Yamasani04e0d262012-02-14 11:50:53 -0800934 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
935 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700936 if (account == null || key == null) {
937 return;
938 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800939 synchronized (accounts.cacheLock) {
940 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800941 db.beginTransaction();
942 try {
943 long accountId = getAccountIdLocked(db, account);
944 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700945 return;
946 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800947 long extrasId = getExtrasIdLocked(db, accountId, key);
948 if (extrasId < 0 ) {
949 extrasId = insertExtraLocked(db, accountId, key, value);
950 if (extrasId < 0) {
951 return;
952 }
953 } else {
954 ContentValues values = new ContentValues();
955 values.put(EXTRAS_VALUE, value);
956 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
957 return;
958 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700959
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800960 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800961 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800962 db.setTransactionSuccessful();
963 } finally {
964 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700965 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700966 }
967 }
968
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700969 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -0800970 if (result == null) {
971 Log.e(TAG, "the result is unexpectedly null", new Exception());
972 }
973 if (Log.isLoggable(TAG, Log.VERBOSE)) {
974 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
975 + response);
976 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700977 try {
978 response.onResult(result);
979 } catch (RemoteException e) {
980 // if the caller is dead then there is no one to care about remote
981 // exceptions
982 if (Log.isLoggable(TAG, Log.VERBOSE)) {
983 Log.v(TAG, "failure while notifying response", e);
984 }
985 }
986 }
987
Fred Quintanad9640ec2012-05-23 12:37:00 -0700988 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
989 final String authTokenType)
990 throws RemoteException {
991 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -0800992 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
993
Fred Quintanad9640ec2012-05-23 12:37:00 -0700994 final int callingUid = getCallingUid();
995 clearCallingIdentity();
996 if (callingUid != android.os.Process.SYSTEM_UID) {
997 throw new SecurityException("can only call from system");
998 }
999 UserAccounts accounts = getUserAccounts(UserId.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001000 long identityToken = clearCallingIdentity();
1001 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001002 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001003 false /* stripAuthTokenFromResult */) {
1004 protected String toDebugString(long now) {
1005 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001006 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001007 + ", authTokenType " + authTokenType;
1008 }
1009
1010 public void run() throws RemoteException {
1011 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1012 }
1013
1014 public void onResult(Bundle result) {
1015 if (result != null) {
1016 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1017 Bundle bundle = new Bundle();
1018 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1019 super.onResult(bundle);
1020 return;
1021 } else {
1022 super.onResult(result);
1023 }
1024 }
1025 }.bind();
1026 } finally {
1027 restoreCallingIdentity(identityToken);
1028 }
1029 }
1030
Fred Quintanaa698f422009-04-08 19:14:54 -07001031 public void getAuthToken(IAccountManagerResponse response, final Account account,
1032 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001033 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001034 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1035 Log.v(TAG, "getAuthToken: " + account
1036 + ", response " + response
1037 + ", authTokenType " + authTokenType
1038 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1039 + ", expectActivityLaunch " + expectActivityLaunch
1040 + ", caller's uid " + Binder.getCallingUid()
1041 + ", pid " + Binder.getCallingPid());
1042 }
Fred Quintana382601f2010-03-25 12:25:10 -07001043 if (response == null) throw new IllegalArgumentException("response is null");
1044 if (account == null) throw new IllegalArgumentException("account is null");
1045 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001046 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001047 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolachea40c6302010-12-13 14:50:45 -08001048 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1049 mAuthenticatorCache.getServiceInfo(
1050 AuthenticatorDescription.newKey(account.type));
1051 final boolean customTokens =
1052 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1053
1054 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001055 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001056 final boolean permissionGranted = customTokens ||
1057 permissionIsGranted(account, authTokenType, callerUid);
1058
Costin Manolachec6684f92011-01-14 11:25:39 -08001059 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1060 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001061 // let authenticator know the identity of the caller
1062 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1063 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1064 if (notifyOnAuthFailure) {
1065 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001066 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001067
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001068 long identityToken = clearCallingIdentity();
1069 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001070 // if the caller has permission, do the peek. otherwise go the more expensive
1071 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001072 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001073 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001074 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001075 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001076 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1077 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1078 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001079 onResult(response, result);
1080 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001081 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001082 }
1083
Amith Yamasani04e0d262012-02-14 11:50:53 -08001084 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001085 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001086 protected String toDebugString(long now) {
1087 if (loginOptions != null) loginOptions.keySet();
1088 return super.toDebugString(now) + ", getAuthToken"
1089 + ", " + account
1090 + ", authTokenType " + authTokenType
1091 + ", loginOptions " + loginOptions
1092 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1093 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001094
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001095 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001096 // If the caller doesn't have permission then create and return the
1097 // "grant permission" intent instead of the "getAuthToken" intent.
1098 if (!permissionGranted) {
1099 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1100 } else {
1101 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1102 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001103 }
1104
1105 public void onResult(Bundle result) {
1106 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001107 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001108 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1109 new AccountAuthenticatorResponse(this),
1110 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001111 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001112 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001113 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001114 onResult(bundle);
1115 return;
1116 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001117 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001118 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001119 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1120 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001121 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001122 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001123 "the type and name should not be empty");
1124 return;
1125 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001126 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001127 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001128 authTokenType, authToken);
1129 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001130 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001131
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001132 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001133 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001134 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001135 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001136 intent);
1137 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001138 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001139 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001140 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001141 }.bind();
1142 } finally {
1143 restoreCallingIdentity(identityToken);
1144 }
Fred Quintana60307342009-03-24 22:48:12 -07001145 }
1146
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001147 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
1148 int uid = intent.getIntExtra(
1149 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1150 String authTokenType = intent.getStringExtra(
1151 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1152 String authTokenLabel = intent.getStringExtra(
1153 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1154
1155 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1156 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001157 final String titleAndSubtitle =
1158 mContext.getString(R.string.permission_request_notification_with_subtitle,
1159 account.name);
1160 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001161 String title = titleAndSubtitle;
1162 String subtitle = "";
1163 if (index > 0) {
1164 title = titleAndSubtitle.substring(0, index);
1165 subtitle = titleAndSubtitle.substring(index + 1);
1166 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001167 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -07001168 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001169 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -08001170 installNotification(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001171 }
1172
Costin Manolache5f383ad92010-12-02 16:44:46 -08001173 String getAccountLabel(String accountType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001174 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
Costin Manolache5f383ad92010-12-02 16:44:46 -08001175 mAuthenticatorCache.getServiceInfo(
1176 AuthenticatorDescription.newKey(accountType));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001177 if (serviceInfo == null) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001178 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001179 }
1180
1181 final Context authContext;
1182 try {
1183 authContext = mContext.createPackageContext(
Costin Manolache5f383ad92010-12-02 16:44:46 -08001184 serviceInfo.type.packageName, 0);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001185 } catch (PackageManager.NameNotFoundException e) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001186 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001187 }
Brian Carlstrom46703b02011-04-06 15:41:29 -07001188 try {
1189 return authContext.getString(serviceInfo.type.labelId);
1190 } catch (Resources.NotFoundException e) {
1191 throw new IllegalArgumentException("unknown account type: " + accountType);
1192 }
Costin Manolache5f383ad92010-12-02 16:44:46 -08001193 }
1194
1195 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1196 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001197
1198 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001199 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001200 // Since it was set in Eclair+ we can't change it without breaking apps using
1201 // the intent from a non-Activity context.
1202 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001203 intent.addCategory(
1204 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001205
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001206 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001207 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1208 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001209 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001210
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001211 return intent;
1212 }
1213
1214 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1215 int uid) {
1216 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001217 UserAccounts accounts = getUserAccounts(UserId.getUserId(uid));
1218 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001219 final Pair<Pair<Account, String>, Integer> key =
1220 new Pair<Pair<Account, String>, Integer>(
1221 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001222 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001223 if (id == null) {
1224 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001225 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001226 }
1227 }
1228 return id;
1229 }
1230
Amith Yamasani04e0d262012-02-14 11:50:53 -08001231 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001232 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001233 synchronized (accounts.signinRequiredNotificationIds) {
1234 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001235 if (id == null) {
1236 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001237 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001238 }
1239 }
1240 return id;
1241 }
1242
Fred Quintana33269202009-04-20 16:05:10 -07001243 public void addAcount(final IAccountManagerResponse response, final String accountType,
1244 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001245 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001246 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1247 Log.v(TAG, "addAccount: accountType " + accountType
1248 + ", response " + response
1249 + ", authTokenType " + authTokenType
1250 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1251 + ", expectActivityLaunch " + expectActivityLaunch
1252 + ", caller's uid " + Binder.getCallingUid()
1253 + ", pid " + Binder.getCallingPid());
1254 }
Fred Quintana382601f2010-03-25 12:25:10 -07001255 if (response == null) throw new IllegalArgumentException("response is null");
1256 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001257 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001258
Amith Yamasani04e0d262012-02-14 11:50:53 -08001259 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001260 final int pid = Binder.getCallingPid();
1261 final int uid = Binder.getCallingUid();
1262 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1263 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1264 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1265
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001266 long identityToken = clearCallingIdentity();
1267 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001268 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001269 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001270 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001271 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001272 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001273 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001274
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001275 protected String toDebugString(long now) {
1276 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001277 + ", accountType " + accountType
1278 + ", requiredFeatures "
1279 + (requiredFeatures != null
1280 ? TextUtils.join(",", requiredFeatures)
1281 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001282 }
1283 }.bind();
1284 } finally {
1285 restoreCallingIdentity(identityToken);
1286 }
Fred Quintana60307342009-03-24 22:48:12 -07001287 }
1288
Fred Quintanaa698f422009-04-08 19:14:54 -07001289 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001290 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001291 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1292 Log.v(TAG, "confirmCredentials: " + account
1293 + ", response " + response
1294 + ", expectActivityLaunch " + expectActivityLaunch
1295 + ", caller's uid " + Binder.getCallingUid()
1296 + ", pid " + Binder.getCallingPid());
1297 }
Fred Quintana382601f2010-03-25 12:25:10 -07001298 if (response == null) throw new IllegalArgumentException("response is null");
1299 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001300 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001301 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001302 long identityToken = clearCallingIdentity();
1303 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001304 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001305 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001306 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001307 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001308 }
1309 protected String toDebugString(long now) {
1310 return super.toDebugString(now) + ", confirmCredentials"
1311 + ", " + account;
1312 }
1313 }.bind();
1314 } finally {
1315 restoreCallingIdentity(identityToken);
1316 }
Fred Quintana60307342009-03-24 22:48:12 -07001317 }
1318
Fred Quintanaa698f422009-04-08 19:14:54 -07001319 public void updateCredentials(IAccountManagerResponse response, final Account account,
1320 final String authTokenType, final boolean expectActivityLaunch,
1321 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001322 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1323 Log.v(TAG, "updateCredentials: " + account
1324 + ", response " + response
1325 + ", authTokenType " + authTokenType
1326 + ", expectActivityLaunch " + expectActivityLaunch
1327 + ", caller's uid " + Binder.getCallingUid()
1328 + ", pid " + Binder.getCallingPid());
1329 }
Fred Quintana382601f2010-03-25 12:25:10 -07001330 if (response == null) throw new IllegalArgumentException("response is null");
1331 if (account == null) throw new IllegalArgumentException("account is null");
1332 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001333 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001334 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001335 long identityToken = clearCallingIdentity();
1336 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001337 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001338 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001339 public void run() throws RemoteException {
1340 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1341 }
1342 protected String toDebugString(long now) {
1343 if (loginOptions != null) loginOptions.keySet();
1344 return super.toDebugString(now) + ", updateCredentials"
1345 + ", " + account
1346 + ", authTokenType " + authTokenType
1347 + ", loginOptions " + loginOptions;
1348 }
1349 }.bind();
1350 } finally {
1351 restoreCallingIdentity(identityToken);
1352 }
Fred Quintana60307342009-03-24 22:48:12 -07001353 }
1354
Fred Quintanaa698f422009-04-08 19:14:54 -07001355 public void editProperties(IAccountManagerResponse response, final String accountType,
1356 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001357 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1358 Log.v(TAG, "editProperties: accountType " + accountType
1359 + ", response " + response
1360 + ", expectActivityLaunch " + expectActivityLaunch
1361 + ", caller's uid " + Binder.getCallingUid()
1362 + ", pid " + Binder.getCallingPid());
1363 }
Fred Quintana382601f2010-03-25 12:25:10 -07001364 if (response == null) throw new IllegalArgumentException("response is null");
1365 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001366 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001367 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001368 long identityToken = clearCallingIdentity();
1369 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001370 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001371 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001372 public void run() throws RemoteException {
1373 mAuthenticator.editProperties(this, mAccountType);
1374 }
1375 protected String toDebugString(long now) {
1376 return super.toDebugString(now) + ", editProperties"
1377 + ", accountType " + accountType;
1378 }
1379 }.bind();
1380 } finally {
1381 restoreCallingIdentity(identityToken);
1382 }
Fred Quintana60307342009-03-24 22:48:12 -07001383 }
1384
Fred Quintana33269202009-04-20 16:05:10 -07001385 private class GetAccountsByTypeAndFeatureSession extends Session {
1386 private final String[] mFeatures;
1387 private volatile Account[] mAccountsOfType = null;
1388 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1389 private volatile int mCurrentAccount = 0;
1390
Amith Yamasani04e0d262012-02-14 11:50:53 -08001391 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
1392 IAccountManagerResponse response, String type, String[] features) {
1393 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001394 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001395 mFeatures = features;
1396 }
1397
1398 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001399 synchronized (mAccounts.cacheLock) {
1400 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001401 }
Fred Quintana33269202009-04-20 16:05:10 -07001402 // check whether each account matches the requested features
1403 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1404 mCurrentAccount = 0;
1405
1406 checkAccount();
1407 }
1408
1409 public void checkAccount() {
1410 if (mCurrentAccount >= mAccountsOfType.length) {
1411 sendResult();
1412 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001413 }
Fred Quintana33269202009-04-20 16:05:10 -07001414
Fred Quintana29e94b82010-03-10 12:11:51 -08001415 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1416 if (accountAuthenticator == null) {
1417 // It is possible that the authenticator has died, which is indicated by
1418 // mAuthenticator being set to null. If this happens then just abort.
1419 // There is no need to send back a result or error in this case since
1420 // that already happened when mAuthenticator was cleared.
1421 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1422 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1423 + " connected to the authenticator, " + toDebugString());
1424 }
1425 return;
1426 }
Fred Quintana33269202009-04-20 16:05:10 -07001427 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001428 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001429 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001430 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001431 }
1432 }
1433
1434 public void onResult(Bundle result) {
1435 mNumResults++;
1436 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001437 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001438 return;
1439 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001440 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001441 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1442 }
1443 mCurrentAccount++;
1444 checkAccount();
1445 }
1446
1447 public void sendResult() {
1448 IAccountManagerResponse response = getResponseAndClose();
1449 if (response != null) {
1450 try {
1451 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1452 for (int i = 0; i < accounts.length; i++) {
1453 accounts[i] = mAccountsWithFeatures.get(i);
1454 }
Fred Quintana56285a62010-12-02 14:20:51 -08001455 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1456 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1457 + response);
1458 }
Fred Quintana33269202009-04-20 16:05:10 -07001459 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001460 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001461 response.onResult(result);
1462 } catch (RemoteException e) {
1463 // if the caller is dead then there is no one to care about remote exceptions
1464 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1465 Log.v(TAG, "failure while notifying response", e);
1466 }
1467 }
1468 }
1469 }
1470
1471
1472 protected String toDebugString(long now) {
1473 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1474 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1475 }
1476 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001477
Amith Yamasani04e0d262012-02-14 11:50:53 -08001478 /**
1479 * Returns the accounts for a specific user
1480 * @hide
1481 */
1482 public Account[] getAccounts(int userId) {
1483 checkReadAccountsPermission();
1484 UserAccounts accounts = getUserAccounts(userId);
1485 long identityToken = clearCallingIdentity();
1486 try {
1487 synchronized (accounts.cacheLock) {
1488 return getAccountsFromCacheLocked(accounts, null);
1489 }
1490 } finally {
1491 restoreCallingIdentity(identityToken);
1492 }
1493 }
1494
Amith Yamasanif29f2362012-04-05 18:29:52 -07001495 /**
1496 * Returns all the accounts qualified by user.
1497 * @hide
1498 */
1499 public AccountAndUser[] getAllAccounts() {
1500 ArrayList<AccountAndUser> allAccounts = new ArrayList<AccountAndUser>();
1501 List<UserInfo> users = getAllUsers();
1502 if (users == null) return new AccountAndUser[0];
1503
1504 synchronized(mUsers) {
1505 for (UserInfo user : users) {
1506 UserAccounts userAccounts = getUserAccounts(user.id);
1507 if (userAccounts == null) continue;
1508 synchronized (userAccounts.cacheLock) {
1509 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null);
1510 for (int a = 0; a < accounts.length; a++) {
1511 allAccounts.add(new AccountAndUser(accounts[a], user.id));
1512 }
1513 }
1514 }
1515 }
1516 AccountAndUser[] accountsArray = new AccountAndUser[allAccounts.size()];
1517 return allAccounts.toArray(accountsArray);
1518 }
1519
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001520 public Account[] getAccounts(String type) {
Fred Quintana56285a62010-12-02 14:20:51 -08001521 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1522 Log.v(TAG, "getAccounts: accountType " + type
1523 + ", caller's uid " + Binder.getCallingUid()
1524 + ", pid " + Binder.getCallingPid());
1525 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001526 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001527 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001528 long identityToken = clearCallingIdentity();
1529 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001530 synchronized (accounts.cacheLock) {
1531 return getAccountsFromCacheLocked(accounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001532 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001533 } finally {
1534 restoreCallingIdentity(identityToken);
1535 }
1536 }
1537
1538 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001539 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1541 Log.v(TAG, "getAccounts: accountType " + type
1542 + ", response " + response
1543 + ", features " + stringArrayToString(features)
1544 + ", caller's uid " + Binder.getCallingUid()
1545 + ", pid " + Binder.getCallingPid());
1546 }
Fred Quintana382601f2010-03-25 12:25:10 -07001547 if (response == null) throw new IllegalArgumentException("response is null");
1548 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001549 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001550 UserAccounts userAccounts = getUserAccountsForCaller();
Fred Quintana33269202009-04-20 16:05:10 -07001551 long identityToken = clearCallingIdentity();
1552 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001553 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001554 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001555 synchronized (userAccounts.cacheLock) {
1556 accounts = getAccountsFromCacheLocked(userAccounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001557 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001558 Bundle result = new Bundle();
1559 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1560 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001561 return;
1562 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001563 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001564 } finally {
1565 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001566 }
1567 }
1568
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001569 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001570 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001571 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001572 try {
1573 if (cursor.moveToNext()) {
1574 return cursor.getLong(0);
1575 }
1576 return -1;
1577 } finally {
1578 cursor.close();
1579 }
1580 }
1581
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001582 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001583 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1584 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1585 new String[]{key}, null, null, null);
1586 try {
1587 if (cursor.moveToNext()) {
1588 return cursor.getLong(0);
1589 }
1590 return -1;
1591 } finally {
1592 cursor.close();
1593 }
1594 }
1595
Fred Quintanaa698f422009-04-08 19:14:54 -07001596 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001597 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001598 IAccountManagerResponse mResponse;
1599 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001600 final boolean mExpectActivityLaunch;
1601 final long mCreationTime;
1602
Fred Quintana33269202009-04-20 16:05:10 -07001603 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001604 private int mNumRequestContinued = 0;
1605 private int mNumErrors = 0;
1606
Fred Quintana60307342009-03-24 22:48:12 -07001607
1608 IAccountAuthenticator mAuthenticator = null;
1609
Fred Quintana8570f742010-02-18 10:32:54 -08001610 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001611 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001612
Amith Yamasani04e0d262012-02-14 11:50:53 -08001613 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001614 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001615 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001616 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001617 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001618 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001619 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001620 mResponse = response;
1621 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001622 mExpectActivityLaunch = expectActivityLaunch;
1623 mCreationTime = SystemClock.elapsedRealtime();
1624 synchronized (mSessions) {
1625 mSessions.put(toString(), this);
1626 }
1627 try {
1628 response.asBinder().linkToDeath(this, 0 /* flags */);
1629 } catch (RemoteException e) {
1630 mResponse = null;
1631 binderDied();
1632 }
Fred Quintana60307342009-03-24 22:48:12 -07001633 }
1634
Fred Quintanaa698f422009-04-08 19:14:54 -07001635 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001636 if (mResponse == null) {
1637 // this session has already been closed
1638 return null;
1639 }
Fred Quintana60307342009-03-24 22:48:12 -07001640 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001641 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001642 return response;
1643 }
1644
Fred Quintanaa698f422009-04-08 19:14:54 -07001645 private void close() {
1646 synchronized (mSessions) {
1647 if (mSessions.remove(toString()) == null) {
1648 // the session was already closed, so bail out now
1649 return;
1650 }
1651 }
1652 if (mResponse != null) {
1653 // stop listening for response deaths
1654 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1655
1656 // clear this so that we don't accidentally send any further results
1657 mResponse = null;
1658 }
1659 cancelTimeout();
1660 unbind();
1661 }
1662
1663 public void binderDied() {
1664 mResponse = null;
1665 close();
1666 }
1667
1668 protected String toDebugString() {
1669 return toDebugString(SystemClock.elapsedRealtime());
1670 }
1671
1672 protected String toDebugString(long now) {
1673 return "Session: expectLaunch " + mExpectActivityLaunch
1674 + ", connected " + (mAuthenticator != null)
1675 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1676 + "/" + mNumErrors + ")"
1677 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1678 }
1679
Fred Quintana60307342009-03-24 22:48:12 -07001680 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001681 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1682 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1683 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001684 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001685 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001686 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001687 }
1688 }
1689
1690 private void unbind() {
1691 if (mAuthenticator != null) {
1692 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001693 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001694 }
1695 }
1696
1697 public void scheduleTimeout() {
1698 mMessageHandler.sendMessageDelayed(
1699 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1700 }
1701
1702 public void cancelTimeout() {
1703 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1704 }
1705
Fred Quintanab839afc2009-10-14 15:57:28 -07001706 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001707 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001708 try {
1709 run();
1710 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001711 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001712 "remote exception");
1713 }
Fred Quintana60307342009-03-24 22:48:12 -07001714 }
1715
Fred Quintanab839afc2009-10-14 15:57:28 -07001716 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001717 mAuthenticator = null;
1718 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001719 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001720 try {
1721 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1722 "disconnected");
1723 } catch (RemoteException e) {
1724 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1725 Log.v(TAG, "Session.onServiceDisconnected: "
1726 + "caught RemoteException while responding", e);
1727 }
1728 }
Fred Quintana60307342009-03-24 22:48:12 -07001729 }
1730 }
1731
Fred Quintanab839afc2009-10-14 15:57:28 -07001732 public abstract void run() throws RemoteException;
1733
Fred Quintana60307342009-03-24 22:48:12 -07001734 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001735 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001736 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001737 try {
1738 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1739 "timeout");
1740 } catch (RemoteException e) {
1741 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1742 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
1743 e);
1744 }
1745 }
Fred Quintana60307342009-03-24 22:48:12 -07001746 }
1747 }
1748
Fred Quintanaa698f422009-04-08 19:14:54 -07001749 public void onResult(Bundle result) {
1750 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001751 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1752 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1753 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001754 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1755 Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001756 cancelNotification(getSigninRequiredNotificationId(mAccounts, account));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001757 }
Fred Quintana60307342009-03-24 22:48:12 -07001758 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001759 IAccountManagerResponse response;
1760 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001761 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001762 response = mResponse;
1763 } else {
1764 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001765 }
Fred Quintana60307342009-03-24 22:48:12 -07001766 if (response != null) {
1767 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001768 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001769 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1770 Log.v(TAG, getClass().getSimpleName()
1771 + " calling onError() on response " + response);
1772 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001773 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001774 "null bundle returned");
1775 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001776 if (mStripAuthTokenFromResult) {
1777 result.remove(AccountManager.KEY_AUTHTOKEN);
1778 }
Fred Quintana56285a62010-12-02 14:20:51 -08001779 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1780 Log.v(TAG, getClass().getSimpleName()
1781 + " calling onResult() on response " + response);
1782 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001783 response.onResult(result);
1784 }
Fred Quintana60307342009-03-24 22:48:12 -07001785 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001786 // if the caller is dead then there is no one to care about remote exceptions
1787 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1788 Log.v(TAG, "failure while notifying response", e);
1789 }
Fred Quintana60307342009-03-24 22:48:12 -07001790 }
1791 }
1792 }
Fred Quintana60307342009-03-24 22:48:12 -07001793
Fred Quintanaa698f422009-04-08 19:14:54 -07001794 public void onRequestContinued() {
1795 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001796 }
1797
1798 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001799 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001800 IAccountManagerResponse response = getResponseAndClose();
1801 if (response != null) {
1802 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001803 Log.v(TAG, getClass().getSimpleName()
1804 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001805 }
1806 try {
1807 response.onError(errorCode, errorMessage);
1808 } catch (RemoteException e) {
1809 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1810 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1811 }
1812 }
1813 } else {
1814 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1815 Log.v(TAG, "Session.onError: already closed");
1816 }
Fred Quintana60307342009-03-24 22:48:12 -07001817 }
1818 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001819
1820 /**
1821 * find the component name for the authenticator and initiate a bind
1822 * if no authenticator or the bind fails then return false, otherwise return true
1823 */
1824 private boolean bindToAuthenticator(String authenticatorType) {
1825 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1826 mAuthenticatorCache.getServiceInfo(
1827 AuthenticatorDescription.newKey(authenticatorType));
1828 if (authenticatorInfo == null) {
1829 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1830 Log.v(TAG, "there is no authenticator for " + authenticatorType
1831 + ", bailing out");
1832 }
1833 return false;
1834 }
1835
1836 Intent intent = new Intent();
1837 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1838 intent.setComponent(authenticatorInfo.componentName);
1839 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1840 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1841 }
Amith Yamasani34daa752012-03-19 16:14:23 -07001842 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE, mAccounts.userId)) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001843 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1844 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1845 }
1846 return false;
1847 }
1848
1849
1850 return true;
1851 }
Fred Quintana60307342009-03-24 22:48:12 -07001852 }
1853
1854 private class MessageHandler extends Handler {
1855 MessageHandler(Looper looper) {
1856 super(looper);
1857 }
Costin Manolache3348f142009-09-29 18:58:36 -07001858
Fred Quintana60307342009-03-24 22:48:12 -07001859 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001860 switch (msg.what) {
1861 case MESSAGE_TIMED_OUT:
1862 Session session = (Session)msg.obj;
1863 session.onTimedOut();
1864 break;
1865
1866 default:
1867 throw new IllegalStateException("unhandled message: " + msg.what);
1868 }
1869 }
1870 }
1871
Amith Yamasani04e0d262012-02-14 11:50:53 -08001872 private static String getDatabaseName(int userId) {
1873 File systemDir = Environment.getSystemSecureDirectory();
1874 File databaseFile = new File(systemDir, "users/" + userId + "/" + DATABASE_NAME);
1875 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07001876 // Migrate old file, if it exists, to the new location.
1877 // Make sure the new file doesn't already exist. A dummy file could have been
1878 // accidentally created in the old location, causing the new one to become corrupted
1879 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08001880 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07001881 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07001882 // Check for use directory; create if it doesn't exist, else renameTo will fail
1883 File userDir = new File(systemDir, "users/" + userId);
1884 if (!userDir.exists()) {
1885 if (!userDir.mkdirs()) {
1886 throw new IllegalStateException("User dir cannot be created: " + userDir);
1887 }
1888 }
1889 if (!oldFile.renameTo(databaseFile)) {
1890 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
1891 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001892 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08001893 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001894 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08001895 }
1896
Amith Yamasani04e0d262012-02-14 11:50:53 -08001897 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001898
Amith Yamasani04e0d262012-02-14 11:50:53 -08001899 public DatabaseHelper(Context context, int userId) {
1900 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001901 }
1902
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001903 /**
1904 * This call needs to be made while the mCacheLock is held. The way to
1905 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
1906 * @param db The database.
1907 */
Fred Quintana60307342009-03-24 22:48:12 -07001908 @Override
1909 public void onCreate(SQLiteDatabase db) {
1910 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1911 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1912 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1913 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1914 + ACCOUNTS_PASSWORD + " TEXT, "
1915 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1916
1917 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1918 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1919 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1920 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1921 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1922 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1923
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001924 createGrantsTable(db);
1925
Fred Quintana60307342009-03-24 22:48:12 -07001926 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1927 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1928 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1929 + EXTRAS_KEY + " TEXT NOT NULL, "
1930 + EXTRAS_VALUE + " TEXT, "
1931 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1932
1933 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1934 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1935 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001936
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001937 createAccountsDeletionTrigger(db);
1938 }
1939
1940 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001941 db.execSQL(""
1942 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1943 + " BEGIN"
1944 + " DELETE FROM " + TABLE_AUTHTOKENS
1945 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1946 + " DELETE FROM " + TABLE_EXTRAS
1947 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001948 + " DELETE FROM " + TABLE_GRANTS
1949 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001950 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001951 }
1952
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001953 private void createGrantsTable(SQLiteDatabase db) {
1954 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1955 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1956 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1957 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1958 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1959 + "," + GRANTS_GRANTEE_UID + "))");
1960 }
1961
Fred Quintana60307342009-03-24 22:48:12 -07001962 @Override
1963 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001964 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001965
Fred Quintanaa698f422009-04-08 19:14:54 -07001966 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001967 // no longer need to do anything since the work is done
1968 // when upgrading from version 2
1969 oldVersion++;
1970 }
1971
1972 if (oldVersion == 2) {
1973 createGrantsTable(db);
1974 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1975 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001976 oldVersion++;
1977 }
Costin Manolache3348f142009-09-29 18:58:36 -07001978
1979 if (oldVersion == 3) {
1980 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1981 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1982 oldVersion++;
1983 }
Fred Quintana60307342009-03-24 22:48:12 -07001984 }
1985
1986 @Override
1987 public void onOpen(SQLiteDatabase db) {
1988 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1989 }
1990 }
1991
Fred Quintana60307342009-03-24 22:48:12 -07001992 public IBinder onBind(Intent intent) {
1993 return asBinder();
1994 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001995
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001996 /**
1997 * Searches array of arguments for the specified string
1998 * @param args array of argument strings
1999 * @param value value to search for
2000 * @return true if the value is contained in the array
2001 */
2002 private static boolean scanArgs(String[] args, String value) {
2003 if (args != null) {
2004 for (String arg : args) {
2005 if (value.equals(arg)) {
2006 return true;
2007 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002008 }
2009 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002010 return false;
2011 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002012
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002013 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002014 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2015 != PackageManager.PERMISSION_GRANTED) {
2016 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2017 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2018 + " without permission " + android.Manifest.permission.DUMP);
2019 return;
2020 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002021 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Kenny Root3abd75b2011-09-29 11:00:41 -07002022
Amith Yamasani04e0d262012-02-14 11:50:53 -08002023 fout = new IndentingPrintWriter(fout, " ");
2024 int size = mUsers.size();
2025 for (int i = 0; i < size; i++) {
2026 fout.println("User " + mUsers.keyAt(i) + ":");
2027 ((IndentingPrintWriter) fout).increaseIndent();
2028 dumpUser(mUsers.valueAt(i), fd, fout, args, isCheckinRequest);
2029 ((IndentingPrintWriter) fout).decreaseIndent();
2030 if (i < size - 1) {
2031 fout.println();
2032 }
2033 }
2034 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002035
Amith Yamasani04e0d262012-02-14 11:50:53 -08002036 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2037 String[] args, boolean isCheckinRequest) {
2038 synchronized (userAccounts.cacheLock) {
2039 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002040
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002041 if (isCheckinRequest) {
2042 // This is a checkin request. *Only* upload the account types and the count of each.
2043 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2044 null, null, ACCOUNTS_TYPE, null, null);
2045 try {
2046 while (cursor.moveToNext()) {
2047 // print type,count
2048 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2049 }
2050 } finally {
2051 if (cursor != null) {
2052 cursor.close();
2053 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002054 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002055 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002056 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002057 fout.println("Accounts: " + accounts.length);
2058 for (Account account : accounts) {
2059 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002060 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002061
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002062 fout.println();
2063 synchronized (mSessions) {
2064 final long now = SystemClock.elapsedRealtime();
2065 fout.println("Active Sessions: " + mSessions.size());
2066 for (Session session : mSessions.values()) {
2067 fout.println(" " + session.toDebugString(now));
2068 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002069 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002070
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002071 fout.println();
2072 mAuthenticatorCache.dump(fd, fout, args);
2073 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002074 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002075 }
2076
Amith Yamasani04e0d262012-02-14 11:50:53 -08002077 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
2078 Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002079 long identityToken = clearCallingIdentity();
2080 try {
2081 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2082 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2083 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002084
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002085 if (intent.getComponent() != null &&
2086 GrantCredentialsPermissionActivity.class.getName().equals(
2087 intent.getComponent().getClassName())) {
2088 createNoCredentialsPermissionNotification(account, intent);
2089 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002090 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002091 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002092 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2093 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07002094 final String notificationTitleFormat =
2095 mContext.getText(R.string.notification_title).toString();
2096 n.setLatestEventInfo(mContext,
2097 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002098 message, PendingIntent.getActivity(
2099 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -08002100 installNotification(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002101 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002102 } finally {
2103 restoreCallingIdentity(identityToken);
2104 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002105 }
2106
Fred Quintana56285a62010-12-02 14:20:51 -08002107 protected void installNotification(final int notificationId, final Notification n) {
2108 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
2109 .notify(notificationId, n);
2110 }
2111
2112 protected void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002113 long identityToken = clearCallingIdentity();
2114 try {
2115 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002116 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002117 } finally {
2118 restoreCallingIdentity(identityToken);
2119 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002120 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002121
Fred Quintanab38eb142010-02-24 13:40:54 -08002122 /** Succeeds if any of the specified permissions are granted. */
2123 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002124 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002125
2126 for (String perm : permissions) {
2127 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2128 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002129 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002130 }
2131 return;
2132 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002133 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002134
2135 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002136 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002137 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002138 }
2139
Fred Quintana7be59642009-08-24 18:29:25 -07002140 private boolean inSystemImage(int callerUid) {
Fred Quintana56285a62010-12-02 14:20:51 -08002141 String[] packages = mPackageManager.getPackagesForUid(callerUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002142 for (String name : packages) {
2143 try {
Fred Quintana56285a62010-12-02 14:20:51 -08002144 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
2145 if (packageInfo != null
2146 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002147 return true;
2148 }
2149 } catch (PackageManager.NameNotFoundException e) {
2150 return false;
2151 }
2152 }
2153 return false;
2154 }
2155
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002156 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002157 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002158 final boolean fromAuthenticator = account != null
2159 && hasAuthenticatorUid(account.type, callerUid);
2160 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002161 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002162 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2163 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002164 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002165 + ": is authenticator? " + fromAuthenticator
2166 + ", has explicit permission? " + hasExplicitGrants);
2167 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002168 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002169 }
2170
Fred Quintana1a231912009-10-15 11:31:30 -07002171 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002172 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
2173 mAuthenticatorCache.getAllServices()) {
2174 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002175 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002176 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002177 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002178 }
2179 }
2180 return false;
2181 }
2182
Amith Yamasani04e0d262012-02-14 11:50:53 -08002183 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2184 int callerUid) {
2185 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002186 return true;
2187 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002188 UserAccounts accounts = getUserAccountsForCaller();
2189 synchronized (accounts.cacheLock) {
2190 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2191 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002192 account.name, account.type};
2193 final boolean permissionGranted =
2194 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2195 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2196 // TODO: Skip this check when running automated tests. Replace this
2197 // with a more general solution.
2198 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002199 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002200 + " but ignoring since device is in test harness.");
2201 return true;
2202 }
2203 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002204 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002205 }
2206
2207 private void checkCallingUidAgainstAuthenticator(Account account) {
2208 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002209 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002210 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2211 Log.w(TAG, msg);
2212 throw new SecurityException(msg);
2213 }
2214 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2215 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2216 }
2217 }
2218
2219 private void checkAuthenticateAccountsPermission(Account account) {
2220 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2221 checkCallingUidAgainstAuthenticator(account);
2222 }
2223
2224 private void checkReadAccountsPermission() {
2225 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2226 }
2227
2228 private void checkManageAccountsPermission() {
2229 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2230 }
2231
Fred Quintanab38eb142010-02-24 13:40:54 -08002232 private void checkManageAccountsOrUseCredentialsPermissions() {
2233 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2234 Manifest.permission.USE_CREDENTIALS);
2235 }
2236
Fred Quintanad9640ec2012-05-23 12:37:00 -07002237 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2238 throws RemoteException {
2239 final int callingUid = getCallingUid();
2240
2241 if (callingUid != android.os.Process.SYSTEM_UID) {
2242 throw new SecurityException();
2243 }
2244
2245 if (value) {
2246 grantAppPermission(account, authTokenType, uid);
2247 } else {
2248 revokeAppPermission(account, authTokenType, uid);
2249 }
2250 }
2251
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002252 /**
2253 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2254 * <p>
2255 * Although this is public it can only be accessed via the AccountManagerService object
2256 * which is in the system. This means we don't need to protect it with permissions.
2257 * @hide
2258 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002259 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002260 if (account == null || authTokenType == null) {
2261 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002262 return;
2263 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002264 UserAccounts accounts = getUserAccounts(UserId.getUserId(uid));
2265 synchronized (accounts.cacheLock) {
2266 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002267 db.beginTransaction();
2268 try {
2269 long accountId = getAccountIdLocked(db, account);
2270 if (accountId >= 0) {
2271 ContentValues values = new ContentValues();
2272 values.put(GRANTS_ACCOUNTS_ID, accountId);
2273 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2274 values.put(GRANTS_GRANTEE_UID, uid);
2275 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2276 db.setTransactionSuccessful();
2277 }
2278 } finally {
2279 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002280 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002281 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002282 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002283 }
2284
2285 /**
2286 * Don't allow callers with the given uid permission to get credentials for
2287 * account/authTokenType.
2288 * <p>
2289 * Although this is public it can only be accessed via the AccountManagerService object
2290 * which is in the system. This means we don't need to protect it with permissions.
2291 * @hide
2292 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002293 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002294 if (account == null || authTokenType == null) {
2295 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002296 return;
2297 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002298 UserAccounts accounts = getUserAccounts(UserId.getUserId(uid));
2299 synchronized (accounts.cacheLock) {
2300 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002301 db.beginTransaction();
2302 try {
2303 long accountId = getAccountIdLocked(db, account);
2304 if (accountId >= 0) {
2305 db.delete(TABLE_GRANTS,
2306 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2307 + GRANTS_GRANTEE_UID + "=?",
2308 new String[]{String.valueOf(accountId), authTokenType,
2309 String.valueOf(uid)});
2310 db.setTransactionSuccessful();
2311 }
2312 } finally {
2313 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002314 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002315 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002316 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002317 }
Fred Quintana56285a62010-12-02 14:20:51 -08002318
2319 static final private String stringArrayToString(String[] value) {
2320 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2321 }
2322
Amith Yamasani04e0d262012-02-14 11:50:53 -08002323 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2324 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002325 if (oldAccountsForType != null) {
2326 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2327 for (Account curAccount : oldAccountsForType) {
2328 if (!curAccount.equals(account)) {
2329 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002330 }
2331 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002332 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002333 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002334 } else {
2335 Account[] newAccountsForType = new Account[newAccountsList.size()];
2336 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002337 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002338 }
Fred Quintana56285a62010-12-02 14:20:51 -08002339 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002340 accounts.userDataCache.remove(account);
2341 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002342 }
2343
2344 /**
2345 * This assumes that the caller has already checked that the account is not already present.
2346 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002347 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2348 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002349 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2350 Account[] newAccountsForType = new Account[oldLength + 1];
2351 if (accountsForType != null) {
2352 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002353 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002354 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002355 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002356 }
2357
Amith Yamasani04e0d262012-02-14 11:50:53 -08002358 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002359 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002360 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002361 if (accounts == null) {
2362 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002363 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002364 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002365 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002366 } else {
2367 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002368 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002369 totalLength += accounts.length;
2370 }
2371 if (totalLength == 0) {
2372 return EMPTY_ACCOUNT_ARRAY;
2373 }
2374 Account[] accounts = new Account[totalLength];
2375 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002376 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002377 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2378 accountsOfType.length);
2379 totalLength += accountsOfType.length;
2380 }
2381 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002382 }
2383 }
2384
Amith Yamasani04e0d262012-02-14 11:50:53 -08002385 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2386 Account account, String key, String value) {
2387 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002388 if (userDataForAccount == null) {
2389 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002390 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002391 }
2392 if (value == null) {
2393 userDataForAccount.remove(key);
2394 } else {
2395 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002396 }
2397 }
2398
Amith Yamasani04e0d262012-02-14 11:50:53 -08002399 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2400 Account account, String key, String value) {
2401 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002402 if (authTokensForAccount == null) {
2403 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002404 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002405 }
2406 if (value == null) {
2407 authTokensForAccount.remove(key);
2408 } else {
2409 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002410 }
2411 }
2412
Amith Yamasani04e0d262012-02-14 11:50:53 -08002413 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2414 String authTokenType) {
2415 synchronized (accounts.cacheLock) {
2416 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002417 if (authTokensForAccount == null) {
2418 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002419 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002420 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002421 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002422 }
2423 return authTokensForAccount.get(authTokenType);
2424 }
2425 }
2426
Amith Yamasani04e0d262012-02-14 11:50:53 -08002427 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2428 synchronized (accounts.cacheLock) {
2429 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002430 if (userDataForAccount == null) {
2431 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002432 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002433 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002434 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002435 }
2436 return userDataForAccount.get(key);
2437 }
2438 }
2439
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002440 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2441 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002442 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002443 Cursor cursor = db.query(TABLE_EXTRAS,
2444 COLUMNS_EXTRAS_KEY_AND_VALUE,
2445 SELECTION_USERDATA_BY_ACCOUNT,
2446 new String[]{account.name, account.type},
2447 null, null, null);
2448 try {
2449 while (cursor.moveToNext()) {
2450 final String tmpkey = cursor.getString(0);
2451 final String value = cursor.getString(1);
2452 userDataForAccount.put(tmpkey, value);
2453 }
2454 } finally {
2455 cursor.close();
2456 }
2457 return userDataForAccount;
2458 }
2459
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002460 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2461 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002462 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002463 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2464 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2465 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2466 new String[]{account.name, account.type},
2467 null, null, null);
2468 try {
2469 while (cursor.moveToNext()) {
2470 final String type = cursor.getString(0);
2471 final String authToken = cursor.getString(1);
2472 authTokensForAccount.put(type, authToken);
2473 }
2474 } finally {
2475 cursor.close();
2476 }
2477 return authTokensForAccount;
2478 }
Fred Quintana60307342009-03-24 22:48:12 -07002479}