blob: 197c1bd109dfbf2df4988713d4906e24b828bfb6 [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
Costin Manolache5f383ad92010-12-02 16:44:46 -0800988 void getAuthTokenLabel(final IAccountManagerResponse response,
Amith Yamasani04e0d262012-02-14 11:50:53 -0800989 final Account account,
990 final String authTokenType, int uid) {
Costin Manolache5f383ad92010-12-02 16:44:46 -0800991 if (account == null) throw new IllegalArgumentException("account is null");
992 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
993
994 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800995 UserAccounts accounts = getUserAccounts(UserId.getUserId(uid));
Costin Manolache5f383ad92010-12-02 16:44:46 -0800996 long identityToken = clearCallingIdentity();
997 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800998 new Session(accounts, response, account.type, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -0800999 false /* stripAuthTokenFromResult */) {
1000 protected String toDebugString(long now) {
1001 return super.toDebugString(now) + ", getAuthTokenLabel"
1002 + ", " + account
1003 + ", authTokenType " + authTokenType;
1004 }
1005
1006 public void run() throws RemoteException {
1007 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1008 }
1009
1010 public void onResult(Bundle result) {
1011 if (result != null) {
1012 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1013 Bundle bundle = new Bundle();
1014 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1015 super.onResult(bundle);
1016 return;
1017 } else {
1018 super.onResult(result);
1019 }
1020 }
1021 }.bind();
1022 } finally {
1023 restoreCallingIdentity(identityToken);
1024 }
1025 }
1026
Fred Quintanaa698f422009-04-08 19:14:54 -07001027 public void getAuthToken(IAccountManagerResponse response, final Account account,
1028 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001029 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001030 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1031 Log.v(TAG, "getAuthToken: " + account
1032 + ", response " + response
1033 + ", authTokenType " + authTokenType
1034 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1035 + ", expectActivityLaunch " + expectActivityLaunch
1036 + ", caller's uid " + Binder.getCallingUid()
1037 + ", pid " + Binder.getCallingPid());
1038 }
Fred Quintana382601f2010-03-25 12:25:10 -07001039 if (response == null) throw new IllegalArgumentException("response is null");
1040 if (account == null) throw new IllegalArgumentException("account is null");
1041 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001042 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001043 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolachea40c6302010-12-13 14:50:45 -08001044 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1045 mAuthenticatorCache.getServiceInfo(
1046 AuthenticatorDescription.newKey(account.type));
1047 final boolean customTokens =
1048 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1049
1050 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001051 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001052 final boolean permissionGranted = customTokens ||
1053 permissionIsGranted(account, authTokenType, callerUid);
1054
Costin Manolachec6684f92011-01-14 11:25:39 -08001055 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1056 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001057 // let authenticator know the identity of the caller
1058 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1059 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1060 if (notifyOnAuthFailure) {
1061 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001062 }
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001063
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001064 long identityToken = clearCallingIdentity();
1065 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001066 // if the caller has permission, do the peek. otherwise go the more expensive
1067 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001068 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001069 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001070 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001071 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001072 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1073 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1074 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001075 onResult(response, result);
1076 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001077 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001078 }
1079
Amith Yamasani04e0d262012-02-14 11:50:53 -08001080 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001081 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001082 protected String toDebugString(long now) {
1083 if (loginOptions != null) loginOptions.keySet();
1084 return super.toDebugString(now) + ", getAuthToken"
1085 + ", " + account
1086 + ", authTokenType " + authTokenType
1087 + ", loginOptions " + loginOptions
1088 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1089 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001090
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001091 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001092 // If the caller doesn't have permission then create and return the
1093 // "grant permission" intent instead of the "getAuthToken" intent.
1094 if (!permissionGranted) {
1095 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1096 } else {
1097 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1098 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001099 }
1100
1101 public void onResult(Bundle result) {
1102 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001103 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001104 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1105 new AccountAuthenticatorResponse(this),
1106 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001107 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001108 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001109 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001110 onResult(bundle);
1111 return;
1112 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001113 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001114 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001115 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1116 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001117 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001118 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001119 "the type and name should not be empty");
1120 return;
1121 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001122 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001123 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001124 authTokenType, authToken);
1125 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001126 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001127
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001128 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001129 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001130 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001131 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001132 intent);
1133 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001134 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001135 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001136 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001137 }.bind();
1138 } finally {
1139 restoreCallingIdentity(identityToken);
1140 }
Fred Quintana60307342009-03-24 22:48:12 -07001141 }
1142
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001143 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
1144 int uid = intent.getIntExtra(
1145 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1146 String authTokenType = intent.getStringExtra(
1147 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1148 String authTokenLabel = intent.getStringExtra(
1149 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1150
1151 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1152 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001153 final String titleAndSubtitle =
1154 mContext.getString(R.string.permission_request_notification_with_subtitle,
1155 account.name);
1156 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001157 String title = titleAndSubtitle;
1158 String subtitle = "";
1159 if (index > 0) {
1160 title = titleAndSubtitle.substring(0, index);
1161 subtitle = titleAndSubtitle.substring(index + 1);
1162 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001163 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -07001164 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001165 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -08001166 installNotification(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001167 }
1168
Costin Manolache5f383ad92010-12-02 16:44:46 -08001169 String getAccountLabel(String accountType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001170 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
Costin Manolache5f383ad92010-12-02 16:44:46 -08001171 mAuthenticatorCache.getServiceInfo(
1172 AuthenticatorDescription.newKey(accountType));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001173 if (serviceInfo == null) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001174 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001175 }
1176
1177 final Context authContext;
1178 try {
1179 authContext = mContext.createPackageContext(
Costin Manolache5f383ad92010-12-02 16:44:46 -08001180 serviceInfo.type.packageName, 0);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001181 } catch (PackageManager.NameNotFoundException e) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001182 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001183 }
Brian Carlstrom46703b02011-04-06 15:41:29 -07001184 try {
1185 return authContext.getString(serviceInfo.type.labelId);
1186 } catch (Resources.NotFoundException e) {
1187 throw new IllegalArgumentException("unknown account type: " + accountType);
1188 }
Costin Manolache5f383ad92010-12-02 16:44:46 -08001189 }
1190
1191 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1192 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001193
1194 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001195 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001196 // Since it was set in Eclair+ we can't change it without breaking apps using
1197 // the intent from a non-Activity context.
1198 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001199 intent.addCategory(
1200 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001201
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001202 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001203 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1204 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001205 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001206
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001207 return intent;
1208 }
1209
1210 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1211 int uid) {
1212 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001213 UserAccounts accounts = getUserAccounts(UserId.getUserId(uid));
1214 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001215 final Pair<Pair<Account, String>, Integer> key =
1216 new Pair<Pair<Account, String>, Integer>(
1217 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001218 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001219 if (id == null) {
1220 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001221 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001222 }
1223 }
1224 return id;
1225 }
1226
Amith Yamasani04e0d262012-02-14 11:50:53 -08001227 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001228 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001229 synchronized (accounts.signinRequiredNotificationIds) {
1230 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001231 if (id == null) {
1232 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001233 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001234 }
1235 }
1236 return id;
1237 }
1238
Fred Quintana33269202009-04-20 16:05:10 -07001239 public void addAcount(final IAccountManagerResponse response, final String accountType,
1240 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001241 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001242 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1243 Log.v(TAG, "addAccount: accountType " + accountType
1244 + ", response " + response
1245 + ", authTokenType " + authTokenType
1246 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1247 + ", expectActivityLaunch " + expectActivityLaunch
1248 + ", caller's uid " + Binder.getCallingUid()
1249 + ", pid " + Binder.getCallingPid());
1250 }
Fred Quintana382601f2010-03-25 12:25:10 -07001251 if (response == null) throw new IllegalArgumentException("response is null");
1252 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001253 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001254
Amith Yamasani04e0d262012-02-14 11:50:53 -08001255 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001256 final int pid = Binder.getCallingPid();
1257 final int uid = Binder.getCallingUid();
1258 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1259 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1260 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1261
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001262 long identityToken = clearCallingIdentity();
1263 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001264 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001265 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001266 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001267 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001268 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001269 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001270
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001271 protected String toDebugString(long now) {
1272 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001273 + ", accountType " + accountType
1274 + ", requiredFeatures "
1275 + (requiredFeatures != null
1276 ? TextUtils.join(",", requiredFeatures)
1277 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001278 }
1279 }.bind();
1280 } finally {
1281 restoreCallingIdentity(identityToken);
1282 }
Fred Quintana60307342009-03-24 22:48:12 -07001283 }
1284
Fred Quintanaa698f422009-04-08 19:14:54 -07001285 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001286 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001287 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1288 Log.v(TAG, "confirmCredentials: " + account
1289 + ", response " + response
1290 + ", expectActivityLaunch " + expectActivityLaunch
1291 + ", caller's uid " + Binder.getCallingUid()
1292 + ", pid " + Binder.getCallingPid());
1293 }
Fred Quintana382601f2010-03-25 12:25:10 -07001294 if (response == null) throw new IllegalArgumentException("response is null");
1295 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001296 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001297 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001298 long identityToken = clearCallingIdentity();
1299 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001300 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001301 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001302 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001303 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001304 }
1305 protected String toDebugString(long now) {
1306 return super.toDebugString(now) + ", confirmCredentials"
1307 + ", " + account;
1308 }
1309 }.bind();
1310 } finally {
1311 restoreCallingIdentity(identityToken);
1312 }
Fred Quintana60307342009-03-24 22:48:12 -07001313 }
1314
Fred Quintanaa698f422009-04-08 19:14:54 -07001315 public void updateCredentials(IAccountManagerResponse response, final Account account,
1316 final String authTokenType, final boolean expectActivityLaunch,
1317 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001318 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1319 Log.v(TAG, "updateCredentials: " + account
1320 + ", response " + response
1321 + ", authTokenType " + authTokenType
1322 + ", expectActivityLaunch " + expectActivityLaunch
1323 + ", caller's uid " + Binder.getCallingUid()
1324 + ", pid " + Binder.getCallingPid());
1325 }
Fred Quintana382601f2010-03-25 12:25:10 -07001326 if (response == null) throw new IllegalArgumentException("response is null");
1327 if (account == null) throw new IllegalArgumentException("account is null");
1328 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001329 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001330 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001331 long identityToken = clearCallingIdentity();
1332 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001333 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001334 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001335 public void run() throws RemoteException {
1336 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1337 }
1338 protected String toDebugString(long now) {
1339 if (loginOptions != null) loginOptions.keySet();
1340 return super.toDebugString(now) + ", updateCredentials"
1341 + ", " + account
1342 + ", authTokenType " + authTokenType
1343 + ", loginOptions " + loginOptions;
1344 }
1345 }.bind();
1346 } finally {
1347 restoreCallingIdentity(identityToken);
1348 }
Fred Quintana60307342009-03-24 22:48:12 -07001349 }
1350
Fred Quintanaa698f422009-04-08 19:14:54 -07001351 public void editProperties(IAccountManagerResponse response, final String accountType,
1352 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001353 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1354 Log.v(TAG, "editProperties: accountType " + accountType
1355 + ", response " + response
1356 + ", expectActivityLaunch " + expectActivityLaunch
1357 + ", caller's uid " + Binder.getCallingUid()
1358 + ", pid " + Binder.getCallingPid());
1359 }
Fred Quintana382601f2010-03-25 12:25:10 -07001360 if (response == null) throw new IllegalArgumentException("response is null");
1361 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001362 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001363 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001364 long identityToken = clearCallingIdentity();
1365 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001366 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001367 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001368 public void run() throws RemoteException {
1369 mAuthenticator.editProperties(this, mAccountType);
1370 }
1371 protected String toDebugString(long now) {
1372 return super.toDebugString(now) + ", editProperties"
1373 + ", accountType " + accountType;
1374 }
1375 }.bind();
1376 } finally {
1377 restoreCallingIdentity(identityToken);
1378 }
Fred Quintana60307342009-03-24 22:48:12 -07001379 }
1380
Fred Quintana33269202009-04-20 16:05:10 -07001381 private class GetAccountsByTypeAndFeatureSession extends Session {
1382 private final String[] mFeatures;
1383 private volatile Account[] mAccountsOfType = null;
1384 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1385 private volatile int mCurrentAccount = 0;
1386
Amith Yamasani04e0d262012-02-14 11:50:53 -08001387 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
1388 IAccountManagerResponse response, String type, String[] features) {
1389 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001390 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001391 mFeatures = features;
1392 }
1393
1394 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001395 synchronized (mAccounts.cacheLock) {
1396 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001397 }
Fred Quintana33269202009-04-20 16:05:10 -07001398 // check whether each account matches the requested features
1399 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1400 mCurrentAccount = 0;
1401
1402 checkAccount();
1403 }
1404
1405 public void checkAccount() {
1406 if (mCurrentAccount >= mAccountsOfType.length) {
1407 sendResult();
1408 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001409 }
Fred Quintana33269202009-04-20 16:05:10 -07001410
Fred Quintana29e94b82010-03-10 12:11:51 -08001411 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1412 if (accountAuthenticator == null) {
1413 // It is possible that the authenticator has died, which is indicated by
1414 // mAuthenticator being set to null. If this happens then just abort.
1415 // There is no need to send back a result or error in this case since
1416 // that already happened when mAuthenticator was cleared.
1417 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1418 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1419 + " connected to the authenticator, " + toDebugString());
1420 }
1421 return;
1422 }
Fred Quintana33269202009-04-20 16:05:10 -07001423 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001424 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001425 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001426 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001427 }
1428 }
1429
1430 public void onResult(Bundle result) {
1431 mNumResults++;
1432 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001433 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001434 return;
1435 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001436 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001437 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1438 }
1439 mCurrentAccount++;
1440 checkAccount();
1441 }
1442
1443 public void sendResult() {
1444 IAccountManagerResponse response = getResponseAndClose();
1445 if (response != null) {
1446 try {
1447 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1448 for (int i = 0; i < accounts.length; i++) {
1449 accounts[i] = mAccountsWithFeatures.get(i);
1450 }
Fred Quintana56285a62010-12-02 14:20:51 -08001451 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1452 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1453 + response);
1454 }
Fred Quintana33269202009-04-20 16:05:10 -07001455 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001456 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001457 response.onResult(result);
1458 } catch (RemoteException e) {
1459 // if the caller is dead then there is no one to care about remote exceptions
1460 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1461 Log.v(TAG, "failure while notifying response", e);
1462 }
1463 }
1464 }
1465 }
1466
1467
1468 protected String toDebugString(long now) {
1469 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1470 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1471 }
1472 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001473
Amith Yamasani04e0d262012-02-14 11:50:53 -08001474 /**
1475 * Returns the accounts for a specific user
1476 * @hide
1477 */
1478 public Account[] getAccounts(int userId) {
1479 checkReadAccountsPermission();
1480 UserAccounts accounts = getUserAccounts(userId);
1481 long identityToken = clearCallingIdentity();
1482 try {
1483 synchronized (accounts.cacheLock) {
1484 return getAccountsFromCacheLocked(accounts, null);
1485 }
1486 } finally {
1487 restoreCallingIdentity(identityToken);
1488 }
1489 }
1490
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001491 public Account[] getAccounts(String type) {
Fred Quintana56285a62010-12-02 14:20:51 -08001492 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1493 Log.v(TAG, "getAccounts: accountType " + type
1494 + ", caller's uid " + Binder.getCallingUid()
1495 + ", pid " + Binder.getCallingPid());
1496 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001497 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001498 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001499 long identityToken = clearCallingIdentity();
1500 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001501 synchronized (accounts.cacheLock) {
1502 return getAccountsFromCacheLocked(accounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001503 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001504 } finally {
1505 restoreCallingIdentity(identityToken);
1506 }
1507 }
1508
1509 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001510 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001511 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1512 Log.v(TAG, "getAccounts: accountType " + type
1513 + ", response " + response
1514 + ", features " + stringArrayToString(features)
1515 + ", caller's uid " + Binder.getCallingUid()
1516 + ", pid " + Binder.getCallingPid());
1517 }
Fred Quintana382601f2010-03-25 12:25:10 -07001518 if (response == null) throw new IllegalArgumentException("response is null");
1519 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001520 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001521 UserAccounts userAccounts = getUserAccountsForCaller();
Fred Quintana33269202009-04-20 16:05:10 -07001522 long identityToken = clearCallingIdentity();
1523 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001524 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001525 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001526 synchronized (userAccounts.cacheLock) {
1527 accounts = getAccountsFromCacheLocked(userAccounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001528 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001529 Bundle result = new Bundle();
1530 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1531 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001532 return;
1533 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001534 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001535 } finally {
1536 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001537 }
1538 }
1539
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001540 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001541 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001542 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001543 try {
1544 if (cursor.moveToNext()) {
1545 return cursor.getLong(0);
1546 }
1547 return -1;
1548 } finally {
1549 cursor.close();
1550 }
1551 }
1552
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001553 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001554 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1555 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1556 new String[]{key}, null, null, null);
1557 try {
1558 if (cursor.moveToNext()) {
1559 return cursor.getLong(0);
1560 }
1561 return -1;
1562 } finally {
1563 cursor.close();
1564 }
1565 }
1566
Fred Quintanaa698f422009-04-08 19:14:54 -07001567 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001568 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001569 IAccountManagerResponse mResponse;
1570 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001571 final boolean mExpectActivityLaunch;
1572 final long mCreationTime;
1573
Fred Quintana33269202009-04-20 16:05:10 -07001574 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001575 private int mNumRequestContinued = 0;
1576 private int mNumErrors = 0;
1577
Fred Quintana60307342009-03-24 22:48:12 -07001578
1579 IAccountAuthenticator mAuthenticator = null;
1580
Fred Quintana8570f742010-02-18 10:32:54 -08001581 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001582 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001583
Amith Yamasani04e0d262012-02-14 11:50:53 -08001584 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001585 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001586 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001587 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001588 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001589 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001590 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001591 mResponse = response;
1592 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001593 mExpectActivityLaunch = expectActivityLaunch;
1594 mCreationTime = SystemClock.elapsedRealtime();
1595 synchronized (mSessions) {
1596 mSessions.put(toString(), this);
1597 }
1598 try {
1599 response.asBinder().linkToDeath(this, 0 /* flags */);
1600 } catch (RemoteException e) {
1601 mResponse = null;
1602 binderDied();
1603 }
Fred Quintana60307342009-03-24 22:48:12 -07001604 }
1605
Fred Quintanaa698f422009-04-08 19:14:54 -07001606 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001607 if (mResponse == null) {
1608 // this session has already been closed
1609 return null;
1610 }
Fred Quintana60307342009-03-24 22:48:12 -07001611 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001612 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001613 return response;
1614 }
1615
Fred Quintanaa698f422009-04-08 19:14:54 -07001616 private void close() {
1617 synchronized (mSessions) {
1618 if (mSessions.remove(toString()) == null) {
1619 // the session was already closed, so bail out now
1620 return;
1621 }
1622 }
1623 if (mResponse != null) {
1624 // stop listening for response deaths
1625 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1626
1627 // clear this so that we don't accidentally send any further results
1628 mResponse = null;
1629 }
1630 cancelTimeout();
1631 unbind();
1632 }
1633
1634 public void binderDied() {
1635 mResponse = null;
1636 close();
1637 }
1638
1639 protected String toDebugString() {
1640 return toDebugString(SystemClock.elapsedRealtime());
1641 }
1642
1643 protected String toDebugString(long now) {
1644 return "Session: expectLaunch " + mExpectActivityLaunch
1645 + ", connected " + (mAuthenticator != null)
1646 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1647 + "/" + mNumErrors + ")"
1648 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1649 }
1650
Fred Quintana60307342009-03-24 22:48:12 -07001651 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001652 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1653 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1654 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001655 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001656 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001657 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001658 }
1659 }
1660
1661 private void unbind() {
1662 if (mAuthenticator != null) {
1663 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001664 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001665 }
1666 }
1667
1668 public void scheduleTimeout() {
1669 mMessageHandler.sendMessageDelayed(
1670 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1671 }
1672
1673 public void cancelTimeout() {
1674 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1675 }
1676
Fred Quintanab839afc2009-10-14 15:57:28 -07001677 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001678 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001679 try {
1680 run();
1681 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001682 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001683 "remote exception");
1684 }
Fred Quintana60307342009-03-24 22:48:12 -07001685 }
1686
Fred Quintanab839afc2009-10-14 15:57:28 -07001687 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001688 mAuthenticator = null;
1689 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001690 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001691 try {
1692 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1693 "disconnected");
1694 } catch (RemoteException e) {
1695 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1696 Log.v(TAG, "Session.onServiceDisconnected: "
1697 + "caught RemoteException while responding", e);
1698 }
1699 }
Fred Quintana60307342009-03-24 22:48:12 -07001700 }
1701 }
1702
Fred Quintanab839afc2009-10-14 15:57:28 -07001703 public abstract void run() throws RemoteException;
1704
Fred Quintana60307342009-03-24 22:48:12 -07001705 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001706 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001707 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001708 try {
1709 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1710 "timeout");
1711 } catch (RemoteException e) {
1712 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1713 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
1714 e);
1715 }
1716 }
Fred Quintana60307342009-03-24 22:48:12 -07001717 }
1718 }
1719
Fred Quintanaa698f422009-04-08 19:14:54 -07001720 public void onResult(Bundle result) {
1721 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001722 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1723 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1724 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001725 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1726 Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001727 cancelNotification(getSigninRequiredNotificationId(mAccounts, account));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001728 }
Fred Quintana60307342009-03-24 22:48:12 -07001729 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001730 IAccountManagerResponse response;
1731 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001732 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001733 response = mResponse;
1734 } else {
1735 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001736 }
Fred Quintana60307342009-03-24 22:48:12 -07001737 if (response != null) {
1738 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001739 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001740 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1741 Log.v(TAG, getClass().getSimpleName()
1742 + " calling onError() on response " + response);
1743 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001744 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001745 "null bundle returned");
1746 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001747 if (mStripAuthTokenFromResult) {
1748 result.remove(AccountManager.KEY_AUTHTOKEN);
1749 }
Fred Quintana56285a62010-12-02 14:20:51 -08001750 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1751 Log.v(TAG, getClass().getSimpleName()
1752 + " calling onResult() on response " + response);
1753 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001754 response.onResult(result);
1755 }
Fred Quintana60307342009-03-24 22:48:12 -07001756 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001757 // if the caller is dead then there is no one to care about remote exceptions
1758 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1759 Log.v(TAG, "failure while notifying response", e);
1760 }
Fred Quintana60307342009-03-24 22:48:12 -07001761 }
1762 }
1763 }
Fred Quintana60307342009-03-24 22:48:12 -07001764
Fred Quintanaa698f422009-04-08 19:14:54 -07001765 public void onRequestContinued() {
1766 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001767 }
1768
1769 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001770 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001771 IAccountManagerResponse response = getResponseAndClose();
1772 if (response != null) {
1773 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001774 Log.v(TAG, getClass().getSimpleName()
1775 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001776 }
1777 try {
1778 response.onError(errorCode, errorMessage);
1779 } catch (RemoteException e) {
1780 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1781 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1782 }
1783 }
1784 } else {
1785 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1786 Log.v(TAG, "Session.onError: already closed");
1787 }
Fred Quintana60307342009-03-24 22:48:12 -07001788 }
1789 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001790
1791 /**
1792 * find the component name for the authenticator and initiate a bind
1793 * if no authenticator or the bind fails then return false, otherwise return true
1794 */
1795 private boolean bindToAuthenticator(String authenticatorType) {
1796 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1797 mAuthenticatorCache.getServiceInfo(
1798 AuthenticatorDescription.newKey(authenticatorType));
1799 if (authenticatorInfo == null) {
1800 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1801 Log.v(TAG, "there is no authenticator for " + authenticatorType
1802 + ", bailing out");
1803 }
1804 return false;
1805 }
1806
1807 Intent intent = new Intent();
1808 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1809 intent.setComponent(authenticatorInfo.componentName);
1810 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1811 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1812 }
Amith Yamasani34daa752012-03-19 16:14:23 -07001813 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE, mAccounts.userId)) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001814 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1815 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1816 }
1817 return false;
1818 }
1819
1820
1821 return true;
1822 }
Fred Quintana60307342009-03-24 22:48:12 -07001823 }
1824
1825 private class MessageHandler extends Handler {
1826 MessageHandler(Looper looper) {
1827 super(looper);
1828 }
Costin Manolache3348f142009-09-29 18:58:36 -07001829
Fred Quintana60307342009-03-24 22:48:12 -07001830 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001831 switch (msg.what) {
1832 case MESSAGE_TIMED_OUT:
1833 Session session = (Session)msg.obj;
1834 session.onTimedOut();
1835 break;
1836
1837 default:
1838 throw new IllegalStateException("unhandled message: " + msg.what);
1839 }
1840 }
1841 }
1842
Amith Yamasani04e0d262012-02-14 11:50:53 -08001843 private static String getDatabaseName(int userId) {
1844 File systemDir = Environment.getSystemSecureDirectory();
1845 File databaseFile = new File(systemDir, "users/" + userId + "/" + DATABASE_NAME);
1846 if (userId == 0) {
1847 // Migrate old file, if it exists, to the new location
1848 File oldFile = new File(systemDir, DATABASE_NAME);
1849 if (oldFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07001850 // Check for use directory; create if it doesn't exist, else renameTo will fail
1851 File userDir = new File(systemDir, "users/" + userId);
1852 if (!userDir.exists()) {
1853 if (!userDir.mkdirs()) {
1854 throw new IllegalStateException("User dir cannot be created: " + userDir);
1855 }
1856 }
1857 if (!oldFile.renameTo(databaseFile)) {
1858 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
1859 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001860 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08001861 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001862 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08001863 }
1864
Amith Yamasani04e0d262012-02-14 11:50:53 -08001865 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001866
Amith Yamasani04e0d262012-02-14 11:50:53 -08001867 public DatabaseHelper(Context context, int userId) {
1868 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001869 }
1870
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001871 /**
1872 * This call needs to be made while the mCacheLock is held. The way to
1873 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
1874 * @param db The database.
1875 */
Fred Quintana60307342009-03-24 22:48:12 -07001876 @Override
1877 public void onCreate(SQLiteDatabase db) {
1878 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1879 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1880 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1881 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1882 + ACCOUNTS_PASSWORD + " TEXT, "
1883 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1884
1885 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1886 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1887 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1888 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1889 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1890 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1891
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001892 createGrantsTable(db);
1893
Fred Quintana60307342009-03-24 22:48:12 -07001894 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1895 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1896 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1897 + EXTRAS_KEY + " TEXT NOT NULL, "
1898 + EXTRAS_VALUE + " TEXT, "
1899 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1900
1901 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1902 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1903 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001904
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001905 createAccountsDeletionTrigger(db);
1906 }
1907
1908 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001909 db.execSQL(""
1910 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1911 + " BEGIN"
1912 + " DELETE FROM " + TABLE_AUTHTOKENS
1913 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1914 + " DELETE FROM " + TABLE_EXTRAS
1915 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001916 + " DELETE FROM " + TABLE_GRANTS
1917 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001918 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001919 }
1920
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001921 private void createGrantsTable(SQLiteDatabase db) {
1922 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1923 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1924 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1925 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1926 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1927 + "," + GRANTS_GRANTEE_UID + "))");
1928 }
1929
Fred Quintana60307342009-03-24 22:48:12 -07001930 @Override
1931 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001932 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001933
Fred Quintanaa698f422009-04-08 19:14:54 -07001934 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001935 // no longer need to do anything since the work is done
1936 // when upgrading from version 2
1937 oldVersion++;
1938 }
1939
1940 if (oldVersion == 2) {
1941 createGrantsTable(db);
1942 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1943 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001944 oldVersion++;
1945 }
Costin Manolache3348f142009-09-29 18:58:36 -07001946
1947 if (oldVersion == 3) {
1948 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1949 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1950 oldVersion++;
1951 }
Fred Quintana60307342009-03-24 22:48:12 -07001952 }
1953
1954 @Override
1955 public void onOpen(SQLiteDatabase db) {
1956 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1957 }
1958 }
1959
Fred Quintana60307342009-03-24 22:48:12 -07001960 public IBinder onBind(Intent intent) {
1961 return asBinder();
1962 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001963
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001964 /**
1965 * Searches array of arguments for the specified string
1966 * @param args array of argument strings
1967 * @param value value to search for
1968 * @return true if the value is contained in the array
1969 */
1970 private static boolean scanArgs(String[] args, String value) {
1971 if (args != null) {
1972 for (String arg : args) {
1973 if (value.equals(arg)) {
1974 return true;
1975 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001976 }
1977 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001978 return false;
1979 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001980
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001981 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001982 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1983 != PackageManager.PERMISSION_GRANTED) {
1984 fout.println("Permission Denial: can't dump AccountsManager from from pid="
1985 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1986 + " without permission " + android.Manifest.permission.DUMP);
1987 return;
1988 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001989 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Kenny Root3abd75b2011-09-29 11:00:41 -07001990
Amith Yamasani04e0d262012-02-14 11:50:53 -08001991 fout = new IndentingPrintWriter(fout, " ");
1992 int size = mUsers.size();
1993 for (int i = 0; i < size; i++) {
1994 fout.println("User " + mUsers.keyAt(i) + ":");
1995 ((IndentingPrintWriter) fout).increaseIndent();
1996 dumpUser(mUsers.valueAt(i), fd, fout, args, isCheckinRequest);
1997 ((IndentingPrintWriter) fout).decreaseIndent();
1998 if (i < size - 1) {
1999 fout.println();
2000 }
2001 }
2002 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002003
Amith Yamasani04e0d262012-02-14 11:50:53 -08002004 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2005 String[] args, boolean isCheckinRequest) {
2006 synchronized (userAccounts.cacheLock) {
2007 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002008
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002009 if (isCheckinRequest) {
2010 // This is a checkin request. *Only* upload the account types and the count of each.
2011 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2012 null, null, ACCOUNTS_TYPE, null, null);
2013 try {
2014 while (cursor.moveToNext()) {
2015 // print type,count
2016 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2017 }
2018 } finally {
2019 if (cursor != null) {
2020 cursor.close();
2021 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002022 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002023 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002024 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002025 fout.println("Accounts: " + accounts.length);
2026 for (Account account : accounts) {
2027 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002028 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002029
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002030 fout.println();
2031 synchronized (mSessions) {
2032 final long now = SystemClock.elapsedRealtime();
2033 fout.println("Active Sessions: " + mSessions.size());
2034 for (Session session : mSessions.values()) {
2035 fout.println(" " + session.toDebugString(now));
2036 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002037 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002038
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002039 fout.println();
2040 mAuthenticatorCache.dump(fd, fout, args);
2041 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002042 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002043 }
2044
Amith Yamasani04e0d262012-02-14 11:50:53 -08002045 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
2046 Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002047 long identityToken = clearCallingIdentity();
2048 try {
2049 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2050 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2051 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002052
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002053 if (intent.getComponent() != null &&
2054 GrantCredentialsPermissionActivity.class.getName().equals(
2055 intent.getComponent().getClassName())) {
2056 createNoCredentialsPermissionNotification(account, intent);
2057 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002058 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002059 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002060 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2061 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07002062 final String notificationTitleFormat =
2063 mContext.getText(R.string.notification_title).toString();
2064 n.setLatestEventInfo(mContext,
2065 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002066 message, PendingIntent.getActivity(
2067 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -08002068 installNotification(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002069 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002070 } finally {
2071 restoreCallingIdentity(identityToken);
2072 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002073 }
2074
Fred Quintana56285a62010-12-02 14:20:51 -08002075 protected void installNotification(final int notificationId, final Notification n) {
2076 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
2077 .notify(notificationId, n);
2078 }
2079
2080 protected void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002081 long identityToken = clearCallingIdentity();
2082 try {
2083 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002084 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002085 } finally {
2086 restoreCallingIdentity(identityToken);
2087 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002088 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002089
Fred Quintanab38eb142010-02-24 13:40:54 -08002090 /** Succeeds if any of the specified permissions are granted. */
2091 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002092 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002093
2094 for (String perm : permissions) {
2095 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2096 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002097 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002098 }
2099 return;
2100 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002101 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002102
2103 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002104 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002105 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002106 }
2107
Fred Quintana7be59642009-08-24 18:29:25 -07002108 private boolean inSystemImage(int callerUid) {
Fred Quintana56285a62010-12-02 14:20:51 -08002109 String[] packages = mPackageManager.getPackagesForUid(callerUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002110 for (String name : packages) {
2111 try {
Fred Quintana56285a62010-12-02 14:20:51 -08002112 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
2113 if (packageInfo != null
2114 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002115 return true;
2116 }
2117 } catch (PackageManager.NameNotFoundException e) {
2118 return false;
2119 }
2120 }
2121 return false;
2122 }
2123
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002124 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002125 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002126 final boolean fromAuthenticator = account != null
2127 && hasAuthenticatorUid(account.type, callerUid);
2128 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002129 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002130 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2131 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002132 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002133 + ": is authenticator? " + fromAuthenticator
2134 + ", has explicit permission? " + hasExplicitGrants);
2135 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002136 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002137 }
2138
Fred Quintana1a231912009-10-15 11:31:30 -07002139 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002140 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
2141 mAuthenticatorCache.getAllServices()) {
2142 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002143 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002144 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002145 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002146 }
2147 }
2148 return false;
2149 }
2150
Amith Yamasani04e0d262012-02-14 11:50:53 -08002151 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2152 int callerUid) {
2153 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002154 return true;
2155 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002156 UserAccounts accounts = getUserAccountsForCaller();
2157 synchronized (accounts.cacheLock) {
2158 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2159 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002160 account.name, account.type};
2161 final boolean permissionGranted =
2162 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2163 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2164 // TODO: Skip this check when running automated tests. Replace this
2165 // with a more general solution.
2166 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002167 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002168 + " but ignoring since device is in test harness.");
2169 return true;
2170 }
2171 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002172 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002173 }
2174
2175 private void checkCallingUidAgainstAuthenticator(Account account) {
2176 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002177 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002178 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2179 Log.w(TAG, msg);
2180 throw new SecurityException(msg);
2181 }
2182 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2183 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2184 }
2185 }
2186
2187 private void checkAuthenticateAccountsPermission(Account account) {
2188 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2189 checkCallingUidAgainstAuthenticator(account);
2190 }
2191
2192 private void checkReadAccountsPermission() {
2193 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2194 }
2195
2196 private void checkManageAccountsPermission() {
2197 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2198 }
2199
Fred Quintanab38eb142010-02-24 13:40:54 -08002200 private void checkManageAccountsOrUseCredentialsPermissions() {
2201 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2202 Manifest.permission.USE_CREDENTIALS);
2203 }
2204
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002205 /**
2206 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2207 * <p>
2208 * Although this is public it can only be accessed via the AccountManagerService object
2209 * which is in the system. This means we don't need to protect it with permissions.
2210 * @hide
2211 */
2212 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002213 if (account == null || authTokenType == null) {
2214 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002215 return;
2216 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002217 UserAccounts accounts = getUserAccounts(UserId.getUserId(uid));
2218 synchronized (accounts.cacheLock) {
2219 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002220 db.beginTransaction();
2221 try {
2222 long accountId = getAccountIdLocked(db, account);
2223 if (accountId >= 0) {
2224 ContentValues values = new ContentValues();
2225 values.put(GRANTS_ACCOUNTS_ID, accountId);
2226 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2227 values.put(GRANTS_GRANTEE_UID, uid);
2228 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2229 db.setTransactionSuccessful();
2230 }
2231 } finally {
2232 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002233 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002234 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002235 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002236 }
2237
2238 /**
2239 * Don't allow callers with the given uid permission to get credentials for
2240 * account/authTokenType.
2241 * <p>
2242 * Although this is public it can only be accessed via the AccountManagerService object
2243 * which is in the system. This means we don't need to protect it with permissions.
2244 * @hide
2245 */
2246 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002247 if (account == null || authTokenType == null) {
2248 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002249 return;
2250 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002251 UserAccounts accounts = getUserAccounts(UserId.getUserId(uid));
2252 synchronized (accounts.cacheLock) {
2253 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002254 db.beginTransaction();
2255 try {
2256 long accountId = getAccountIdLocked(db, account);
2257 if (accountId >= 0) {
2258 db.delete(TABLE_GRANTS,
2259 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2260 + GRANTS_GRANTEE_UID + "=?",
2261 new String[]{String.valueOf(accountId), authTokenType,
2262 String.valueOf(uid)});
2263 db.setTransactionSuccessful();
2264 }
2265 } finally {
2266 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002267 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002268 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002269 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002270 }
Fred Quintana56285a62010-12-02 14:20:51 -08002271
2272 static final private String stringArrayToString(String[] value) {
2273 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2274 }
2275
Amith Yamasani04e0d262012-02-14 11:50:53 -08002276 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2277 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002278 if (oldAccountsForType != null) {
2279 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2280 for (Account curAccount : oldAccountsForType) {
2281 if (!curAccount.equals(account)) {
2282 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002283 }
2284 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002285 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002286 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002287 } else {
2288 Account[] newAccountsForType = new Account[newAccountsList.size()];
2289 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002290 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002291 }
Fred Quintana56285a62010-12-02 14:20:51 -08002292 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002293 accounts.userDataCache.remove(account);
2294 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002295 }
2296
2297 /**
2298 * This assumes that the caller has already checked that the account is not already present.
2299 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002300 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2301 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002302 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2303 Account[] newAccountsForType = new Account[oldLength + 1];
2304 if (accountsForType != null) {
2305 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002306 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002307 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002308 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002309 }
2310
Amith Yamasani04e0d262012-02-14 11:50:53 -08002311 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002312 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002313 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002314 if (accounts == null) {
2315 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002316 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002317 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002318 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002319 } else {
2320 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002321 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002322 totalLength += accounts.length;
2323 }
2324 if (totalLength == 0) {
2325 return EMPTY_ACCOUNT_ARRAY;
2326 }
2327 Account[] accounts = new Account[totalLength];
2328 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002329 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002330 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2331 accountsOfType.length);
2332 totalLength += accountsOfType.length;
2333 }
2334 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002335 }
2336 }
2337
Amith Yamasani04e0d262012-02-14 11:50:53 -08002338 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2339 Account account, String key, String value) {
2340 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002341 if (userDataForAccount == null) {
2342 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002343 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002344 }
2345 if (value == null) {
2346 userDataForAccount.remove(key);
2347 } else {
2348 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002349 }
2350 }
2351
Amith Yamasani04e0d262012-02-14 11:50:53 -08002352 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2353 Account account, String key, String value) {
2354 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002355 if (authTokensForAccount == null) {
2356 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002357 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002358 }
2359 if (value == null) {
2360 authTokensForAccount.remove(key);
2361 } else {
2362 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002363 }
2364 }
2365
Amith Yamasani04e0d262012-02-14 11:50:53 -08002366 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2367 String authTokenType) {
2368 synchronized (accounts.cacheLock) {
2369 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002370 if (authTokensForAccount == null) {
2371 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002372 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002373 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002374 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002375 }
2376 return authTokensForAccount.get(authTokenType);
2377 }
2378 }
2379
Amith Yamasani04e0d262012-02-14 11:50:53 -08002380 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2381 synchronized (accounts.cacheLock) {
2382 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002383 if (userDataForAccount == null) {
2384 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002385 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002386 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002387 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002388 }
2389 return userDataForAccount.get(key);
2390 }
2391 }
2392
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002393 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2394 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002395 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002396 Cursor cursor = db.query(TABLE_EXTRAS,
2397 COLUMNS_EXTRAS_KEY_AND_VALUE,
2398 SELECTION_USERDATA_BY_ACCOUNT,
2399 new String[]{account.name, account.type},
2400 null, null, null);
2401 try {
2402 while (cursor.moveToNext()) {
2403 final String tmpkey = cursor.getString(0);
2404 final String value = cursor.getString(1);
2405 userDataForAccount.put(tmpkey, value);
2406 }
2407 } finally {
2408 cursor.close();
2409 }
2410 return userDataForAccount;
2411 }
2412
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002413 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2414 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002415 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002416 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2417 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2418 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2419 new String[]{account.name, account.type},
2420 null, null, null);
2421 try {
2422 while (cursor.moveToNext()) {
2423 final String type = cursor.getString(0);
2424 final String authToken = cursor.getString(1);
2425 authTokensForAccount.put(type, authToken);
2426 }
2427 } finally {
2428 cursor.close();
2429 }
2430 return authTokensForAccount;
2431 }
Fred Quintana60307342009-03-24 22:48:12 -07002432}