blob: 5cde65c90cc41c8268381022067b6fd5688ad713 [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;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070021import android.app.ActivityManagerNative;
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;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070035import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070036import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070037import android.content.pm.RegisteredServicesCacheListener;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070038import android.content.pm.UserInfo;
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;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070053import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070054import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070055import android.text.TextUtils;
56import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070057import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070058import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080059import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070060
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070061import com.android.internal.R;
Amith Yamasani04e0d262012-02-14 11:50:53 -080062import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070063import com.google.android.collect.Lists;
64import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070065
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070067import java.io.FileDescriptor;
68import java.io.PrintWriter;
69import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080070import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070071import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070072import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070073import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080074import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070075import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080076import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070077import java.util.concurrent.atomic.AtomicInteger;
78import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070079
Fred Quintana60307342009-03-24 22:48:12 -070080/**
81 * A system service that provides account, password, and authtoken management for all
82 * accounts on the device. Some of these calls are implemented with the help of the corresponding
83 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
84 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070085 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -070086 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070087 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070088public class AccountManagerService
89 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080090 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -070091 private static final String TAG = "AccountManagerService";
92
93 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
94 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070095 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070096
97 private final Context mContext;
98
Fred Quintana56285a62010-12-02 14:20:51 -080099 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700100 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800101
Fred Quintana60307342009-03-24 22:48:12 -0700102 private HandlerThread mMessageThread;
103 private final MessageHandler mMessageHandler;
104
105 // Messages that can be sent on mHandler
106 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700107
Fred Quintana56285a62010-12-02 14:20:51 -0800108 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700109
110 private static final String TABLE_ACCOUNTS = "accounts";
111 private static final String ACCOUNTS_ID = "_id";
112 private static final String ACCOUNTS_NAME = "name";
113 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700114 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700115 private static final String ACCOUNTS_PASSWORD = "password";
116
117 private static final String TABLE_AUTHTOKENS = "authtokens";
118 private static final String AUTHTOKENS_ID = "_id";
119 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
120 private static final String AUTHTOKENS_TYPE = "type";
121 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
122
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700123 private static final String TABLE_GRANTS = "grants";
124 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
125 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
126 private static final String GRANTS_GRANTEE_UID = "uid";
127
Fred Quintana60307342009-03-24 22:48:12 -0700128 private static final String TABLE_EXTRAS = "extras";
129 private static final String EXTRAS_ID = "_id";
130 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
131 private static final String EXTRAS_KEY = "key";
132 private static final String EXTRAS_VALUE = "value";
133
134 private static final String TABLE_META = "meta";
135 private static final String META_KEY = "key";
136 private static final String META_VALUE = "value";
137
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700138 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
139 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700140 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700141
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700142 private static final String COUNT_OF_MATCHING_GRANTS = ""
143 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
144 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
145 + " AND " + GRANTS_GRANTEE_UID + "=?"
146 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
147 + " AND " + ACCOUNTS_NAME + "=?"
148 + " AND " + ACCOUNTS_TYPE + "=?";
149
Fred Quintana56285a62010-12-02 14:20:51 -0800150 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
151 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
152 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
153 AUTHTOKENS_AUTHTOKEN};
154
155 private static final String SELECTION_USERDATA_BY_ACCOUNT =
156 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
157 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
158
Fred Quintanaa698f422009-04-08 19:14:54 -0700159 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700160 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
161
Amith Yamasani04e0d262012-02-14 11:50:53 -0800162 static class UserAccounts {
163 private final int userId;
164 private final DatabaseHelper openHelper;
165 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
166 credentialsPermissionNotificationIds =
167 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
168 private final HashMap<Account, Integer> signinRequiredNotificationIds =
169 new HashMap<Account, Integer>();
170 private final Object cacheLock = new Object();
171 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700172 private final HashMap<String, Account[]> accountCache =
173 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800174 /** protected by the {@link #cacheLock} */
175 private HashMap<Account, HashMap<String, String>> userDataCache =
176 new HashMap<Account, HashMap<String, String>>();
177 /** protected by the {@link #cacheLock} */
178 private HashMap<Account, HashMap<String, String>> authTokenCache =
179 new HashMap<Account, HashMap<String, String>>();
180
181 UserAccounts(Context context, int userId) {
182 this.userId = userId;
183 synchronized (cacheLock) {
184 openHelper = new DatabaseHelper(context, userId);
185 }
186 }
187 }
188
189 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
190
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700191 private static AtomicReference<AccountManagerService> sThis =
192 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700193 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700194
195 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700196 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700197 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
198 }
199
Fred Quintana56285a62010-12-02 14:20:51 -0800200
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700201 /**
202 * This should only be called by system code. One should only call this after the service
203 * has started.
204 * @return a reference to the AccountManagerService instance
205 * @hide
206 */
207 public static AccountManagerService getSingleton() {
208 return sThis.get();
209 }
Fred Quintana60307342009-03-24 22:48:12 -0700210
Fred Quintana56285a62010-12-02 14:20:51 -0800211 public AccountManagerService(Context context) {
212 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700213 }
214
Fred Quintana56285a62010-12-02 14:20:51 -0800215 public AccountManagerService(Context context, PackageManager packageManager,
216 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700217 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800218 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700219
Fred Quintana60307342009-03-24 22:48:12 -0700220 mMessageThread = new HandlerThread("AccountManagerService");
221 mMessageThread.start();
222 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
223
Fred Quintana56285a62010-12-02 14:20:51 -0800224 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800225 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700226
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700227 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800228
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800229 IntentFilter intentFilter = new IntentFilter();
230 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
231 intentFilter.addDataScheme("package");
232 mContext.registerReceiver(new BroadcastReceiver() {
233 @Override
234 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800235 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800236 }
237 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800238
Amith Yamasani13593602012-03-22 16:16:17 -0700239 IntentFilter userFilter = new IntentFilter();
240 userFilter.addAction(Intent.ACTION_USER_REMOVED);
241 mContext.registerReceiver(new BroadcastReceiver() {
242 @Override
243 public void onReceive(Context context, Intent intent) {
244 onUserRemoved(intent);
245 }
246 }, userFilter);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800247 }
248
Kenny Root26ff6622012-07-30 12:58:03 -0700249 public void systemReady() {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700250 initUser(UserHandle.USER_OWNER);
Kenny Root26ff6622012-07-30 12:58:03 -0700251 }
252
Amith Yamasani258848d2012-08-10 17:06:33 -0700253 private UserManager getUserManager() {
254 if (mUserManager == null) {
255 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
256 }
257 return mUserManager;
258 }
259
Amith Yamasani04e0d262012-02-14 11:50:53 -0800260 private UserAccounts initUser(int userId) {
261 synchronized (mUsers) {
262 UserAccounts accounts = mUsers.get(userId);
263 if (accounts == null) {
264 accounts = new UserAccounts(mContext, userId);
265 mUsers.append(userId, accounts);
266 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700267 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800268 }
269 return accounts;
270 }
271 }
272
273 private void purgeOldGrantsAll() {
274 synchronized (mUsers) {
275 for (int i = 0; i < mUsers.size(); i++) {
276 purgeOldGrants(mUsers.valueAt(i));
277 }
278 }
279 }
280
281 private void purgeOldGrants(UserAccounts accounts) {
282 synchronized (accounts.cacheLock) {
283 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800284 final Cursor cursor = db.query(TABLE_GRANTS,
285 new String[]{GRANTS_GRANTEE_UID},
286 null, null, GRANTS_GRANTEE_UID, null, null);
287 try {
288 while (cursor.moveToNext()) {
289 final int uid = cursor.getInt(0);
290 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
291 if (packageExists) {
292 continue;
293 }
294 Log.d(TAG, "deleting grants for UID " + uid
295 + " because its package is no longer installed");
296 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
297 new String[]{Integer.toString(uid)});
298 }
299 } finally {
300 cursor.close();
301 }
302 }
303 }
304
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700305 /**
306 * Validate internal set of accounts against installed authenticators for
307 * given user. Clears cached authenticators before validating.
308 */
309 public void validateAccounts(int userId) {
310 final UserAccounts accounts = getUserAccounts(userId);
311
312 // Invalidate user-specific cache to make sure we catch any
313 // removed authenticators.
314 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
315 }
316
317 /**
318 * Validate internal set of accounts against installed authenticators for
319 * given user. Clear cached authenticators before validating when requested.
320 */
321 private void validateAccountsInternal(
322 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
323 if (invalidateAuthenticatorCache) {
324 mAuthenticatorCache.invalidateCache(accounts.userId);
325 }
326
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700327 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
328 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
329 mAuthenticatorCache.getAllServices(accounts.userId)) {
330 knownAuth.add(service.type);
331 }
332
Amith Yamasani04e0d262012-02-14 11:50:53 -0800333 synchronized (accounts.cacheLock) {
334 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800335 boolean accountDeleted = false;
336 Cursor cursor = db.query(TABLE_ACCOUNTS,
337 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
338 null, null, null, null, null);
339 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800340 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800341 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700342 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800343 while (cursor.moveToNext()) {
344 final long accountId = cursor.getLong(0);
345 final String accountType = cursor.getString(1);
346 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700347
348 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700349 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800350 + accountType + " no longer has a registered authenticator");
351 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
352 accountDeleted = true;
353 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800354 accounts.userDataCache.remove(account);
355 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800356 } else {
357 ArrayList<String> accountNames = accountNamesByType.get(accountType);
358 if (accountNames == null) {
359 accountNames = new ArrayList<String>();
360 accountNamesByType.put(accountType, accountNames);
361 }
362 accountNames.add(accountName);
363 }
364 }
Andy McFadden2f362292012-01-20 14:43:38 -0800365 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800366 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800367 final String accountType = cur.getKey();
368 final ArrayList<String> accountNames = cur.getValue();
369 final Account[] accountsForType = new Account[accountNames.size()];
370 int i = 0;
371 for (String accountName : accountNames) {
372 accountsForType[i] = new Account(accountName, accountType);
373 ++i;
374 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800375 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800376 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800377 } finally {
378 cursor.close();
379 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800380 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800381 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800382 }
383 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700384 }
385
Amith Yamasani04e0d262012-02-14 11:50:53 -0800386 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700387 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800388 }
389
390 protected UserAccounts getUserAccounts(int userId) {
391 synchronized (mUsers) {
392 UserAccounts accounts = mUsers.get(userId);
393 if (accounts == null) {
394 accounts = initUser(userId);
395 mUsers.append(userId, accounts);
396 }
397 return accounts;
398 }
399 }
400
Amith Yamasani13593602012-03-22 16:16:17 -0700401 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700402 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700403 if (userId < 1) return;
404
405 UserAccounts accounts;
406 synchronized (mUsers) {
407 accounts = mUsers.get(userId);
408 mUsers.remove(userId);
409 }
410 if (accounts == null) {
411 File dbFile = new File(getDatabaseName(userId));
412 dbFile.delete();
413 return;
414 }
415
416 synchronized (accounts.cacheLock) {
417 accounts.openHelper.close();
418 File dbFile = new File(getDatabaseName(userId));
419 dbFile.delete();
420 }
421 }
422
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700423 @Override
424 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700425 Slog.d(TAG, "onServiceChanged() for userId " + userId);
426 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700427 }
428
Fred Quintanaa698f422009-04-08 19:14:54 -0700429 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800430 if (Log.isLoggable(TAG, Log.VERBOSE)) {
431 Log.v(TAG, "getPassword: " + account
432 + ", caller's uid " + Binder.getCallingUid()
433 + ", pid " + Binder.getCallingPid());
434 }
Fred Quintana382601f2010-03-25 12:25:10 -0700435 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700436 checkAuthenticateAccountsPermission(account);
437
Amith Yamasani04e0d262012-02-14 11:50:53 -0800438 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700439 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700440 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800441 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700442 } finally {
443 restoreCallingIdentity(identityToken);
444 }
445 }
446
Amith Yamasani04e0d262012-02-14 11:50:53 -0800447 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700448 if (account == null) {
449 return null;
450 }
451
Amith Yamasani04e0d262012-02-14 11:50:53 -0800452 synchronized (accounts.cacheLock) {
453 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800454 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
455 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
456 new String[]{account.name, account.type}, null, null, null);
457 try {
458 if (cursor.moveToNext()) {
459 return cursor.getString(0);
460 }
461 return null;
462 } finally {
463 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700464 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700465 }
466 }
467
468 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800469 if (Log.isLoggable(TAG, Log.VERBOSE)) {
470 Log.v(TAG, "getUserData: " + account
471 + ", key " + key
472 + ", caller's uid " + Binder.getCallingUid()
473 + ", pid " + Binder.getCallingPid());
474 }
Fred Quintana382601f2010-03-25 12:25:10 -0700475 if (account == null) throw new IllegalArgumentException("account is null");
476 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700477 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800478 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700479 long identityToken = clearCallingIdentity();
480 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800481 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700482 } finally {
483 restoreCallingIdentity(identityToken);
484 }
485 }
486
Fred Quintana97889762009-06-15 12:29:24 -0700487 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800488 if (Log.isLoggable(TAG, Log.VERBOSE)) {
489 Log.v(TAG, "getAuthenticatorTypes: "
490 + "caller's uid " + Binder.getCallingUid()
491 + ", pid " + Binder.getCallingPid());
492 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700493 final int userId = UserHandle.getCallingUserId();
494 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700495 try {
Fred Quintana97889762009-06-15 12:29:24 -0700496 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700497 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700498 AuthenticatorDescription[] types =
499 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700500 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700501 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700502 : authenticatorCollection) {
503 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700504 i++;
505 }
506 return types;
507 } finally {
508 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700509 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700510 }
511
Fred Quintanaa698f422009-04-08 19:14:54 -0700512 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800513 if (Log.isLoggable(TAG, Log.VERBOSE)) {
514 Log.v(TAG, "addAccount: " + account
515 + ", caller's uid " + Binder.getCallingUid()
516 + ", pid " + Binder.getCallingPid());
517 }
Fred Quintana382601f2010-03-25 12:25:10 -0700518 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700519 checkAuthenticateAccountsPermission(account);
520
Amith Yamasani04e0d262012-02-14 11:50:53 -0800521 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700522 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700523 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700524 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800525 return addAccountInternal(accounts, account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700526 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700527 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700528 }
529 }
530
Amith Yamasani04e0d262012-02-14 11:50:53 -0800531 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
532 Bundle extras) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700533 if (account == null) {
534 return false;
535 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800536 synchronized (accounts.cacheLock) {
537 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800538 db.beginTransaction();
539 try {
540 long numMatches = DatabaseUtils.longForQuery(db,
541 "select count(*) from " + TABLE_ACCOUNTS
542 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
543 new String[]{account.name, account.type});
544 if (numMatches > 0) {
545 Log.w(TAG, "insertAccountIntoDatabase: " + account
546 + ", skipping since the account already exists");
547 return false;
548 }
549 ContentValues values = new ContentValues();
550 values.put(ACCOUNTS_NAME, account.name);
551 values.put(ACCOUNTS_TYPE, account.type);
552 values.put(ACCOUNTS_PASSWORD, password);
553 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
554 if (accountId < 0) {
555 Log.w(TAG, "insertAccountIntoDatabase: " + account
556 + ", skipping the DB insert failed");
557 return false;
558 }
559 if (extras != null) {
560 for (String key : extras.keySet()) {
561 final String value = extras.getString(key);
562 if (insertExtraLocked(db, accountId, key, value) < 0) {
563 Log.w(TAG, "insertAccountIntoDatabase: " + account
564 + ", skipping since insertExtra failed for key " + key);
565 return false;
566 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700567 }
568 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800569 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800570 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800571 } finally {
572 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700573 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800574 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800575 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700576 }
577 }
578
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800579 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700580 ContentValues values = new ContentValues();
581 values.put(EXTRAS_KEY, key);
582 values.put(EXTRAS_ACCOUNTS_ID, accountId);
583 values.put(EXTRAS_VALUE, value);
584 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
585 }
586
Fred Quintana3084a6f2010-01-14 18:02:03 -0800587 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800588 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800589 if (Log.isLoggable(TAG, Log.VERBOSE)) {
590 Log.v(TAG, "hasFeatures: " + account
591 + ", response " + response
592 + ", features " + stringArrayToString(features)
593 + ", caller's uid " + Binder.getCallingUid()
594 + ", pid " + Binder.getCallingPid());
595 }
Fred Quintana382601f2010-03-25 12:25:10 -0700596 if (response == null) throw new IllegalArgumentException("response is null");
597 if (account == null) throw new IllegalArgumentException("account is null");
598 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800599 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800600 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800601 long identityToken = clearCallingIdentity();
602 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800603 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800604 } finally {
605 restoreCallingIdentity(identityToken);
606 }
607 }
608
609 private class TestFeaturesSession extends Session {
610 private final String[] mFeatures;
611 private final Account mAccount;
612
Amith Yamasani04e0d262012-02-14 11:50:53 -0800613 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800614 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800615 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800616 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800617 mFeatures = features;
618 mAccount = account;
619 }
620
621 public void run() throws RemoteException {
622 try {
623 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
624 } catch (RemoteException e) {
625 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
626 }
627 }
628
629 public void onResult(Bundle result) {
630 IAccountManagerResponse response = getResponseAndClose();
631 if (response != null) {
632 try {
633 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700634 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800635 return;
636 }
Fred Quintana56285a62010-12-02 14:20:51 -0800637 if (Log.isLoggable(TAG, Log.VERBOSE)) {
638 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
639 + response);
640 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800641 final Bundle newResult = new Bundle();
642 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
643 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
644 response.onResult(newResult);
645 } catch (RemoteException e) {
646 // if the caller is dead then there is no one to care about remote exceptions
647 if (Log.isLoggable(TAG, Log.VERBOSE)) {
648 Log.v(TAG, "failure while notifying response", e);
649 }
650 }
651 }
652 }
653
654 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800655 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800656 + ", " + mAccount
657 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
658 }
659 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800660
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700661 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800662 if (Log.isLoggable(TAG, Log.VERBOSE)) {
663 Log.v(TAG, "removeAccount: " + account
664 + ", response " + response
665 + ", caller's uid " + Binder.getCallingUid()
666 + ", pid " + Binder.getCallingPid());
667 }
Fred Quintana382601f2010-03-25 12:25:10 -0700668 if (response == null) throw new IllegalArgumentException("response is null");
669 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700670 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700671 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800672 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700673 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800674
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700675 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800676 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800677 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800678 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800679 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800680 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700681 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800682 }
683 }
684 }
685
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700686 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800687 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700688 } finally {
689 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700690 }
Fred Quintana60307342009-03-24 22:48:12 -0700691 }
692
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700693 private class RemoveAccountSession extends Session {
694 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800695 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
696 Account account) {
697 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800698 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700699 mAccount = account;
700 }
701
702 protected String toDebugString(long now) {
703 return super.toDebugString(now) + ", removeAccount"
704 + ", account " + mAccount;
705 }
706
707 public void run() throws RemoteException {
708 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
709 }
710
711 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700712 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
713 && !result.containsKey(AccountManager.KEY_INTENT)) {
714 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700715 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800716 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700717 }
718 IAccountManagerResponse response = getResponseAndClose();
719 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800720 if (Log.isLoggable(TAG, Log.VERBOSE)) {
721 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
722 + response);
723 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700724 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700725 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700726 try {
727 response.onResult(result2);
728 } catch (RemoteException e) {
729 // ignore
730 }
731 }
732 }
733 super.onResult(result);
734 }
735 }
736
Amith Yamasani04e0d262012-02-14 11:50:53 -0800737 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800738 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800739 removeAccountInternal(getUserAccountsForCaller(), account);
740 }
741
742 private void removeAccountInternal(UserAccounts accounts, Account account) {
743 synchronized (accounts.cacheLock) {
744 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800745 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
746 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800747 removeAccountFromCacheLocked(accounts, account);
748 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800749 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700750 }
751
Fred Quintanaa698f422009-04-08 19:14:54 -0700752 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800753 if (Log.isLoggable(TAG, Log.VERBOSE)) {
754 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
755 + ", caller's uid " + Binder.getCallingUid()
756 + ", pid " + Binder.getCallingPid());
757 }
Fred Quintana382601f2010-03-25 12:25:10 -0700758 if (accountType == null) throw new IllegalArgumentException("accountType is null");
759 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800760 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800761 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700762 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700763 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800764 synchronized (accounts.cacheLock) {
765 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800766 db.beginTransaction();
767 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800768 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800769 db.setTransactionSuccessful();
770 } finally {
771 db.endTransaction();
772 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700773 }
Fred Quintana60307342009-03-24 22:48:12 -0700774 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700775 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700776 }
777 }
778
Amith Yamasani04e0d262012-02-14 11:50:53 -0800779 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
780 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700781 if (authToken == null || accountType == null) {
782 return;
783 }
Fred Quintana33269202009-04-20 16:05:10 -0700784 Cursor cursor = db.rawQuery(
785 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
786 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
787 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
788 + " FROM " + TABLE_ACCOUNTS
789 + " JOIN " + TABLE_AUTHTOKENS
790 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
791 + " = " + AUTHTOKENS_ACCOUNTS_ID
792 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
793 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
794 new String[]{authToken, accountType});
795 try {
796 while (cursor.moveToNext()) {
797 long authTokenId = cursor.getLong(0);
798 String accountName = cursor.getString(1);
799 String authTokenType = cursor.getString(2);
800 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800801 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800802 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700803 }
Fred Quintana33269202009-04-20 16:05:10 -0700804 } finally {
805 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700806 }
807 }
808
Amith Yamasani04e0d262012-02-14 11:50:53 -0800809 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
810 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700811 if (account == null || type == null) {
812 return false;
813 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700814 cancelNotification(getSigninRequiredNotificationId(accounts, account),
815 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800816 synchronized (accounts.cacheLock) {
817 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800818 db.beginTransaction();
819 try {
820 long accountId = getAccountIdLocked(db, account);
821 if (accountId < 0) {
822 return false;
823 }
824 db.delete(TABLE_AUTHTOKENS,
825 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
826 new String[]{type});
827 ContentValues values = new ContentValues();
828 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
829 values.put(AUTHTOKENS_TYPE, type);
830 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
831 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
832 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800833 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800834 return true;
835 }
Fred Quintana33269202009-04-20 16:05:10 -0700836 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800837 } finally {
838 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -0700839 }
Fred Quintana60307342009-03-24 22:48:12 -0700840 }
841 }
842
Fred Quintanaa698f422009-04-08 19:14:54 -0700843 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800844 if (Log.isLoggable(TAG, Log.VERBOSE)) {
845 Log.v(TAG, "peekAuthToken: " + account
846 + ", authTokenType " + authTokenType
847 + ", caller's uid " + Binder.getCallingUid()
848 + ", pid " + Binder.getCallingPid());
849 }
Fred Quintana382601f2010-03-25 12:25:10 -0700850 if (account == null) throw new IllegalArgumentException("account is null");
851 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700852 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800853 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700854 long identityToken = clearCallingIdentity();
855 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800856 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700857 } finally {
858 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700859 }
Fred Quintana60307342009-03-24 22:48:12 -0700860 }
861
Fred Quintanaa698f422009-04-08 19:14:54 -0700862 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800863 if (Log.isLoggable(TAG, Log.VERBOSE)) {
864 Log.v(TAG, "setAuthToken: " + account
865 + ", authTokenType " + authTokenType
866 + ", caller's uid " + Binder.getCallingUid()
867 + ", pid " + Binder.getCallingPid());
868 }
Fred Quintana382601f2010-03-25 12:25:10 -0700869 if (account == null) throw new IllegalArgumentException("account is null");
870 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700871 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800872 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700873 long identityToken = clearCallingIdentity();
874 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800875 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700876 } finally {
877 restoreCallingIdentity(identityToken);
878 }
Fred Quintana60307342009-03-24 22:48:12 -0700879 }
880
Fred Quintanaa698f422009-04-08 19:14:54 -0700881 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -0800882 if (Log.isLoggable(TAG, Log.VERBOSE)) {
883 Log.v(TAG, "setAuthToken: " + account
884 + ", caller's uid " + Binder.getCallingUid()
885 + ", pid " + Binder.getCallingPid());
886 }
Fred Quintana382601f2010-03-25 12:25:10 -0700887 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700888 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800889 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700890 long identityToken = clearCallingIdentity();
891 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800892 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700893 } finally {
894 restoreCallingIdentity(identityToken);
895 }
Fred Quintana60307342009-03-24 22:48:12 -0700896 }
897
Amith Yamasani04e0d262012-02-14 11:50:53 -0800898 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700899 if (account == null) {
900 return;
901 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800902 synchronized (accounts.cacheLock) {
903 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800904 db.beginTransaction();
905 try {
906 final ContentValues values = new ContentValues();
907 values.put(ACCOUNTS_PASSWORD, password);
908 final long accountId = getAccountIdLocked(db, account);
909 if (accountId >= 0) {
910 final String[] argsAccountId = {String.valueOf(accountId)};
911 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
912 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800913 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800914 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -0800915 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800916 } finally {
917 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800918 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800919 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800920 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700921 }
922
Amith Yamasani04e0d262012-02-14 11:50:53 -0800923 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800924 Log.i(TAG, "the accounts changed, sending broadcast of "
925 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700926 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -0700927 }
928
Fred Quintanaa698f422009-04-08 19:14:54 -0700929 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800930 if (Log.isLoggable(TAG, Log.VERBOSE)) {
931 Log.v(TAG, "clearPassword: " + account
932 + ", caller's uid " + Binder.getCallingUid()
933 + ", pid " + Binder.getCallingPid());
934 }
Fred Quintana382601f2010-03-25 12:25:10 -0700935 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700936 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800937 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700938 long identityToken = clearCallingIdentity();
939 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800940 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700941 } finally {
942 restoreCallingIdentity(identityToken);
943 }
Fred Quintana60307342009-03-24 22:48:12 -0700944 }
945
Fred Quintanaa698f422009-04-08 19:14:54 -0700946 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -0800947 if (Log.isLoggable(TAG, Log.VERBOSE)) {
948 Log.v(TAG, "setUserData: " + account
949 + ", key " + key
950 + ", caller's uid " + Binder.getCallingUid()
951 + ", pid " + Binder.getCallingPid());
952 }
Fred Quintana382601f2010-03-25 12:25:10 -0700953 if (key == null) throw new IllegalArgumentException("key is null");
954 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700955 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800956 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700957 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700958 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800959 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700960 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700961 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700962 }
963 }
964
Amith Yamasani04e0d262012-02-14 11:50:53 -0800965 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
966 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700967 if (account == null || key == null) {
968 return;
969 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800970 synchronized (accounts.cacheLock) {
971 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800972 db.beginTransaction();
973 try {
974 long accountId = getAccountIdLocked(db, account);
975 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700976 return;
977 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800978 long extrasId = getExtrasIdLocked(db, accountId, key);
979 if (extrasId < 0 ) {
980 extrasId = insertExtraLocked(db, accountId, key, value);
981 if (extrasId < 0) {
982 return;
983 }
984 } else {
985 ContentValues values = new ContentValues();
986 values.put(EXTRAS_VALUE, value);
987 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
988 return;
989 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700990
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800991 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800992 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800993 db.setTransactionSuccessful();
994 } finally {
995 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700996 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700997 }
998 }
999
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001000 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001001 if (result == null) {
1002 Log.e(TAG, "the result is unexpectedly null", new Exception());
1003 }
1004 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1005 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1006 + response);
1007 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001008 try {
1009 response.onResult(result);
1010 } catch (RemoteException e) {
1011 // if the caller is dead then there is no one to care about remote
1012 // exceptions
1013 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1014 Log.v(TAG, "failure while notifying response", e);
1015 }
1016 }
1017 }
1018
Fred Quintanad9640ec2012-05-23 12:37:00 -07001019 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1020 final String authTokenType)
1021 throws RemoteException {
1022 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001023 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1024
Fred Quintanad9640ec2012-05-23 12:37:00 -07001025 final int callingUid = getCallingUid();
1026 clearCallingIdentity();
1027 if (callingUid != android.os.Process.SYSTEM_UID) {
1028 throw new SecurityException("can only call from system");
1029 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001030 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001031 long identityToken = clearCallingIdentity();
1032 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001033 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001034 false /* stripAuthTokenFromResult */) {
1035 protected String toDebugString(long now) {
1036 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001037 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001038 + ", authTokenType " + authTokenType;
1039 }
1040
1041 public void run() throws RemoteException {
1042 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1043 }
1044
1045 public void onResult(Bundle result) {
1046 if (result != null) {
1047 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1048 Bundle bundle = new Bundle();
1049 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1050 super.onResult(bundle);
1051 return;
1052 } else {
1053 super.onResult(result);
1054 }
1055 }
1056 }.bind();
1057 } finally {
1058 restoreCallingIdentity(identityToken);
1059 }
1060 }
1061
Fred Quintanaa698f422009-04-08 19:14:54 -07001062 public void getAuthToken(IAccountManagerResponse response, final Account account,
1063 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001064 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001065 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1066 Log.v(TAG, "getAuthToken: " + account
1067 + ", response " + response
1068 + ", authTokenType " + authTokenType
1069 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1070 + ", expectActivityLaunch " + expectActivityLaunch
1071 + ", caller's uid " + Binder.getCallingUid()
1072 + ", pid " + Binder.getCallingPid());
1073 }
Fred Quintana382601f2010-03-25 12:25:10 -07001074 if (response == null) throw new IllegalArgumentException("response is null");
1075 if (account == null) throw new IllegalArgumentException("account is null");
1076 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001077 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001078 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001079 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1080 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1081 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001082 final boolean customTokens =
1083 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1084
1085 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001086 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001087 final boolean permissionGranted = customTokens ||
1088 permissionIsGranted(account, authTokenType, callerUid);
1089
Costin Manolachec6684f92011-01-14 11:25:39 -08001090 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1091 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001092 // let authenticator know the identity of the caller
1093 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1094 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1095 if (notifyOnAuthFailure) {
1096 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001097 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001098
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001099 long identityToken = clearCallingIdentity();
1100 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001101 // if the caller has permission, do the peek. otherwise go the more expensive
1102 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001103 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001104 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001105 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001106 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001107 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1108 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1109 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001110 onResult(response, result);
1111 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001112 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001113 }
1114
Amith Yamasani04e0d262012-02-14 11:50:53 -08001115 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001116 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001117 protected String toDebugString(long now) {
1118 if (loginOptions != null) loginOptions.keySet();
1119 return super.toDebugString(now) + ", getAuthToken"
1120 + ", " + account
1121 + ", authTokenType " + authTokenType
1122 + ", loginOptions " + loginOptions
1123 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1124 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001125
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001126 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001127 // If the caller doesn't have permission then create and return the
1128 // "grant permission" intent instead of the "getAuthToken" intent.
1129 if (!permissionGranted) {
1130 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1131 } else {
1132 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1133 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001134 }
1135
1136 public void onResult(Bundle result) {
1137 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001138 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001139 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1140 new AccountAuthenticatorResponse(this),
1141 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001142 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001143 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001144 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001145 onResult(bundle);
1146 return;
1147 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001148 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001149 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001150 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1151 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001152 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001153 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001154 "the type and name should not be empty");
1155 return;
1156 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001157 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001158 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001159 authTokenType, authToken);
1160 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001161 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001162
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001163 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001164 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001165 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001166 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001167 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001168 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001169 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001170 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001171 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001172 }.bind();
1173 } finally {
1174 restoreCallingIdentity(identityToken);
1175 }
Fred Quintana60307342009-03-24 22:48:12 -07001176 }
1177
Dianne Hackborn41203752012-08-31 14:05:51 -07001178 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1179 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001180 int uid = intent.getIntExtra(
1181 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1182 String authTokenType = intent.getStringExtra(
1183 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1184 String authTokenLabel = intent.getStringExtra(
1185 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1186
1187 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1188 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001189 final String titleAndSubtitle =
1190 mContext.getString(R.string.permission_request_notification_with_subtitle,
1191 account.name);
1192 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001193 String title = titleAndSubtitle;
1194 String subtitle = "";
1195 if (index > 0) {
1196 title = titleAndSubtitle.substring(0, index);
1197 subtitle = titleAndSubtitle.substring(index + 1);
1198 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001199 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001200 n.setLatestEventInfo(mContext, title, subtitle,
1201 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001202 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1203 installNotification(getCredentialPermissionNotificationId(
1204 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001205 }
1206
Costin Manolache5f383ad92010-12-02 16:44:46 -08001207 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1208 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001209
1210 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001211 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001212 // Since it was set in Eclair+ we can't change it without breaking apps using
1213 // the intent from a non-Activity context.
1214 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001215 intent.addCategory(
1216 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001217
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001218 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001219 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1220 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001221 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001222
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001223 return intent;
1224 }
1225
1226 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1227 int uid) {
1228 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001229 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001230 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001231 final Pair<Pair<Account, String>, Integer> key =
1232 new Pair<Pair<Account, String>, Integer>(
1233 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001234 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001235 if (id == null) {
1236 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001237 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001238 }
1239 }
1240 return id;
1241 }
1242
Amith Yamasani04e0d262012-02-14 11:50:53 -08001243 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001244 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001245 synchronized (accounts.signinRequiredNotificationIds) {
1246 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001247 if (id == null) {
1248 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001249 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001250 }
1251 }
1252 return id;
1253 }
1254
Fred Quintana33269202009-04-20 16:05:10 -07001255 public void addAcount(final IAccountManagerResponse response, final String accountType,
1256 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001257 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001258 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1259 Log.v(TAG, "addAccount: accountType " + accountType
1260 + ", response " + response
1261 + ", authTokenType " + authTokenType
1262 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1263 + ", expectActivityLaunch " + expectActivityLaunch
1264 + ", caller's uid " + Binder.getCallingUid()
1265 + ", pid " + Binder.getCallingPid());
1266 }
Fred Quintana382601f2010-03-25 12:25:10 -07001267 if (response == null) throw new IllegalArgumentException("response is null");
1268 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001269 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001270
Amith Yamasani04e0d262012-02-14 11:50:53 -08001271 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001272 final int pid = Binder.getCallingPid();
1273 final int uid = Binder.getCallingUid();
1274 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1275 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1276 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1277
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001278 long identityToken = clearCallingIdentity();
1279 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001280 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001281 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001282 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001283 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001284 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001285 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001286
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001287 protected String toDebugString(long now) {
1288 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001289 + ", accountType " + accountType
1290 + ", requiredFeatures "
1291 + (requiredFeatures != null
1292 ? TextUtils.join(",", requiredFeatures)
1293 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001294 }
1295 }.bind();
1296 } finally {
1297 restoreCallingIdentity(identityToken);
1298 }
Fred Quintana60307342009-03-24 22:48:12 -07001299 }
1300
Fred Quintanaa698f422009-04-08 19:14:54 -07001301 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001302 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001303 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1304 Log.v(TAG, "confirmCredentials: " + account
1305 + ", response " + response
1306 + ", expectActivityLaunch " + expectActivityLaunch
1307 + ", caller's uid " + Binder.getCallingUid()
1308 + ", pid " + Binder.getCallingPid());
1309 }
Fred Quintana382601f2010-03-25 12:25:10 -07001310 if (response == null) throw new IllegalArgumentException("response is null");
1311 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001312 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001313 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001314 long identityToken = clearCallingIdentity();
1315 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001316 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001317 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001318 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001319 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001320 }
1321 protected String toDebugString(long now) {
1322 return super.toDebugString(now) + ", confirmCredentials"
1323 + ", " + account;
1324 }
1325 }.bind();
1326 } finally {
1327 restoreCallingIdentity(identityToken);
1328 }
Fred Quintana60307342009-03-24 22:48:12 -07001329 }
1330
Fred Quintanaa698f422009-04-08 19:14:54 -07001331 public void updateCredentials(IAccountManagerResponse response, final Account account,
1332 final String authTokenType, final boolean expectActivityLaunch,
1333 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001334 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1335 Log.v(TAG, "updateCredentials: " + account
1336 + ", response " + response
1337 + ", authTokenType " + authTokenType
1338 + ", expectActivityLaunch " + expectActivityLaunch
1339 + ", caller's uid " + Binder.getCallingUid()
1340 + ", pid " + Binder.getCallingPid());
1341 }
Fred Quintana382601f2010-03-25 12:25:10 -07001342 if (response == null) throw new IllegalArgumentException("response is null");
1343 if (account == null) throw new IllegalArgumentException("account is null");
1344 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001345 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001346 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001347 long identityToken = clearCallingIdentity();
1348 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001349 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001350 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001351 public void run() throws RemoteException {
1352 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1353 }
1354 protected String toDebugString(long now) {
1355 if (loginOptions != null) loginOptions.keySet();
1356 return super.toDebugString(now) + ", updateCredentials"
1357 + ", " + account
1358 + ", authTokenType " + authTokenType
1359 + ", loginOptions " + loginOptions;
1360 }
1361 }.bind();
1362 } finally {
1363 restoreCallingIdentity(identityToken);
1364 }
Fred Quintana60307342009-03-24 22:48:12 -07001365 }
1366
Fred Quintanaa698f422009-04-08 19:14:54 -07001367 public void editProperties(IAccountManagerResponse response, final String accountType,
1368 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001369 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1370 Log.v(TAG, "editProperties: accountType " + accountType
1371 + ", response " + response
1372 + ", expectActivityLaunch " + expectActivityLaunch
1373 + ", caller's uid " + Binder.getCallingUid()
1374 + ", pid " + Binder.getCallingPid());
1375 }
Fred Quintana382601f2010-03-25 12:25:10 -07001376 if (response == null) throw new IllegalArgumentException("response is null");
1377 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001378 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001379 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001380 long identityToken = clearCallingIdentity();
1381 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001382 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001383 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001384 public void run() throws RemoteException {
1385 mAuthenticator.editProperties(this, mAccountType);
1386 }
1387 protected String toDebugString(long now) {
1388 return super.toDebugString(now) + ", editProperties"
1389 + ", accountType " + accountType;
1390 }
1391 }.bind();
1392 } finally {
1393 restoreCallingIdentity(identityToken);
1394 }
Fred Quintana60307342009-03-24 22:48:12 -07001395 }
1396
Fred Quintana33269202009-04-20 16:05:10 -07001397 private class GetAccountsByTypeAndFeatureSession extends Session {
1398 private final String[] mFeatures;
1399 private volatile Account[] mAccountsOfType = null;
1400 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1401 private volatile int mCurrentAccount = 0;
1402
Amith Yamasani04e0d262012-02-14 11:50:53 -08001403 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
1404 IAccountManagerResponse response, String type, String[] features) {
1405 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001406 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001407 mFeatures = features;
1408 }
1409
1410 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001411 synchronized (mAccounts.cacheLock) {
1412 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001413 }
Fred Quintana33269202009-04-20 16:05:10 -07001414 // check whether each account matches the requested features
1415 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1416 mCurrentAccount = 0;
1417
1418 checkAccount();
1419 }
1420
1421 public void checkAccount() {
1422 if (mCurrentAccount >= mAccountsOfType.length) {
1423 sendResult();
1424 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001425 }
Fred Quintana33269202009-04-20 16:05:10 -07001426
Fred Quintana29e94b82010-03-10 12:11:51 -08001427 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1428 if (accountAuthenticator == null) {
1429 // It is possible that the authenticator has died, which is indicated by
1430 // mAuthenticator being set to null. If this happens then just abort.
1431 // There is no need to send back a result or error in this case since
1432 // that already happened when mAuthenticator was cleared.
1433 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1434 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1435 + " connected to the authenticator, " + toDebugString());
1436 }
1437 return;
1438 }
Fred Quintana33269202009-04-20 16:05:10 -07001439 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001440 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001441 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001442 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001443 }
1444 }
1445
1446 public void onResult(Bundle result) {
1447 mNumResults++;
1448 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001449 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001450 return;
1451 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001452 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001453 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1454 }
1455 mCurrentAccount++;
1456 checkAccount();
1457 }
1458
1459 public void sendResult() {
1460 IAccountManagerResponse response = getResponseAndClose();
1461 if (response != null) {
1462 try {
1463 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1464 for (int i = 0; i < accounts.length; i++) {
1465 accounts[i] = mAccountsWithFeatures.get(i);
1466 }
Fred Quintana56285a62010-12-02 14:20:51 -08001467 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1468 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1469 + response);
1470 }
Fred Quintana33269202009-04-20 16:05:10 -07001471 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001472 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001473 response.onResult(result);
1474 } catch (RemoteException e) {
1475 // if the caller is dead then there is no one to care about remote exceptions
1476 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1477 Log.v(TAG, "failure while notifying response", e);
1478 }
1479 }
1480 }
1481 }
1482
1483
1484 protected String toDebugString(long now) {
1485 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1486 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1487 }
1488 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001489
Amith Yamasani04e0d262012-02-14 11:50:53 -08001490 /**
1491 * Returns the accounts for a specific user
1492 * @hide
1493 */
1494 public Account[] getAccounts(int userId) {
1495 checkReadAccountsPermission();
1496 UserAccounts accounts = getUserAccounts(userId);
1497 long identityToken = clearCallingIdentity();
1498 try {
1499 synchronized (accounts.cacheLock) {
1500 return getAccountsFromCacheLocked(accounts, null);
1501 }
1502 } finally {
1503 restoreCallingIdentity(identityToken);
1504 }
1505 }
1506
Amith Yamasanif29f2362012-04-05 18:29:52 -07001507 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001508 * Returns accounts for all running users.
1509 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001510 * @hide
1511 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001512 public AccountAndUser[] getRunningAccounts() {
1513 final int[] runningUserIds;
1514 try {
1515 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1516 } catch (RemoteException e) {
1517 // Running in system_server; should never happen
1518 throw new RuntimeException(e);
1519 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001520 return getAccounts(runningUserIds);
1521 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001522
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001523 /** {@hide} */
1524 public AccountAndUser[] getAllAccounts() {
1525 final List<UserInfo> users = getUserManager().getUsers();
1526 final int[] userIds = new int[users.size()];
1527 for (int i = 0; i < userIds.length; i++) {
1528 userIds[i] = users.get(i).id;
1529 }
1530 return getAccounts(userIds);
1531 }
1532
1533 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001534 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1535 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001536 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001537 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001538 if (userAccounts == null) continue;
1539 synchronized (userAccounts.cacheLock) {
1540 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null);
1541 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001542 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001543 }
1544 }
1545 }
1546 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001547
1548 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1549 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001550 }
1551
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001552 public Account[] getAccounts(String type) {
Fred Quintana56285a62010-12-02 14:20:51 -08001553 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1554 Log.v(TAG, "getAccounts: accountType " + type
1555 + ", caller's uid " + Binder.getCallingUid()
1556 + ", pid " + Binder.getCallingPid());
1557 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001558 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001559 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001560 long identityToken = clearCallingIdentity();
1561 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001562 synchronized (accounts.cacheLock) {
1563 return getAccountsFromCacheLocked(accounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001564 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001565 } finally {
1566 restoreCallingIdentity(identityToken);
1567 }
1568 }
1569
1570 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001571 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001572 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1573 Log.v(TAG, "getAccounts: accountType " + type
1574 + ", response " + response
1575 + ", features " + stringArrayToString(features)
1576 + ", caller's uid " + Binder.getCallingUid()
1577 + ", pid " + Binder.getCallingPid());
1578 }
Fred Quintana382601f2010-03-25 12:25:10 -07001579 if (response == null) throw new IllegalArgumentException("response is null");
1580 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001581 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001582 UserAccounts userAccounts = getUserAccountsForCaller();
Fred Quintana33269202009-04-20 16:05:10 -07001583 long identityToken = clearCallingIdentity();
1584 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001585 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001586 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001587 synchronized (userAccounts.cacheLock) {
1588 accounts = getAccountsFromCacheLocked(userAccounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001589 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001590 Bundle result = new Bundle();
1591 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1592 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001593 return;
1594 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001595 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001596 } finally {
1597 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001598 }
1599 }
1600
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001601 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001602 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001603 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001604 try {
1605 if (cursor.moveToNext()) {
1606 return cursor.getLong(0);
1607 }
1608 return -1;
1609 } finally {
1610 cursor.close();
1611 }
1612 }
1613
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001614 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001615 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1616 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1617 new String[]{key}, null, null, null);
1618 try {
1619 if (cursor.moveToNext()) {
1620 return cursor.getLong(0);
1621 }
1622 return -1;
1623 } finally {
1624 cursor.close();
1625 }
1626 }
1627
Fred Quintanaa698f422009-04-08 19:14:54 -07001628 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001629 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001630 IAccountManagerResponse mResponse;
1631 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001632 final boolean mExpectActivityLaunch;
1633 final long mCreationTime;
1634
Fred Quintana33269202009-04-20 16:05:10 -07001635 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001636 private int mNumRequestContinued = 0;
1637 private int mNumErrors = 0;
1638
Fred Quintana60307342009-03-24 22:48:12 -07001639
1640 IAccountAuthenticator mAuthenticator = null;
1641
Fred Quintana8570f742010-02-18 10:32:54 -08001642 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001643 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001644
Amith Yamasani04e0d262012-02-14 11:50:53 -08001645 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001646 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001647 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001648 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001649 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001650 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001651 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001652 mResponse = response;
1653 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001654 mExpectActivityLaunch = expectActivityLaunch;
1655 mCreationTime = SystemClock.elapsedRealtime();
1656 synchronized (mSessions) {
1657 mSessions.put(toString(), this);
1658 }
1659 try {
1660 response.asBinder().linkToDeath(this, 0 /* flags */);
1661 } catch (RemoteException e) {
1662 mResponse = null;
1663 binderDied();
1664 }
Fred Quintana60307342009-03-24 22:48:12 -07001665 }
1666
Fred Quintanaa698f422009-04-08 19:14:54 -07001667 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001668 if (mResponse == null) {
1669 // this session has already been closed
1670 return null;
1671 }
Fred Quintana60307342009-03-24 22:48:12 -07001672 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001673 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001674 return response;
1675 }
1676
Fred Quintanaa698f422009-04-08 19:14:54 -07001677 private void close() {
1678 synchronized (mSessions) {
1679 if (mSessions.remove(toString()) == null) {
1680 // the session was already closed, so bail out now
1681 return;
1682 }
1683 }
1684 if (mResponse != null) {
1685 // stop listening for response deaths
1686 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1687
1688 // clear this so that we don't accidentally send any further results
1689 mResponse = null;
1690 }
1691 cancelTimeout();
1692 unbind();
1693 }
1694
1695 public void binderDied() {
1696 mResponse = null;
1697 close();
1698 }
1699
1700 protected String toDebugString() {
1701 return toDebugString(SystemClock.elapsedRealtime());
1702 }
1703
1704 protected String toDebugString(long now) {
1705 return "Session: expectLaunch " + mExpectActivityLaunch
1706 + ", connected " + (mAuthenticator != null)
1707 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1708 + "/" + mNumErrors + ")"
1709 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1710 }
1711
Fred Quintana60307342009-03-24 22:48:12 -07001712 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001713 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1714 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1715 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001716 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001717 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001718 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001719 }
1720 }
1721
1722 private void unbind() {
1723 if (mAuthenticator != null) {
1724 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001725 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001726 }
1727 }
1728
1729 public void scheduleTimeout() {
1730 mMessageHandler.sendMessageDelayed(
1731 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1732 }
1733
1734 public void cancelTimeout() {
1735 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1736 }
1737
Fred Quintanab839afc2009-10-14 15:57:28 -07001738 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001739 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001740 try {
1741 run();
1742 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001743 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001744 "remote exception");
1745 }
Fred Quintana60307342009-03-24 22:48:12 -07001746 }
1747
Fred Quintanab839afc2009-10-14 15:57:28 -07001748 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001749 mAuthenticator = null;
1750 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001751 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001752 try {
1753 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1754 "disconnected");
1755 } catch (RemoteException e) {
1756 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1757 Log.v(TAG, "Session.onServiceDisconnected: "
1758 + "caught RemoteException while responding", e);
1759 }
1760 }
Fred Quintana60307342009-03-24 22:48:12 -07001761 }
1762 }
1763
Fred Quintanab839afc2009-10-14 15:57:28 -07001764 public abstract void run() throws RemoteException;
1765
Fred Quintana60307342009-03-24 22:48:12 -07001766 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001767 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001768 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001769 try {
1770 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1771 "timeout");
1772 } catch (RemoteException e) {
1773 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1774 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
1775 e);
1776 }
1777 }
Fred Quintana60307342009-03-24 22:48:12 -07001778 }
1779 }
1780
Fred Quintanaa698f422009-04-08 19:14:54 -07001781 public void onResult(Bundle result) {
1782 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001783 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1784 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1785 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001786 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1787 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001788 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
1789 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001790 }
Fred Quintana60307342009-03-24 22:48:12 -07001791 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001792 IAccountManagerResponse response;
1793 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001794 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001795 response = mResponse;
1796 } else {
1797 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001798 }
Fred Quintana60307342009-03-24 22:48:12 -07001799 if (response != null) {
1800 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001801 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001802 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1803 Log.v(TAG, getClass().getSimpleName()
1804 + " calling onError() on response " + response);
1805 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001806 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001807 "null bundle returned");
1808 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001809 if (mStripAuthTokenFromResult) {
1810 result.remove(AccountManager.KEY_AUTHTOKEN);
1811 }
Fred Quintana56285a62010-12-02 14:20:51 -08001812 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1813 Log.v(TAG, getClass().getSimpleName()
1814 + " calling onResult() on response " + response);
1815 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001816 response.onResult(result);
1817 }
Fred Quintana60307342009-03-24 22:48:12 -07001818 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001819 // if the caller is dead then there is no one to care about remote exceptions
1820 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1821 Log.v(TAG, "failure while notifying response", e);
1822 }
Fred Quintana60307342009-03-24 22:48:12 -07001823 }
1824 }
1825 }
Fred Quintana60307342009-03-24 22:48:12 -07001826
Fred Quintanaa698f422009-04-08 19:14:54 -07001827 public void onRequestContinued() {
1828 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001829 }
1830
1831 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001832 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001833 IAccountManagerResponse response = getResponseAndClose();
1834 if (response != null) {
1835 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001836 Log.v(TAG, getClass().getSimpleName()
1837 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001838 }
1839 try {
1840 response.onError(errorCode, errorMessage);
1841 } catch (RemoteException e) {
1842 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1843 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1844 }
1845 }
1846 } else {
1847 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1848 Log.v(TAG, "Session.onError: already closed");
1849 }
Fred Quintana60307342009-03-24 22:48:12 -07001850 }
1851 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001852
1853 /**
1854 * find the component name for the authenticator and initiate a bind
1855 * if no authenticator or the bind fails then return false, otherwise return true
1856 */
1857 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001858 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1859 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1860 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07001861 if (authenticatorInfo == null) {
1862 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1863 Log.v(TAG, "there is no authenticator for " + authenticatorType
1864 + ", bailing out");
1865 }
1866 return false;
1867 }
1868
1869 Intent intent = new Intent();
1870 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1871 intent.setComponent(authenticatorInfo.componentName);
1872 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1873 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1874 }
Amith Yamasani34daa752012-03-19 16:14:23 -07001875 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE, mAccounts.userId)) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001876 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1877 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1878 }
1879 return false;
1880 }
1881
1882
1883 return true;
1884 }
Fred Quintana60307342009-03-24 22:48:12 -07001885 }
1886
1887 private class MessageHandler extends Handler {
1888 MessageHandler(Looper looper) {
1889 super(looper);
1890 }
Costin Manolache3348f142009-09-29 18:58:36 -07001891
Fred Quintana60307342009-03-24 22:48:12 -07001892 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001893 switch (msg.what) {
1894 case MESSAGE_TIMED_OUT:
1895 Session session = (Session)msg.obj;
1896 session.onTimedOut();
1897 break;
1898
1899 default:
1900 throw new IllegalStateException("unhandled message: " + msg.what);
1901 }
1902 }
1903 }
1904
Amith Yamasani04e0d262012-02-14 11:50:53 -08001905 private static String getDatabaseName(int userId) {
1906 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07001907 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001908 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07001909 // Migrate old file, if it exists, to the new location.
1910 // Make sure the new file doesn't already exist. A dummy file could have been
1911 // accidentally created in the old location, causing the new one to become corrupted
1912 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08001913 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07001914 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07001915 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07001916 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07001917 if (!userDir.exists()) {
1918 if (!userDir.mkdirs()) {
1919 throw new IllegalStateException("User dir cannot be created: " + userDir);
1920 }
1921 }
1922 if (!oldFile.renameTo(databaseFile)) {
1923 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
1924 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001925 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08001926 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001927 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08001928 }
1929
Amith Yamasani04e0d262012-02-14 11:50:53 -08001930 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001931
Amith Yamasani04e0d262012-02-14 11:50:53 -08001932 public DatabaseHelper(Context context, int userId) {
1933 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001934 }
1935
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001936 /**
1937 * This call needs to be made while the mCacheLock is held. The way to
1938 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
1939 * @param db The database.
1940 */
Fred Quintana60307342009-03-24 22:48:12 -07001941 @Override
1942 public void onCreate(SQLiteDatabase db) {
1943 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1944 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1945 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1946 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1947 + ACCOUNTS_PASSWORD + " TEXT, "
1948 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1949
1950 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1951 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1952 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1953 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1954 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1955 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1956
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001957 createGrantsTable(db);
1958
Fred Quintana60307342009-03-24 22:48:12 -07001959 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1960 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1961 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1962 + EXTRAS_KEY + " TEXT NOT NULL, "
1963 + EXTRAS_VALUE + " TEXT, "
1964 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1965
1966 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1967 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1968 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001969
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001970 createAccountsDeletionTrigger(db);
1971 }
1972
1973 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001974 db.execSQL(""
1975 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1976 + " BEGIN"
1977 + " DELETE FROM " + TABLE_AUTHTOKENS
1978 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1979 + " DELETE FROM " + TABLE_EXTRAS
1980 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001981 + " DELETE FROM " + TABLE_GRANTS
1982 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001983 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001984 }
1985
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001986 private void createGrantsTable(SQLiteDatabase db) {
1987 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1988 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1989 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1990 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1991 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1992 + "," + GRANTS_GRANTEE_UID + "))");
1993 }
1994
Fred Quintana60307342009-03-24 22:48:12 -07001995 @Override
1996 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001997 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001998
Fred Quintanaa698f422009-04-08 19:14:54 -07001999 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002000 // no longer need to do anything since the work is done
2001 // when upgrading from version 2
2002 oldVersion++;
2003 }
2004
2005 if (oldVersion == 2) {
2006 createGrantsTable(db);
2007 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2008 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002009 oldVersion++;
2010 }
Costin Manolache3348f142009-09-29 18:58:36 -07002011
2012 if (oldVersion == 3) {
2013 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2014 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2015 oldVersion++;
2016 }
Fred Quintana60307342009-03-24 22:48:12 -07002017 }
2018
2019 @Override
2020 public void onOpen(SQLiteDatabase db) {
2021 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2022 }
2023 }
2024
Fred Quintana60307342009-03-24 22:48:12 -07002025 public IBinder onBind(Intent intent) {
2026 return asBinder();
2027 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002028
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002029 /**
2030 * Searches array of arguments for the specified string
2031 * @param args array of argument strings
2032 * @param value value to search for
2033 * @return true if the value is contained in the array
2034 */
2035 private static boolean scanArgs(String[] args, String value) {
2036 if (args != null) {
2037 for (String arg : args) {
2038 if (value.equals(arg)) {
2039 return true;
2040 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002041 }
2042 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002043 return false;
2044 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002045
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002046 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002047 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002048 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2049 != PackageManager.PERMISSION_GRANTED) {
2050 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2051 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2052 + " without permission " + android.Manifest.permission.DUMP);
2053 return;
2054 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002055 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002056 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002057
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002058 final List<UserInfo> users = getUserManager().getUsers();
2059 for (UserInfo user : users) {
2060 ipw.println("User " + user + ":");
2061 ipw.increaseIndent();
2062 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2063 ipw.println();
2064 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002065 }
2066 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002067
Amith Yamasani04e0d262012-02-14 11:50:53 -08002068 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2069 String[] args, boolean isCheckinRequest) {
2070 synchronized (userAccounts.cacheLock) {
2071 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002072
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002073 if (isCheckinRequest) {
2074 // This is a checkin request. *Only* upload the account types and the count of each.
2075 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2076 null, null, ACCOUNTS_TYPE, null, null);
2077 try {
2078 while (cursor.moveToNext()) {
2079 // print type,count
2080 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2081 }
2082 } finally {
2083 if (cursor != null) {
2084 cursor.close();
2085 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002086 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002087 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002088 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002089 fout.println("Accounts: " + accounts.length);
2090 for (Account account : accounts) {
2091 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002092 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002093
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002094 fout.println();
2095 synchronized (mSessions) {
2096 final long now = SystemClock.elapsedRealtime();
2097 fout.println("Active Sessions: " + mSessions.size());
2098 for (Session session : mSessions.values()) {
2099 fout.println(" " + session.toDebugString(now));
2100 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002101 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002102
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002103 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002104 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002105 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002106 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002107 }
2108
Amith Yamasani04e0d262012-02-14 11:50:53 -08002109 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002110 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002111 long identityToken = clearCallingIdentity();
2112 try {
2113 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2114 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2115 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002116
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002117 if (intent.getComponent() != null &&
2118 GrantCredentialsPermissionActivity.class.getName().equals(
2119 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002120 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002121 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002122 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002123 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002124 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2125 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002126 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002127 final String notificationTitleFormat =
2128 mContext.getText(R.string.notification_title).toString();
2129 n.setLatestEventInfo(mContext,
2130 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002131 message, PendingIntent.getActivityAsUser(
2132 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002133 null, user));
2134 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002135 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002136 } finally {
2137 restoreCallingIdentity(identityToken);
2138 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002139 }
2140
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002141 protected void installNotification(final int notificationId, final Notification n,
2142 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002143 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002144 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002145 }
2146
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002147 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002148 long identityToken = clearCallingIdentity();
2149 try {
2150 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002151 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002152 } finally {
2153 restoreCallingIdentity(identityToken);
2154 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002155 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002156
Fred Quintanab38eb142010-02-24 13:40:54 -08002157 /** Succeeds if any of the specified permissions are granted. */
2158 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002159 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002160
2161 for (String perm : permissions) {
2162 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2163 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002164 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002165 }
2166 return;
2167 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002168 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002169
2170 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002171 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002172 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002173 }
2174
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002175 private boolean inSystemImage(int callingUid) {
2176 final int callingUserId = UserHandle.getUserId(callingUid);
2177
2178 final PackageManager userPackageManager;
2179 try {
2180 userPackageManager = mContext.createPackageContextAsUser(
2181 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2182 } catch (NameNotFoundException e) {
2183 return false;
2184 }
2185
2186 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002187 for (String name : packages) {
2188 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002189 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002190 if (packageInfo != null
2191 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002192 return true;
2193 }
2194 } catch (PackageManager.NameNotFoundException e) {
2195 return false;
2196 }
2197 }
2198 return false;
2199 }
2200
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002201 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002202 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002203 final boolean fromAuthenticator = account != null
2204 && hasAuthenticatorUid(account.type, callerUid);
2205 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002206 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002207 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2208 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002209 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002210 + ": is authenticator? " + fromAuthenticator
2211 + ", has explicit permission? " + hasExplicitGrants);
2212 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002213 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002214 }
2215
Fred Quintana1a231912009-10-15 11:31:30 -07002216 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002217 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002218 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002219 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002220 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002221 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002222 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002223 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002224 }
2225 }
2226 return false;
2227 }
2228
Amith Yamasani04e0d262012-02-14 11:50:53 -08002229 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2230 int callerUid) {
2231 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002232 return true;
2233 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002234 UserAccounts accounts = getUserAccountsForCaller();
2235 synchronized (accounts.cacheLock) {
2236 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2237 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002238 account.name, account.type};
2239 final boolean permissionGranted =
2240 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2241 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2242 // TODO: Skip this check when running automated tests. Replace this
2243 // with a more general solution.
2244 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002245 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002246 + " but ignoring since device is in test harness.");
2247 return true;
2248 }
2249 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002250 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002251 }
2252
2253 private void checkCallingUidAgainstAuthenticator(Account account) {
2254 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002255 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002256 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2257 Log.w(TAG, msg);
2258 throw new SecurityException(msg);
2259 }
2260 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2261 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2262 }
2263 }
2264
2265 private void checkAuthenticateAccountsPermission(Account account) {
2266 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2267 checkCallingUidAgainstAuthenticator(account);
2268 }
2269
2270 private void checkReadAccountsPermission() {
2271 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2272 }
2273
2274 private void checkManageAccountsPermission() {
2275 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2276 }
2277
Fred Quintanab38eb142010-02-24 13:40:54 -08002278 private void checkManageAccountsOrUseCredentialsPermissions() {
2279 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2280 Manifest.permission.USE_CREDENTIALS);
2281 }
2282
Fred Quintanad9640ec2012-05-23 12:37:00 -07002283 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2284 throws RemoteException {
2285 final int callingUid = getCallingUid();
2286
2287 if (callingUid != android.os.Process.SYSTEM_UID) {
2288 throw new SecurityException();
2289 }
2290
2291 if (value) {
2292 grantAppPermission(account, authTokenType, uid);
2293 } else {
2294 revokeAppPermission(account, authTokenType, uid);
2295 }
2296 }
2297
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002298 /**
2299 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2300 * <p>
2301 * Although this is public it can only be accessed via the AccountManagerService object
2302 * which is in the system. This means we don't need to protect it with permissions.
2303 * @hide
2304 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002305 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002306 if (account == null || authTokenType == null) {
2307 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002308 return;
2309 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002310 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002311 synchronized (accounts.cacheLock) {
2312 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002313 db.beginTransaction();
2314 try {
2315 long accountId = getAccountIdLocked(db, account);
2316 if (accountId >= 0) {
2317 ContentValues values = new ContentValues();
2318 values.put(GRANTS_ACCOUNTS_ID, accountId);
2319 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2320 values.put(GRANTS_GRANTEE_UID, uid);
2321 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2322 db.setTransactionSuccessful();
2323 }
2324 } finally {
2325 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002326 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002327 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2328 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002329 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002330 }
2331
2332 /**
2333 * Don't allow callers with the given uid permission to get credentials for
2334 * account/authTokenType.
2335 * <p>
2336 * Although this is public it can only be accessed via the AccountManagerService object
2337 * which is in the system. This means we don't need to protect it with permissions.
2338 * @hide
2339 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002340 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002341 if (account == null || authTokenType == null) {
2342 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002343 return;
2344 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002345 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002346 synchronized (accounts.cacheLock) {
2347 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002348 db.beginTransaction();
2349 try {
2350 long accountId = getAccountIdLocked(db, account);
2351 if (accountId >= 0) {
2352 db.delete(TABLE_GRANTS,
2353 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2354 + GRANTS_GRANTEE_UID + "=?",
2355 new String[]{String.valueOf(accountId), authTokenType,
2356 String.valueOf(uid)});
2357 db.setTransactionSuccessful();
2358 }
2359 } finally {
2360 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002361 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002362 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2363 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002364 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002365 }
Fred Quintana56285a62010-12-02 14:20:51 -08002366
2367 static final private String stringArrayToString(String[] value) {
2368 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2369 }
2370
Amith Yamasani04e0d262012-02-14 11:50:53 -08002371 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2372 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002373 if (oldAccountsForType != null) {
2374 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2375 for (Account curAccount : oldAccountsForType) {
2376 if (!curAccount.equals(account)) {
2377 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002378 }
2379 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002380 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002381 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002382 } else {
2383 Account[] newAccountsForType = new Account[newAccountsList.size()];
2384 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002385 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002386 }
Fred Quintana56285a62010-12-02 14:20:51 -08002387 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002388 accounts.userDataCache.remove(account);
2389 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002390 }
2391
2392 /**
2393 * This assumes that the caller has already checked that the account is not already present.
2394 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002395 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2396 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002397 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2398 Account[] newAccountsForType = new Account[oldLength + 1];
2399 if (accountsForType != null) {
2400 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002401 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002402 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002403 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002404 }
2405
Amith Yamasani04e0d262012-02-14 11:50:53 -08002406 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002407 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002408 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002409 if (accounts == null) {
2410 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002411 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002412 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002413 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002414 } else {
2415 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002416 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002417 totalLength += accounts.length;
2418 }
2419 if (totalLength == 0) {
2420 return EMPTY_ACCOUNT_ARRAY;
2421 }
2422 Account[] accounts = new Account[totalLength];
2423 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002424 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002425 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2426 accountsOfType.length);
2427 totalLength += accountsOfType.length;
2428 }
2429 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002430 }
2431 }
2432
Amith Yamasani04e0d262012-02-14 11:50:53 -08002433 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2434 Account account, String key, String value) {
2435 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002436 if (userDataForAccount == null) {
2437 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002438 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002439 }
2440 if (value == null) {
2441 userDataForAccount.remove(key);
2442 } else {
2443 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002444 }
2445 }
2446
Amith Yamasani04e0d262012-02-14 11:50:53 -08002447 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2448 Account account, String key, String value) {
2449 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002450 if (authTokensForAccount == null) {
2451 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002452 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002453 }
2454 if (value == null) {
2455 authTokensForAccount.remove(key);
2456 } else {
2457 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002458 }
2459 }
2460
Amith Yamasani04e0d262012-02-14 11:50:53 -08002461 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2462 String authTokenType) {
2463 synchronized (accounts.cacheLock) {
2464 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002465 if (authTokensForAccount == null) {
2466 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002467 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002468 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002469 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002470 }
2471 return authTokensForAccount.get(authTokenType);
2472 }
2473 }
2474
Amith Yamasani04e0d262012-02-14 11:50:53 -08002475 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2476 synchronized (accounts.cacheLock) {
2477 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002478 if (userDataForAccount == null) {
2479 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002480 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002481 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002482 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002483 }
2484 return userDataForAccount.get(key);
2485 }
2486 }
2487
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002488 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2489 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002490 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002491 Cursor cursor = db.query(TABLE_EXTRAS,
2492 COLUMNS_EXTRAS_KEY_AND_VALUE,
2493 SELECTION_USERDATA_BY_ACCOUNT,
2494 new String[]{account.name, account.type},
2495 null, null, null);
2496 try {
2497 while (cursor.moveToNext()) {
2498 final String tmpkey = cursor.getString(0);
2499 final String value = cursor.getString(1);
2500 userDataForAccount.put(tmpkey, value);
2501 }
2502 } finally {
2503 cursor.close();
2504 }
2505 return userDataForAccount;
2506 }
2507
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002508 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2509 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002510 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002511 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2512 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2513 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2514 new String[]{account.name, account.type},
2515 null, null, null);
2516 try {
2517 while (cursor.moveToNext()) {
2518 final String type = cursor.getString(0);
2519 final String authToken = cursor.getString(1);
2520 authTokensForAccount.put(type, authToken);
2521 }
2522 } finally {
2523 cursor.close();
2524 }
2525 return authTokensForAccount;
2526 }
Fred Quintana60307342009-03-24 22:48:12 -07002527}