blob: 5009793da3faefe189a706344dbd5d43bf187dbb [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080020import android.accounts.Account;
21import android.accounts.AccountAndUser;
22import android.accounts.AccountAuthenticatorResponse;
23import android.accounts.AccountManager;
24import android.accounts.AuthenticatorDescription;
25import android.accounts.GrantCredentialsPermissionActivity;
26import android.accounts.IAccountAuthenticator;
27import android.accounts.IAccountAuthenticatorResponse;
28import android.accounts.IAccountManager;
29import android.accounts.IAccountManagerResponse;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080030import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070031import android.app.ActivityManagerNative;
Doug Zongker885cfc232009-10-21 16:52:44 -070032import android.app.Notification;
33import android.app.NotificationManager;
34import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070035import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070036import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070037import android.content.ContentValues;
38import android.content.Context;
39import android.content.Intent;
40import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070041import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070042import android.content.pm.ApplicationInfo;
43import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070044import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070045import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070046import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070047import android.content.pm.RegisteredServicesCacheListener;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070048import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070049import android.database.Cursor;
50import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070051import android.database.sqlite.SQLiteDatabase;
52import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070053import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070054import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080055import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070056import android.os.Handler;
57import android.os.HandlerThread;
58import android.os.IBinder;
59import android.os.Looper;
60import android.os.Message;
Amith Yamasani27db4682013-03-30 17:07:47 -070061import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import android.os.RemoteException;
63import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070064import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070065import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import android.text.TextUtils;
67import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070068import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070069import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080070import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070071
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070072import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080073import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080074import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070075import com.google.android.collect.Lists;
76import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070077
Oscar Montemayora8529f62009-11-18 10:14:20 -080078import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070079import java.io.FileDescriptor;
80import java.io.PrintWriter;
81import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080082import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070083import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070084import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070085import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080086import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070087import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080088import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070089import java.util.concurrent.atomic.AtomicInteger;
90import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070091
Fred Quintana60307342009-03-24 22:48:12 -070092/**
93 * A system service that provides account, password, and authtoken management for all
94 * accounts on the device. Some of these calls are implemented with the help of the corresponding
95 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
96 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070097 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -070098 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070099 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700100public class AccountManagerService
101 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800102 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700103 private static final String TAG = "AccountManagerService";
104
105 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
106 private static final String DATABASE_NAME = "accounts.db";
Amith Yamasani67df64b2012-12-14 12:09:36 -0800107 private static final int DATABASE_VERSION = 5;
Fred Quintana60307342009-03-24 22:48:12 -0700108
109 private final Context mContext;
110
Fred Quintana56285a62010-12-02 14:20:51 -0800111 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700112 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800113
Fred Quintana60307342009-03-24 22:48:12 -0700114 private HandlerThread mMessageThread;
115 private final MessageHandler mMessageHandler;
116
117 // Messages that can be sent on mHandler
118 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700119
Fred Quintana56285a62010-12-02 14:20:51 -0800120 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700121
122 private static final String TABLE_ACCOUNTS = "accounts";
123 private static final String ACCOUNTS_ID = "_id";
124 private static final String ACCOUNTS_NAME = "name";
125 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700126 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700127 private static final String ACCOUNTS_PASSWORD = "password";
128
129 private static final String TABLE_AUTHTOKENS = "authtokens";
130 private static final String AUTHTOKENS_ID = "_id";
131 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
132 private static final String AUTHTOKENS_TYPE = "type";
133 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
134
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700135 private static final String TABLE_GRANTS = "grants";
136 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
137 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
138 private static final String GRANTS_GRANTEE_UID = "uid";
139
Fred Quintana60307342009-03-24 22:48:12 -0700140 private static final String TABLE_EXTRAS = "extras";
141 private static final String EXTRAS_ID = "_id";
142 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
143 private static final String EXTRAS_KEY = "key";
144 private static final String EXTRAS_VALUE = "value";
145
146 private static final String TABLE_META = "meta";
147 private static final String META_KEY = "key";
148 private static final String META_VALUE = "value";
149
Amith Yamasani67df64b2012-12-14 12:09:36 -0800150 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
151
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700152 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
153 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700154 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700155
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700156 private static final String COUNT_OF_MATCHING_GRANTS = ""
157 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
158 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
159 + " AND " + GRANTS_GRANTEE_UID + "=?"
160 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
161 + " AND " + ACCOUNTS_NAME + "=?"
162 + " AND " + ACCOUNTS_TYPE + "=?";
163
Fred Quintana56285a62010-12-02 14:20:51 -0800164 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
165 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
166 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
167 AUTHTOKENS_AUTHTOKEN};
168
169 private static final String SELECTION_USERDATA_BY_ACCOUNT =
170 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
171 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
172
Fred Quintanaa698f422009-04-08 19:14:54 -0700173 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700174 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
175
Amith Yamasani04e0d262012-02-14 11:50:53 -0800176 static class UserAccounts {
177 private final int userId;
178 private final DatabaseHelper openHelper;
179 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
180 credentialsPermissionNotificationIds =
181 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
182 private final HashMap<Account, Integer> signinRequiredNotificationIds =
183 new HashMap<Account, Integer>();
184 private final Object cacheLock = new Object();
185 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700186 private final HashMap<String, Account[]> accountCache =
187 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800188 /** protected by the {@link #cacheLock} */
189 private HashMap<Account, HashMap<String, String>> userDataCache =
190 new HashMap<Account, HashMap<String, String>>();
191 /** protected by the {@link #cacheLock} */
192 private HashMap<Account, HashMap<String, String>> authTokenCache =
193 new HashMap<Account, HashMap<String, String>>();
194
195 UserAccounts(Context context, int userId) {
196 this.userId = userId;
197 synchronized (cacheLock) {
198 openHelper = new DatabaseHelper(context, userId);
199 }
200 }
201 }
202
203 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
204
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700205 private static AtomicReference<AccountManagerService> sThis =
206 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700207 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700208
209 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700210 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700211 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
212 }
213
Fred Quintana56285a62010-12-02 14:20:51 -0800214
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700215 /**
216 * This should only be called by system code. One should only call this after the service
217 * has started.
218 * @return a reference to the AccountManagerService instance
219 * @hide
220 */
221 public static AccountManagerService getSingleton() {
222 return sThis.get();
223 }
Fred Quintana60307342009-03-24 22:48:12 -0700224
Fred Quintana56285a62010-12-02 14:20:51 -0800225 public AccountManagerService(Context context) {
226 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700227 }
228
Fred Quintana56285a62010-12-02 14:20:51 -0800229 public AccountManagerService(Context context, PackageManager packageManager,
230 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700231 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800232 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700233
Fred Quintana60307342009-03-24 22:48:12 -0700234 mMessageThread = new HandlerThread("AccountManagerService");
235 mMessageThread.start();
236 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
237
Fred Quintana56285a62010-12-02 14:20:51 -0800238 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800239 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700240
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700241 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800242
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800243 IntentFilter intentFilter = new IntentFilter();
244 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
245 intentFilter.addDataScheme("package");
246 mContext.registerReceiver(new BroadcastReceiver() {
247 @Override
248 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800249 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800250 }
251 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800252
Amith Yamasani13593602012-03-22 16:16:17 -0700253 IntentFilter userFilter = new IntentFilter();
254 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800255 userFilter.addAction(Intent.ACTION_USER_STARTED);
256 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700257 @Override
258 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800259 String action = intent.getAction();
260 if (Intent.ACTION_USER_REMOVED.equals(action)) {
261 onUserRemoved(intent);
262 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
263 onUserStarted(intent);
264 }
Amith Yamasani13593602012-03-22 16:16:17 -0700265 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800266 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800267 }
268
Kenny Root26ff6622012-07-30 12:58:03 -0700269 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700270 }
271
Amith Yamasani258848d2012-08-10 17:06:33 -0700272 private UserManager getUserManager() {
273 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700274 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700275 }
276 return mUserManager;
277 }
278
Amith Yamasani04e0d262012-02-14 11:50:53 -0800279 private UserAccounts initUser(int userId) {
280 synchronized (mUsers) {
281 UserAccounts accounts = mUsers.get(userId);
282 if (accounts == null) {
283 accounts = new UserAccounts(mContext, userId);
284 mUsers.append(userId, accounts);
285 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700286 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800287 }
288 return accounts;
289 }
290 }
291
292 private void purgeOldGrantsAll() {
293 synchronized (mUsers) {
294 for (int i = 0; i < mUsers.size(); i++) {
295 purgeOldGrants(mUsers.valueAt(i));
296 }
297 }
298 }
299
300 private void purgeOldGrants(UserAccounts accounts) {
301 synchronized (accounts.cacheLock) {
302 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800303 final Cursor cursor = db.query(TABLE_GRANTS,
304 new String[]{GRANTS_GRANTEE_UID},
305 null, null, GRANTS_GRANTEE_UID, null, null);
306 try {
307 while (cursor.moveToNext()) {
308 final int uid = cursor.getInt(0);
309 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
310 if (packageExists) {
311 continue;
312 }
313 Log.d(TAG, "deleting grants for UID " + uid
314 + " because its package is no longer installed");
315 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
316 new String[]{Integer.toString(uid)});
317 }
318 } finally {
319 cursor.close();
320 }
321 }
322 }
323
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700324 /**
325 * Validate internal set of accounts against installed authenticators for
326 * given user. Clears cached authenticators before validating.
327 */
328 public void validateAccounts(int userId) {
329 final UserAccounts accounts = getUserAccounts(userId);
330
331 // Invalidate user-specific cache to make sure we catch any
332 // removed authenticators.
333 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
334 }
335
336 /**
337 * Validate internal set of accounts against installed authenticators for
338 * given user. Clear cached authenticators before validating when requested.
339 */
340 private void validateAccountsInternal(
341 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
342 if (invalidateAuthenticatorCache) {
343 mAuthenticatorCache.invalidateCache(accounts.userId);
344 }
345
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700346 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
347 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
348 mAuthenticatorCache.getAllServices(accounts.userId)) {
349 knownAuth.add(service.type);
350 }
351
Amith Yamasani04e0d262012-02-14 11:50:53 -0800352 synchronized (accounts.cacheLock) {
353 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800354 boolean accountDeleted = false;
355 Cursor cursor = db.query(TABLE_ACCOUNTS,
356 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
357 null, null, null, null, null);
358 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800359 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800360 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700361 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800362 while (cursor.moveToNext()) {
363 final long accountId = cursor.getLong(0);
364 final String accountType = cursor.getString(1);
365 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700366
367 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700368 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800369 + accountType + " no longer has a registered authenticator");
370 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
371 accountDeleted = true;
372 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800373 accounts.userDataCache.remove(account);
374 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800375 } else {
376 ArrayList<String> accountNames = accountNamesByType.get(accountType);
377 if (accountNames == null) {
378 accountNames = new ArrayList<String>();
379 accountNamesByType.put(accountType, accountNames);
380 }
381 accountNames.add(accountName);
382 }
383 }
Andy McFadden2f362292012-01-20 14:43:38 -0800384 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800385 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800386 final String accountType = cur.getKey();
387 final ArrayList<String> accountNames = cur.getValue();
388 final Account[] accountsForType = new Account[accountNames.size()];
389 int i = 0;
390 for (String accountName : accountNames) {
391 accountsForType[i] = new Account(accountName, accountType);
392 ++i;
393 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800394 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800395 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800396 } finally {
397 cursor.close();
398 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800399 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800400 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800401 }
402 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700403 }
404
Amith Yamasani04e0d262012-02-14 11:50:53 -0800405 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700406 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800407 }
408
409 protected UserAccounts getUserAccounts(int userId) {
410 synchronized (mUsers) {
411 UserAccounts accounts = mUsers.get(userId);
412 if (accounts == null) {
413 accounts = initUser(userId);
414 mUsers.append(userId, accounts);
415 }
416 return accounts;
417 }
418 }
419
Amith Yamasani13593602012-03-22 16:16:17 -0700420 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700421 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700422 if (userId < 1) return;
423
424 UserAccounts accounts;
425 synchronized (mUsers) {
426 accounts = mUsers.get(userId);
427 mUsers.remove(userId);
428 }
429 if (accounts == null) {
430 File dbFile = new File(getDatabaseName(userId));
431 dbFile.delete();
432 return;
433 }
434
435 synchronized (accounts.cacheLock) {
436 accounts.openHelper.close();
437 File dbFile = new File(getDatabaseName(userId));
438 dbFile.delete();
439 }
440 }
441
Amith Yamasani67df64b2012-12-14 12:09:36 -0800442 private void onUserStarted(Intent intent) {
443 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
444 if (userId < 1) return;
445
446 // Check if there's a shared account that needs to be created as an account
447 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
448 if (sharedAccounts == null || sharedAccounts.length == 0) return;
449 Account[] accounts = getAccountsAsUser(null, userId);
450 for (Account sa : sharedAccounts) {
451 if (ArrayUtils.contains(accounts, sa)) continue;
452 // Account doesn't exist. Copy it now.
453 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
454 }
455 }
456
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700457 @Override
458 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700459 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700460 }
461
Fred Quintanaa698f422009-04-08 19:14:54 -0700462 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800463 if (Log.isLoggable(TAG, Log.VERBOSE)) {
464 Log.v(TAG, "getPassword: " + account
465 + ", caller's uid " + Binder.getCallingUid()
466 + ", pid " + Binder.getCallingPid());
467 }
Fred Quintana382601f2010-03-25 12:25:10 -0700468 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700469 checkAuthenticateAccountsPermission(account);
470
Amith Yamasani04e0d262012-02-14 11:50:53 -0800471 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700472 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700473 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800474 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700475 } finally {
476 restoreCallingIdentity(identityToken);
477 }
478 }
479
Amith Yamasani04e0d262012-02-14 11:50:53 -0800480 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700481 if (account == null) {
482 return null;
483 }
484
Amith Yamasani04e0d262012-02-14 11:50:53 -0800485 synchronized (accounts.cacheLock) {
486 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800487 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
488 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
489 new String[]{account.name, account.type}, null, null, null);
490 try {
491 if (cursor.moveToNext()) {
492 return cursor.getString(0);
493 }
494 return null;
495 } finally {
496 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700497 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700498 }
499 }
500
501 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800502 if (Log.isLoggable(TAG, Log.VERBOSE)) {
503 Log.v(TAG, "getUserData: " + account
504 + ", key " + key
505 + ", caller's uid " + Binder.getCallingUid()
506 + ", pid " + Binder.getCallingPid());
507 }
Fred Quintana382601f2010-03-25 12:25:10 -0700508 if (account == null) throw new IllegalArgumentException("account is null");
509 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700510 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800511 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700512 long identityToken = clearCallingIdentity();
513 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800514 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 } finally {
516 restoreCallingIdentity(identityToken);
517 }
518 }
519
Fred Quintana97889762009-06-15 12:29:24 -0700520 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800521 if (Log.isLoggable(TAG, Log.VERBOSE)) {
522 Log.v(TAG, "getAuthenticatorTypes: "
523 + "caller's uid " + Binder.getCallingUid()
524 + ", pid " + Binder.getCallingPid());
525 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700526 final int userId = UserHandle.getCallingUserId();
527 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700528 try {
Fred Quintana97889762009-06-15 12:29:24 -0700529 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700530 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700531 AuthenticatorDescription[] types =
532 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700533 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700534 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700535 : authenticatorCollection) {
536 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700537 i++;
538 }
539 return types;
540 } finally {
541 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700542 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700543 }
544
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700545 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700546 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800547 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700548 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800549 + ", caller's uid " + Binder.getCallingUid()
550 + ", pid " + Binder.getCallingPid());
551 }
Fred Quintana382601f2010-03-25 12:25:10 -0700552 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700553 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700554 /*
555 * Child users are not allowed to add accounts. Only the accounts that are
556 * shared by the parent profile can be added to child profile.
557 *
558 * TODO: Only allow accounts that were shared to be added by
559 * a limited user.
560 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700561
Amith Yamasani04e0d262012-02-14 11:50:53 -0800562 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700563 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700564 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700565 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800566 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700567 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700568 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700569 }
570 }
571
Amith Yamasani67df64b2012-12-14 12:09:36 -0800572 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
573 final UserAccounts fromAccounts = getUserAccounts(userFrom);
574 final UserAccounts toAccounts = getUserAccounts(userTo);
575 if (fromAccounts == null || toAccounts == null) {
576 return false;
577 }
578
579 long identityToken = clearCallingIdentity();
580 try {
581 new Session(fromAccounts, null, account.type, false,
582 false /* stripAuthTokenFromResult */) {
583 protected String toDebugString(long now) {
584 return super.toDebugString(now) + ", getAccountCredentialsForClone"
585 + ", " + account.type;
586 }
587
588 public void run() throws RemoteException {
589 mAuthenticator.getAccountCredentialsForCloning(this, account);
590 }
591
592 public void onResult(Bundle result) {
593 if (result != null) {
594 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
595 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800596 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800597 }
598 return;
599 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800600 super.onResult(result);
601 }
602 }
603 }.bind();
604 } finally {
605 restoreCallingIdentity(identityToken);
606 }
607 return true;
608 }
609
Amith Yamasani67df64b2012-12-14 12:09:36 -0800610 void completeCloningAccount(final Bundle result, final Account account,
611 final UserAccounts targetUser) {
612 long id = clearCallingIdentity();
613 try {
614 new Session(targetUser, null, account.type, false,
615 false /* stripAuthTokenFromResult */) {
616 protected String toDebugString(long now) {
617 return super.toDebugString(now) + ", getAccountCredentialsForClone"
618 + ", " + account.type;
619 }
620
621 public void run() throws RemoteException {
622 mAuthenticator.addAccountFromCredentials(this, account, result);
623 }
624
625 public void onResult(Bundle result) {
626 if (result != null) {
627 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
628 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800629 } else {
630 // TODO: Show error notification
631 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800632 }
633 return;
634 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800635 super.onResult(result);
636 }
637 }
638
639 public void onError(int errorCode, String errorMessage) {
640 super.onError(errorCode, errorMessage);
641 // TODO: Show error notification to user
642 // TODO: Should we remove the shadow account so that it doesn't keep trying?
643 }
644
645 }.bind();
646 } finally {
647 restoreCallingIdentity(id);
648 }
649 }
650
Amith Yamasani04e0d262012-02-14 11:50:53 -0800651 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800652 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700653 if (account == null) {
654 return false;
655 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800656 synchronized (accounts.cacheLock) {
657 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800658 db.beginTransaction();
659 try {
660 long numMatches = DatabaseUtils.longForQuery(db,
661 "select count(*) from " + TABLE_ACCOUNTS
662 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
663 new String[]{account.name, account.type});
664 if (numMatches > 0) {
665 Log.w(TAG, "insertAccountIntoDatabase: " + account
666 + ", skipping since the account already exists");
667 return false;
668 }
669 ContentValues values = new ContentValues();
670 values.put(ACCOUNTS_NAME, account.name);
671 values.put(ACCOUNTS_TYPE, account.type);
672 values.put(ACCOUNTS_PASSWORD, password);
673 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
674 if (accountId < 0) {
675 Log.w(TAG, "insertAccountIntoDatabase: " + account
676 + ", skipping the DB insert failed");
677 return false;
678 }
679 if (extras != null) {
680 for (String key : extras.keySet()) {
681 final String value = extras.getString(key);
682 if (insertExtraLocked(db, accountId, key, value) < 0) {
683 Log.w(TAG, "insertAccountIntoDatabase: " + account
684 + ", skipping since insertExtra failed for key " + key);
685 return false;
686 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700687 }
688 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800689 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800690 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800691 } finally {
692 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700693 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800694 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800695 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700696 }
697 }
698
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800699 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700700 ContentValues values = new ContentValues();
701 values.put(EXTRAS_KEY, key);
702 values.put(EXTRAS_ACCOUNTS_ID, accountId);
703 values.put(EXTRAS_VALUE, value);
704 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
705 }
706
Fred Quintana3084a6f2010-01-14 18:02:03 -0800707 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800708 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800709 if (Log.isLoggable(TAG, Log.VERBOSE)) {
710 Log.v(TAG, "hasFeatures: " + account
711 + ", response " + response
712 + ", features " + stringArrayToString(features)
713 + ", caller's uid " + Binder.getCallingUid()
714 + ", pid " + Binder.getCallingPid());
715 }
Fred Quintana382601f2010-03-25 12:25:10 -0700716 if (response == null) throw new IllegalArgumentException("response is null");
717 if (account == null) throw new IllegalArgumentException("account is null");
718 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800719 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800720 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800721 long identityToken = clearCallingIdentity();
722 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800723 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800724 } finally {
725 restoreCallingIdentity(identityToken);
726 }
727 }
728
729 private class TestFeaturesSession extends Session {
730 private final String[] mFeatures;
731 private final Account mAccount;
732
Amith Yamasani04e0d262012-02-14 11:50:53 -0800733 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800734 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800735 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800736 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800737 mFeatures = features;
738 mAccount = account;
739 }
740
741 public void run() throws RemoteException {
742 try {
743 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
744 } catch (RemoteException e) {
745 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
746 }
747 }
748
749 public void onResult(Bundle result) {
750 IAccountManagerResponse response = getResponseAndClose();
751 if (response != null) {
752 try {
753 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700754 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800755 return;
756 }
Fred Quintana56285a62010-12-02 14:20:51 -0800757 if (Log.isLoggable(TAG, Log.VERBOSE)) {
758 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
759 + response);
760 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800761 final Bundle newResult = new Bundle();
762 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
763 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
764 response.onResult(newResult);
765 } catch (RemoteException e) {
766 // if the caller is dead then there is no one to care about remote exceptions
767 if (Log.isLoggable(TAG, Log.VERBOSE)) {
768 Log.v(TAG, "failure while notifying response", e);
769 }
770 }
771 }
772 }
773
774 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800775 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800776 + ", " + mAccount
777 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
778 }
779 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800780
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700781 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800782 if (Log.isLoggable(TAG, Log.VERBOSE)) {
783 Log.v(TAG, "removeAccount: " + account
784 + ", response " + response
785 + ", caller's uid " + Binder.getCallingUid()
786 + ", pid " + Binder.getCallingPid());
787 }
Fred Quintana382601f2010-03-25 12:25:10 -0700788 if (response == null) throw new IllegalArgumentException("response is null");
789 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700790 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700791 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800792 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800793 if (!canUserModifyAccounts(Binder.getCallingUid())) {
794 try {
795 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
796 "User cannot modify accounts");
797 } catch (RemoteException re) {
798 }
799 }
800
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700801 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800802
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700803 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800804 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800805 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800806 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800807 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800808 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700809 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800810 }
811 }
812 }
813
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700814 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800815 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700816 } finally {
817 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700818 }
Fred Quintana60307342009-03-24 22:48:12 -0700819 }
820
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700821 private class RemoveAccountSession extends Session {
822 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800823 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
824 Account account) {
825 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800826 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700827 mAccount = account;
828 }
829
830 protected String toDebugString(long now) {
831 return super.toDebugString(now) + ", removeAccount"
832 + ", account " + mAccount;
833 }
834
835 public void run() throws RemoteException {
836 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
837 }
838
839 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700840 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
841 && !result.containsKey(AccountManager.KEY_INTENT)) {
842 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700843 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800844 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700845 }
846 IAccountManagerResponse response = getResponseAndClose();
847 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800848 if (Log.isLoggable(TAG, Log.VERBOSE)) {
849 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
850 + response);
851 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700852 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700853 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700854 try {
855 response.onResult(result2);
856 } catch (RemoteException e) {
857 // ignore
858 }
859 }
860 }
861 super.onResult(result);
862 }
863 }
864
Amith Yamasani04e0d262012-02-14 11:50:53 -0800865 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800866 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800867 removeAccountInternal(getUserAccountsForCaller(), account);
868 }
869
870 private void removeAccountInternal(UserAccounts accounts, Account account) {
871 synchronized (accounts.cacheLock) {
872 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800873 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
874 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800875 removeAccountFromCacheLocked(accounts, account);
876 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800877 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800878 if (accounts.userId == UserHandle.USER_OWNER) {
879 // Owner's account was removed, remove from any users that are sharing
880 // this account.
881 long id = Binder.clearCallingIdentity();
882 try {
883 List<UserInfo> users = mUserManager.getUsers(true);
884 for (UserInfo user : users) {
885 if (!user.isPrimary() && user.isRestricted()) {
886 removeSharedAccountAsUser(account, user.id);
887 }
888 }
889 } finally {
890 Binder.restoreCallingIdentity(id);
891 }
892 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700893 }
894
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400895 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700896 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800897 if (Log.isLoggable(TAG, Log.VERBOSE)) {
898 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
899 + ", caller's uid " + Binder.getCallingUid()
900 + ", pid " + Binder.getCallingPid());
901 }
Fred Quintana382601f2010-03-25 12:25:10 -0700902 if (accountType == null) throw new IllegalArgumentException("accountType is null");
903 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800904 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800905 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700906 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700907 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800908 synchronized (accounts.cacheLock) {
909 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800910 db.beginTransaction();
911 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800912 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800913 db.setTransactionSuccessful();
914 } finally {
915 db.endTransaction();
916 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700917 }
Fred Quintana60307342009-03-24 22:48:12 -0700918 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700919 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700920 }
921 }
922
Amith Yamasani04e0d262012-02-14 11:50:53 -0800923 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
924 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700925 if (authToken == null || accountType == null) {
926 return;
927 }
Fred Quintana33269202009-04-20 16:05:10 -0700928 Cursor cursor = db.rawQuery(
929 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
930 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
931 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
932 + " FROM " + TABLE_ACCOUNTS
933 + " JOIN " + TABLE_AUTHTOKENS
934 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
935 + " = " + AUTHTOKENS_ACCOUNTS_ID
936 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
937 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
938 new String[]{authToken, accountType});
939 try {
940 while (cursor.moveToNext()) {
941 long authTokenId = cursor.getLong(0);
942 String accountName = cursor.getString(1);
943 String authTokenType = cursor.getString(2);
944 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800945 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800946 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700947 }
Fred Quintana33269202009-04-20 16:05:10 -0700948 } finally {
949 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700950 }
951 }
952
Amith Yamasani04e0d262012-02-14 11:50:53 -0800953 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
954 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700955 if (account == null || type == null) {
956 return false;
957 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700958 cancelNotification(getSigninRequiredNotificationId(accounts, account),
959 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800960 synchronized (accounts.cacheLock) {
961 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800962 db.beginTransaction();
963 try {
964 long accountId = getAccountIdLocked(db, account);
965 if (accountId < 0) {
966 return false;
967 }
968 db.delete(TABLE_AUTHTOKENS,
969 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
970 new String[]{type});
971 ContentValues values = new ContentValues();
972 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
973 values.put(AUTHTOKENS_TYPE, type);
974 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
975 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
976 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800977 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800978 return true;
979 }
Fred Quintana33269202009-04-20 16:05:10 -0700980 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800981 } finally {
982 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -0700983 }
Fred Quintana60307342009-03-24 22:48:12 -0700984 }
985 }
986
Fred Quintanaa698f422009-04-08 19:14:54 -0700987 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800988 if (Log.isLoggable(TAG, Log.VERBOSE)) {
989 Log.v(TAG, "peekAuthToken: " + account
990 + ", authTokenType " + authTokenType
991 + ", caller's uid " + Binder.getCallingUid()
992 + ", pid " + Binder.getCallingPid());
993 }
Fred Quintana382601f2010-03-25 12:25:10 -0700994 if (account == null) throw new IllegalArgumentException("account is null");
995 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700996 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800997 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700998 long identityToken = clearCallingIdentity();
999 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001000 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001001 } finally {
1002 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001003 }
Fred Quintana60307342009-03-24 22:48:12 -07001004 }
1005
Fred Quintanaa698f422009-04-08 19:14:54 -07001006 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001007 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1008 Log.v(TAG, "setAuthToken: " + account
1009 + ", authTokenType " + authTokenType
1010 + ", caller's uid " + Binder.getCallingUid()
1011 + ", pid " + Binder.getCallingPid());
1012 }
Fred Quintana382601f2010-03-25 12:25:10 -07001013 if (account == null) throw new IllegalArgumentException("account is null");
1014 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001015 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001016 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001017 long identityToken = clearCallingIdentity();
1018 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001019 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001020 } finally {
1021 restoreCallingIdentity(identityToken);
1022 }
Fred Quintana60307342009-03-24 22:48:12 -07001023 }
1024
Fred Quintanaa698f422009-04-08 19:14:54 -07001025 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001026 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1027 Log.v(TAG, "setAuthToken: " + account
1028 + ", caller's uid " + Binder.getCallingUid()
1029 + ", pid " + Binder.getCallingPid());
1030 }
Fred Quintana382601f2010-03-25 12:25:10 -07001031 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001032 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001033 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001034 long identityToken = clearCallingIdentity();
1035 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001036 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001037 } finally {
1038 restoreCallingIdentity(identityToken);
1039 }
Fred Quintana60307342009-03-24 22:48:12 -07001040 }
1041
Amith Yamasani04e0d262012-02-14 11:50:53 -08001042 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001043 if (account == null) {
1044 return;
1045 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001046 synchronized (accounts.cacheLock) {
1047 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001048 db.beginTransaction();
1049 try {
1050 final ContentValues values = new ContentValues();
1051 values.put(ACCOUNTS_PASSWORD, password);
1052 final long accountId = getAccountIdLocked(db, account);
1053 if (accountId >= 0) {
1054 final String[] argsAccountId = {String.valueOf(accountId)};
1055 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1056 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001057 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001058 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001059 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001060 } finally {
1061 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001062 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001063 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001064 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001065 }
1066
Amith Yamasani04e0d262012-02-14 11:50:53 -08001067 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001068 Log.i(TAG, "the accounts changed, sending broadcast of "
1069 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001070 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001071 }
1072
Fred Quintanaa698f422009-04-08 19:14:54 -07001073 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001074 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1075 Log.v(TAG, "clearPassword: " + account
1076 + ", caller's uid " + Binder.getCallingUid()
1077 + ", pid " + Binder.getCallingPid());
1078 }
Fred Quintana382601f2010-03-25 12:25:10 -07001079 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001080 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001081 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001082 long identityToken = clearCallingIdentity();
1083 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001084 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001085 } finally {
1086 restoreCallingIdentity(identityToken);
1087 }
Fred Quintana60307342009-03-24 22:48:12 -07001088 }
1089
Fred Quintanaa698f422009-04-08 19:14:54 -07001090 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001091 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1092 Log.v(TAG, "setUserData: " + account
1093 + ", key " + key
1094 + ", caller's uid " + Binder.getCallingUid()
1095 + ", pid " + Binder.getCallingPid());
1096 }
Fred Quintana382601f2010-03-25 12:25:10 -07001097 if (key == null) throw new IllegalArgumentException("key is null");
1098 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001099 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001100 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001101 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001102 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001103 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001104 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001105 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001106 }
1107 }
1108
Amith Yamasani04e0d262012-02-14 11:50:53 -08001109 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1110 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001111 if (account == null || key == null) {
1112 return;
1113 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001114 synchronized (accounts.cacheLock) {
1115 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001116 db.beginTransaction();
1117 try {
1118 long accountId = getAccountIdLocked(db, account);
1119 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001120 return;
1121 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001122 long extrasId = getExtrasIdLocked(db, accountId, key);
1123 if (extrasId < 0 ) {
1124 extrasId = insertExtraLocked(db, accountId, key, value);
1125 if (extrasId < 0) {
1126 return;
1127 }
1128 } else {
1129 ContentValues values = new ContentValues();
1130 values.put(EXTRAS_VALUE, value);
1131 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1132 return;
1133 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001134
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001135 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001136 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001137 db.setTransactionSuccessful();
1138 } finally {
1139 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001140 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001141 }
1142 }
1143
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001144 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001145 if (result == null) {
1146 Log.e(TAG, "the result is unexpectedly null", new Exception());
1147 }
1148 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1149 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1150 + response);
1151 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001152 try {
1153 response.onResult(result);
1154 } catch (RemoteException e) {
1155 // if the caller is dead then there is no one to care about remote
1156 // exceptions
1157 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1158 Log.v(TAG, "failure while notifying response", e);
1159 }
1160 }
1161 }
1162
Fred Quintanad9640ec2012-05-23 12:37:00 -07001163 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1164 final String authTokenType)
1165 throws RemoteException {
1166 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001167 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1168
Fred Quintanad9640ec2012-05-23 12:37:00 -07001169 final int callingUid = getCallingUid();
1170 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001171 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001172 throw new SecurityException("can only call from system");
1173 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001174 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001175 long identityToken = clearCallingIdentity();
1176 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001177 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001178 false /* stripAuthTokenFromResult */) {
1179 protected String toDebugString(long now) {
1180 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001181 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001182 + ", authTokenType " + authTokenType;
1183 }
1184
1185 public void run() throws RemoteException {
1186 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1187 }
1188
1189 public void onResult(Bundle result) {
1190 if (result != null) {
1191 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1192 Bundle bundle = new Bundle();
1193 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1194 super.onResult(bundle);
1195 return;
1196 } else {
1197 super.onResult(result);
1198 }
1199 }
1200 }.bind();
1201 } finally {
1202 restoreCallingIdentity(identityToken);
1203 }
1204 }
1205
Fred Quintanaa698f422009-04-08 19:14:54 -07001206 public void getAuthToken(IAccountManagerResponse response, final Account account,
1207 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001208 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001209 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1210 Log.v(TAG, "getAuthToken: " + account
1211 + ", response " + response
1212 + ", authTokenType " + authTokenType
1213 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1214 + ", expectActivityLaunch " + expectActivityLaunch
1215 + ", caller's uid " + Binder.getCallingUid()
1216 + ", pid " + Binder.getCallingPid());
1217 }
Fred Quintana382601f2010-03-25 12:25:10 -07001218 if (response == null) throw new IllegalArgumentException("response is null");
1219 if (account == null) throw new IllegalArgumentException("account is null");
1220 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001221 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001222 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001223 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1224 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1225 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001226 final boolean customTokens =
1227 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1228
1229 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001230 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001231 final boolean permissionGranted = customTokens ||
1232 permissionIsGranted(account, authTokenType, callerUid);
1233
Costin Manolachec6684f92011-01-14 11:25:39 -08001234 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1235 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001236 // let authenticator know the identity of the caller
1237 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1238 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1239 if (notifyOnAuthFailure) {
1240 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001241 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001242
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001243 long identityToken = clearCallingIdentity();
1244 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001245 // if the caller has permission, do the peek. otherwise go the more expensive
1246 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001247 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001248 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001249 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001250 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001251 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1252 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1253 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001254 onResult(response, result);
1255 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001256 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001257 }
1258
Amith Yamasani04e0d262012-02-14 11:50:53 -08001259 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001260 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001261 protected String toDebugString(long now) {
1262 if (loginOptions != null) loginOptions.keySet();
1263 return super.toDebugString(now) + ", getAuthToken"
1264 + ", " + account
1265 + ", authTokenType " + authTokenType
1266 + ", loginOptions " + loginOptions
1267 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1268 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001269
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001270 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001271 // If the caller doesn't have permission then create and return the
1272 // "grant permission" intent instead of the "getAuthToken" intent.
1273 if (!permissionGranted) {
1274 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1275 } else {
1276 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1277 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001278 }
1279
1280 public void onResult(Bundle result) {
1281 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001282 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001283 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1284 new AccountAuthenticatorResponse(this),
1285 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001286 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001287 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001288 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001289 onResult(bundle);
1290 return;
1291 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001292 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001293 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001294 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1295 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001296 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001297 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001298 "the type and name should not be empty");
1299 return;
1300 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001301 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001302 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001303 authTokenType, authToken);
1304 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001305 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001306
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001307 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001308 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001309 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001310 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001311 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001312 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001313 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001314 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001315 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001316 }.bind();
1317 } finally {
1318 restoreCallingIdentity(identityToken);
1319 }
Fred Quintana60307342009-03-24 22:48:12 -07001320 }
1321
Dianne Hackborn41203752012-08-31 14:05:51 -07001322 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1323 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001324 int uid = intent.getIntExtra(
1325 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1326 String authTokenType = intent.getStringExtra(
1327 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1328 String authTokenLabel = intent.getStringExtra(
1329 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1330
1331 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1332 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001333 final String titleAndSubtitle =
1334 mContext.getString(R.string.permission_request_notification_with_subtitle,
1335 account.name);
1336 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001337 String title = titleAndSubtitle;
1338 String subtitle = "";
1339 if (index > 0) {
1340 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001341 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001342 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001343 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001344 n.setLatestEventInfo(mContext, title, subtitle,
1345 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001346 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1347 installNotification(getCredentialPermissionNotificationId(
1348 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001349 }
1350
Costin Manolache5f383ad92010-12-02 16:44:46 -08001351 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1352 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001353
1354 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001355 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001356 // Since it was set in Eclair+ we can't change it without breaking apps using
1357 // the intent from a non-Activity context.
1358 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001359 intent.addCategory(
1360 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001361
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001362 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001363 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1364 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001365 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001366
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001367 return intent;
1368 }
1369
1370 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1371 int uid) {
1372 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001373 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001374 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001375 final Pair<Pair<Account, String>, Integer> key =
1376 new Pair<Pair<Account, String>, Integer>(
1377 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001378 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001379 if (id == null) {
1380 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001381 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001382 }
1383 }
1384 return id;
1385 }
1386
Amith Yamasani04e0d262012-02-14 11:50:53 -08001387 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001388 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001389 synchronized (accounts.signinRequiredNotificationIds) {
1390 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001391 if (id == null) {
1392 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001393 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001394 }
1395 }
1396 return id;
1397 }
1398
Amith Yamasani27db4682013-03-30 17:07:47 -07001399 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001400 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001401 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001402 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1403 Log.v(TAG, "addAccount: accountType " + accountType
1404 + ", response " + response
1405 + ", authTokenType " + authTokenType
1406 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1407 + ", expectActivityLaunch " + expectActivityLaunch
1408 + ", caller's uid " + Binder.getCallingUid()
1409 + ", pid " + Binder.getCallingPid());
1410 }
Fred Quintana382601f2010-03-25 12:25:10 -07001411 if (response == null) throw new IllegalArgumentException("response is null");
1412 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001413 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001414
Amith Yamasani71e6c692013-03-24 17:39:28 -07001415 // Is user disallowed from modifying accounts?
Amith Yamasani27db4682013-03-30 17:07:47 -07001416 if (!canUserModifyAccounts(Binder.getCallingUid())) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001417 try {
1418 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1419 "User is not allowed to add an account!");
1420 } catch (RemoteException re) {
1421 }
1422 return;
1423 }
1424
Amith Yamasani04e0d262012-02-14 11:50:53 -08001425 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001426 final int pid = Binder.getCallingPid();
1427 final int uid = Binder.getCallingUid();
1428 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1429 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1430 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1431
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001432 long identityToken = clearCallingIdentity();
1433 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001434 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001435 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001436 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001437 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001438 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001439 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001440
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001441 protected String toDebugString(long now) {
1442 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001443 + ", accountType " + accountType
1444 + ", requiredFeatures "
1445 + (requiredFeatures != null
1446 ? TextUtils.join(",", requiredFeatures)
1447 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001448 }
1449 }.bind();
1450 } finally {
1451 restoreCallingIdentity(identityToken);
1452 }
Fred Quintana60307342009-03-24 22:48:12 -07001453 }
1454
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001455 @Override
1456 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1457 final Account account, final Bundle options, final boolean expectActivityLaunch,
1458 int userId) {
1459 // Only allow the system process to read accounts of other users
1460 if (userId != UserHandle.getCallingUserId()
Amith Yamasani27db4682013-03-30 17:07:47 -07001461 && Binder.getCallingUid() != Process.myUid()) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001462 throw new SecurityException("User " + UserHandle.getCallingUserId()
1463 + " trying to confirm account credentials for " + userId);
1464 }
1465
Fred Quintana56285a62010-12-02 14:20:51 -08001466 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1467 Log.v(TAG, "confirmCredentials: " + account
1468 + ", response " + response
1469 + ", expectActivityLaunch " + expectActivityLaunch
1470 + ", caller's uid " + Binder.getCallingUid()
1471 + ", pid " + Binder.getCallingPid());
1472 }
Fred Quintana382601f2010-03-25 12:25:10 -07001473 if (response == null) throw new IllegalArgumentException("response is null");
1474 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001475 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001476 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001477 long identityToken = clearCallingIdentity();
1478 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001479 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001480 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001481 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001482 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001483 }
1484 protected String toDebugString(long now) {
1485 return super.toDebugString(now) + ", confirmCredentials"
1486 + ", " + account;
1487 }
1488 }.bind();
1489 } finally {
1490 restoreCallingIdentity(identityToken);
1491 }
Fred Quintana60307342009-03-24 22:48:12 -07001492 }
1493
Fred Quintanaa698f422009-04-08 19:14:54 -07001494 public void updateCredentials(IAccountManagerResponse response, final Account account,
1495 final String authTokenType, final boolean expectActivityLaunch,
1496 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001497 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1498 Log.v(TAG, "updateCredentials: " + account
1499 + ", response " + response
1500 + ", authTokenType " + authTokenType
1501 + ", expectActivityLaunch " + expectActivityLaunch
1502 + ", caller's uid " + Binder.getCallingUid()
1503 + ", pid " + Binder.getCallingPid());
1504 }
Fred Quintana382601f2010-03-25 12:25:10 -07001505 if (response == null) throw new IllegalArgumentException("response is null");
1506 if (account == null) throw new IllegalArgumentException("account is null");
1507 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001508 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001509 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001510 long identityToken = clearCallingIdentity();
1511 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001512 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001513 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001514 public void run() throws RemoteException {
1515 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1516 }
1517 protected String toDebugString(long now) {
1518 if (loginOptions != null) loginOptions.keySet();
1519 return super.toDebugString(now) + ", updateCredentials"
1520 + ", " + account
1521 + ", authTokenType " + authTokenType
1522 + ", loginOptions " + loginOptions;
1523 }
1524 }.bind();
1525 } finally {
1526 restoreCallingIdentity(identityToken);
1527 }
Fred Quintana60307342009-03-24 22:48:12 -07001528 }
1529
Fred Quintanaa698f422009-04-08 19:14:54 -07001530 public void editProperties(IAccountManagerResponse response, final String accountType,
1531 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001532 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1533 Log.v(TAG, "editProperties: accountType " + accountType
1534 + ", response " + response
1535 + ", expectActivityLaunch " + expectActivityLaunch
1536 + ", caller's uid " + Binder.getCallingUid()
1537 + ", pid " + Binder.getCallingPid());
1538 }
Fred Quintana382601f2010-03-25 12:25:10 -07001539 if (response == null) throw new IllegalArgumentException("response is null");
1540 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001541 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001542 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001543 long identityToken = clearCallingIdentity();
1544 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001545 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001546 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001547 public void run() throws RemoteException {
1548 mAuthenticator.editProperties(this, mAccountType);
1549 }
1550 protected String toDebugString(long now) {
1551 return super.toDebugString(now) + ", editProperties"
1552 + ", accountType " + accountType;
1553 }
1554 }.bind();
1555 } finally {
1556 restoreCallingIdentity(identityToken);
1557 }
Fred Quintana60307342009-03-24 22:48:12 -07001558 }
1559
Fred Quintana33269202009-04-20 16:05:10 -07001560 private class GetAccountsByTypeAndFeatureSession extends Session {
1561 private final String[] mFeatures;
1562 private volatile Account[] mAccountsOfType = null;
1563 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1564 private volatile int mCurrentAccount = 0;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001565 private int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001566
Amith Yamasani04e0d262012-02-14 11:50:53 -08001567 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001568 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001569 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001570 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001571 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001572 mFeatures = features;
1573 }
1574
1575 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001576 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001577 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1578 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001579 }
Fred Quintana33269202009-04-20 16:05:10 -07001580 // check whether each account matches the requested features
1581 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1582 mCurrentAccount = 0;
1583
1584 checkAccount();
1585 }
1586
1587 public void checkAccount() {
1588 if (mCurrentAccount >= mAccountsOfType.length) {
1589 sendResult();
1590 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001591 }
Fred Quintana33269202009-04-20 16:05:10 -07001592
Fred Quintana29e94b82010-03-10 12:11:51 -08001593 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1594 if (accountAuthenticator == null) {
1595 // It is possible that the authenticator has died, which is indicated by
1596 // mAuthenticator being set to null. If this happens then just abort.
1597 // There is no need to send back a result or error in this case since
1598 // that already happened when mAuthenticator was cleared.
1599 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1600 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1601 + " connected to the authenticator, " + toDebugString());
1602 }
1603 return;
1604 }
Fred Quintana33269202009-04-20 16:05:10 -07001605 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001606 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001607 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001608 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001609 }
1610 }
1611
1612 public void onResult(Bundle result) {
1613 mNumResults++;
1614 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001615 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001616 return;
1617 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001618 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001619 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1620 }
1621 mCurrentAccount++;
1622 checkAccount();
1623 }
1624
1625 public void sendResult() {
1626 IAccountManagerResponse response = getResponseAndClose();
1627 if (response != null) {
1628 try {
1629 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1630 for (int i = 0; i < accounts.length; i++) {
1631 accounts[i] = mAccountsWithFeatures.get(i);
1632 }
Fred Quintana56285a62010-12-02 14:20:51 -08001633 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1634 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1635 + response);
1636 }
Fred Quintana33269202009-04-20 16:05:10 -07001637 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001638 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001639 response.onResult(result);
1640 } catch (RemoteException e) {
1641 // if the caller is dead then there is no one to care about remote exceptions
1642 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1643 Log.v(TAG, "failure while notifying response", e);
1644 }
1645 }
1646 }
1647 }
1648
1649
1650 protected String toDebugString(long now) {
1651 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1652 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1653 }
1654 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001655
Amith Yamasani04e0d262012-02-14 11:50:53 -08001656 /**
1657 * Returns the accounts for a specific user
1658 * @hide
1659 */
1660 public Account[] getAccounts(int userId) {
1661 checkReadAccountsPermission();
1662 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001663 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001664 long identityToken = clearCallingIdentity();
1665 try {
1666 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001667 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001668 }
1669 } finally {
1670 restoreCallingIdentity(identityToken);
1671 }
1672 }
1673
Amith Yamasanif29f2362012-04-05 18:29:52 -07001674 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001675 * Returns accounts for all running users.
1676 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001677 * @hide
1678 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001679 public AccountAndUser[] getRunningAccounts() {
1680 final int[] runningUserIds;
1681 try {
1682 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1683 } catch (RemoteException e) {
1684 // Running in system_server; should never happen
1685 throw new RuntimeException(e);
1686 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001687 return getAccounts(runningUserIds);
1688 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001689
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001690 /** {@hide} */
1691 public AccountAndUser[] getAllAccounts() {
1692 final List<UserInfo> users = getUserManager().getUsers();
1693 final int[] userIds = new int[users.size()];
1694 for (int i = 0; i < userIds.length; i++) {
1695 userIds[i] = users.get(i).id;
1696 }
1697 return getAccounts(userIds);
1698 }
1699
1700 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001701 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1702 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001703 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001704 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001705 if (userAccounts == null) continue;
1706 synchronized (userAccounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001707 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
Amith Yamasani27db4682013-03-30 17:07:47 -07001708 Binder.getCallingUid(), null);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001709 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001710 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001711 }
1712 }
1713 }
1714 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001715
1716 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1717 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001718 }
1719
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001720 @Override
1721 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001722 return getAccountsAsUser(type, userId, null, -1);
1723 }
1724
1725 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
1726 int packageUid) {
1727 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001728 // Only allow the system process to read accounts of other users
1729 if (userId != UserHandle.getCallingUserId()
Amith Yamasani27db4682013-03-30 17:07:47 -07001730 && callingUid != Process.myUid()) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001731 throw new SecurityException("User " + UserHandle.getCallingUserId()
1732 + " trying to get account for " + userId);
1733 }
1734
Fred Quintana56285a62010-12-02 14:20:51 -08001735 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1736 Log.v(TAG, "getAccounts: accountType " + type
1737 + ", caller's uid " + Binder.getCallingUid()
1738 + ", pid " + Binder.getCallingPid());
1739 }
Amith Yamasani27db4682013-03-30 17:07:47 -07001740 // If the original calling app was using the framework account chooser activity, we'll
1741 // be passed in the original caller's uid here, which is what should be used for filtering.
1742 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
1743 callingUid = packageUid;
1744 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001745 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001746 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001747 long identityToken = clearCallingIdentity();
1748 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001749 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001750 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001751 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001752 } finally {
1753 restoreCallingIdentity(identityToken);
1754 }
1755 }
1756
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001757 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001758 public boolean addSharedAccountAsUser(Account account, int userId) {
1759 userId = handleIncomingUser(userId);
1760 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1761 ContentValues values = new ContentValues();
1762 values.put(ACCOUNTS_NAME, account.name);
1763 values.put(ACCOUNTS_TYPE, account.type);
1764 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1765 new String[] {account.name, account.type});
1766 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1767 if (accountId < 0) {
1768 Log.w(TAG, "insertAccountIntoDatabase: " + account
1769 + ", skipping the DB insert failed");
1770 return false;
1771 }
1772 return true;
1773 }
1774
1775 @Override
1776 public boolean removeSharedAccountAsUser(Account account, int userId) {
1777 userId = handleIncomingUser(userId);
1778 UserAccounts accounts = getUserAccounts(userId);
1779 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1780 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1781 new String[] {account.name, account.type});
1782 if (r > 0) {
1783 removeAccountInternal(accounts, account);
1784 }
1785 return r > 0;
1786 }
1787
1788 @Override
1789 public Account[] getSharedAccountsAsUser(int userId) {
1790 userId = handleIncomingUser(userId);
1791 UserAccounts accounts = getUserAccounts(userId);
1792 ArrayList<Account> accountList = new ArrayList<Account>();
1793 Cursor cursor = null;
1794 try {
1795 cursor = accounts.openHelper.getReadableDatabase()
1796 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1797 null, null, null, null, null);
1798 if (cursor != null && cursor.moveToFirst()) {
1799 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1800 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1801 do {
1802 accountList.add(new Account(cursor.getString(nameIndex),
1803 cursor.getString(typeIndex)));
1804 } while (cursor.moveToNext());
1805 }
1806 } finally {
1807 if (cursor != null) {
1808 cursor.close();
1809 }
1810 }
1811 Account[] accountArray = new Account[accountList.size()];
1812 accountList.toArray(accountArray);
1813 return accountArray;
1814 }
1815
1816 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001817 public Account[] getAccounts(String type) {
1818 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1819 }
1820
Amith Yamasani27db4682013-03-30 17:07:47 -07001821 @Override
1822 public Account[] getAccountsForPackage(String packageName, int uid) {
1823 int callingUid = Binder.getCallingUid();
1824 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
1825 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
1826 + callingUid + " with uid=" + uid);
1827 }
1828 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
1829 }
1830
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001831 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001832 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001833 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1834 Log.v(TAG, "getAccounts: accountType " + type
1835 + ", response " + response
1836 + ", features " + stringArrayToString(features)
1837 + ", caller's uid " + Binder.getCallingUid()
1838 + ", pid " + Binder.getCallingPid());
1839 }
Fred Quintana382601f2010-03-25 12:25:10 -07001840 if (response == null) throw new IllegalArgumentException("response is null");
1841 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001842 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001843 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001844 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001845 long identityToken = clearCallingIdentity();
1846 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001847 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001848 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001849 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001850 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001851 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001852 Bundle result = new Bundle();
1853 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1854 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001855 return;
1856 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001857 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
1858 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001859 } finally {
1860 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001861 }
1862 }
1863
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001864 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001865 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001866 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001867 try {
1868 if (cursor.moveToNext()) {
1869 return cursor.getLong(0);
1870 }
1871 return -1;
1872 } finally {
1873 cursor.close();
1874 }
1875 }
1876
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001877 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001878 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1879 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1880 new String[]{key}, null, null, null);
1881 try {
1882 if (cursor.moveToNext()) {
1883 return cursor.getLong(0);
1884 }
1885 return -1;
1886 } finally {
1887 cursor.close();
1888 }
1889 }
1890
Fred Quintanaa698f422009-04-08 19:14:54 -07001891 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001892 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001893 IAccountManagerResponse mResponse;
1894 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001895 final boolean mExpectActivityLaunch;
1896 final long mCreationTime;
1897
Fred Quintana33269202009-04-20 16:05:10 -07001898 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001899 private int mNumRequestContinued = 0;
1900 private int mNumErrors = 0;
1901
Fred Quintana60307342009-03-24 22:48:12 -07001902 IAccountAuthenticator mAuthenticator = null;
1903
Fred Quintana8570f742010-02-18 10:32:54 -08001904 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001905 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001906
Amith Yamasani04e0d262012-02-14 11:50:53 -08001907 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001908 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001909 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001910 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001911 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001912 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001913 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001914 mResponse = response;
1915 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001916 mExpectActivityLaunch = expectActivityLaunch;
1917 mCreationTime = SystemClock.elapsedRealtime();
1918 synchronized (mSessions) {
1919 mSessions.put(toString(), this);
1920 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001921 if (response != null) {
1922 try {
1923 response.asBinder().linkToDeath(this, 0 /* flags */);
1924 } catch (RemoteException e) {
1925 mResponse = null;
1926 binderDied();
1927 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001928 }
Fred Quintana60307342009-03-24 22:48:12 -07001929 }
1930
Fred Quintanaa698f422009-04-08 19:14:54 -07001931 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001932 if (mResponse == null) {
1933 // this session has already been closed
1934 return null;
1935 }
Fred Quintana60307342009-03-24 22:48:12 -07001936 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001937 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001938 return response;
1939 }
1940
Fred Quintanaa698f422009-04-08 19:14:54 -07001941 private void close() {
1942 synchronized (mSessions) {
1943 if (mSessions.remove(toString()) == null) {
1944 // the session was already closed, so bail out now
1945 return;
1946 }
1947 }
1948 if (mResponse != null) {
1949 // stop listening for response deaths
1950 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1951
1952 // clear this so that we don't accidentally send any further results
1953 mResponse = null;
1954 }
1955 cancelTimeout();
1956 unbind();
1957 }
1958
1959 public void binderDied() {
1960 mResponse = null;
1961 close();
1962 }
1963
1964 protected String toDebugString() {
1965 return toDebugString(SystemClock.elapsedRealtime());
1966 }
1967
1968 protected String toDebugString(long now) {
1969 return "Session: expectLaunch " + mExpectActivityLaunch
1970 + ", connected " + (mAuthenticator != null)
1971 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1972 + "/" + mNumErrors + ")"
1973 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1974 }
1975
Fred Quintana60307342009-03-24 22:48:12 -07001976 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001977 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1978 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1979 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001980 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001981 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001982 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001983 }
1984 }
1985
1986 private void unbind() {
1987 if (mAuthenticator != null) {
1988 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001989 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001990 }
1991 }
1992
1993 public void scheduleTimeout() {
1994 mMessageHandler.sendMessageDelayed(
1995 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1996 }
1997
1998 public void cancelTimeout() {
1999 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2000 }
2001
Fred Quintanab839afc2009-10-14 15:57:28 -07002002 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002003 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002004 try {
2005 run();
2006 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002007 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002008 "remote exception");
2009 }
Fred Quintana60307342009-03-24 22:48:12 -07002010 }
2011
Fred Quintanab839afc2009-10-14 15:57:28 -07002012 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002013 mAuthenticator = null;
2014 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002015 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002016 try {
2017 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2018 "disconnected");
2019 } catch (RemoteException e) {
2020 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2021 Log.v(TAG, "Session.onServiceDisconnected: "
2022 + "caught RemoteException while responding", e);
2023 }
2024 }
Fred Quintana60307342009-03-24 22:48:12 -07002025 }
2026 }
2027
Fred Quintanab839afc2009-10-14 15:57:28 -07002028 public abstract void run() throws RemoteException;
2029
Fred Quintana60307342009-03-24 22:48:12 -07002030 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002031 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002032 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002033 try {
2034 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2035 "timeout");
2036 } catch (RemoteException e) {
2037 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2038 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2039 e);
2040 }
2041 }
Fred Quintana60307342009-03-24 22:48:12 -07002042 }
2043 }
2044
Fred Quintanaa698f422009-04-08 19:14:54 -07002045 public void onResult(Bundle result) {
2046 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002047 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
2048 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2049 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002050 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2051 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002052 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2053 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002054 }
Fred Quintana60307342009-03-24 22:48:12 -07002055 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002056 IAccountManagerResponse response;
2057 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002058 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002059 response = mResponse;
2060 } else {
2061 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002062 }
Fred Quintana60307342009-03-24 22:48:12 -07002063 if (response != null) {
2064 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002065 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002066 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2067 Log.v(TAG, getClass().getSimpleName()
2068 + " calling onError() on response " + response);
2069 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002070 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002071 "null bundle returned");
2072 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002073 if (mStripAuthTokenFromResult) {
2074 result.remove(AccountManager.KEY_AUTHTOKEN);
2075 }
Fred Quintana56285a62010-12-02 14:20:51 -08002076 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2077 Log.v(TAG, getClass().getSimpleName()
2078 + " calling onResult() on response " + response);
2079 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002080 response.onResult(result);
2081 }
Fred Quintana60307342009-03-24 22:48:12 -07002082 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002083 // if the caller is dead then there is no one to care about remote exceptions
2084 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2085 Log.v(TAG, "failure while notifying response", e);
2086 }
Fred Quintana60307342009-03-24 22:48:12 -07002087 }
2088 }
2089 }
Fred Quintana60307342009-03-24 22:48:12 -07002090
Fred Quintanaa698f422009-04-08 19:14:54 -07002091 public void onRequestContinued() {
2092 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002093 }
2094
2095 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002096 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002097 IAccountManagerResponse response = getResponseAndClose();
2098 if (response != null) {
2099 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002100 Log.v(TAG, getClass().getSimpleName()
2101 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002102 }
2103 try {
2104 response.onError(errorCode, errorMessage);
2105 } catch (RemoteException e) {
2106 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2107 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2108 }
2109 }
2110 } else {
2111 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2112 Log.v(TAG, "Session.onError: already closed");
2113 }
Fred Quintana60307342009-03-24 22:48:12 -07002114 }
2115 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002116
2117 /**
2118 * find the component name for the authenticator and initiate a bind
2119 * if no authenticator or the bind fails then return false, otherwise return true
2120 */
2121 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002122 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2123 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2124 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002125 if (authenticatorInfo == null) {
2126 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2127 Log.v(TAG, "there is no authenticator for " + authenticatorType
2128 + ", bailing out");
2129 }
2130 return false;
2131 }
2132
2133 Intent intent = new Intent();
2134 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2135 intent.setComponent(authenticatorInfo.componentName);
2136 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2137 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2138 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002139 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2140 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002141 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2142 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2143 }
2144 return false;
2145 }
2146
2147
2148 return true;
2149 }
Fred Quintana60307342009-03-24 22:48:12 -07002150 }
2151
2152 private class MessageHandler extends Handler {
2153 MessageHandler(Looper looper) {
2154 super(looper);
2155 }
Costin Manolache3348f142009-09-29 18:58:36 -07002156
Fred Quintana60307342009-03-24 22:48:12 -07002157 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002158 switch (msg.what) {
2159 case MESSAGE_TIMED_OUT:
2160 Session session = (Session)msg.obj;
2161 session.onTimedOut();
2162 break;
2163
2164 default:
2165 throw new IllegalStateException("unhandled message: " + msg.what);
2166 }
2167 }
2168 }
2169
Amith Yamasani04e0d262012-02-14 11:50:53 -08002170 private static String getDatabaseName(int userId) {
2171 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002172 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002173 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002174 // Migrate old file, if it exists, to the new location.
2175 // Make sure the new file doesn't already exist. A dummy file could have been
2176 // accidentally created in the old location, causing the new one to become corrupted
2177 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002178 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002179 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002180 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002181 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002182 if (!userDir.exists()) {
2183 if (!userDir.mkdirs()) {
2184 throw new IllegalStateException("User dir cannot be created: " + userDir);
2185 }
2186 }
2187 if (!oldFile.renameTo(databaseFile)) {
2188 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2189 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002190 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002191 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002192 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002193 }
2194
Amith Yamasani04e0d262012-02-14 11:50:53 -08002195 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002196
Amith Yamasani04e0d262012-02-14 11:50:53 -08002197 public DatabaseHelper(Context context, int userId) {
2198 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002199 }
2200
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002201 /**
2202 * This call needs to be made while the mCacheLock is held. The way to
2203 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2204 * @param db The database.
2205 */
Fred Quintana60307342009-03-24 22:48:12 -07002206 @Override
2207 public void onCreate(SQLiteDatabase db) {
2208 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2209 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2210 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2211 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2212 + ACCOUNTS_PASSWORD + " TEXT, "
2213 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2214
2215 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2216 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2217 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2218 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2219 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2220 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2221
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002222 createGrantsTable(db);
2223
Fred Quintana60307342009-03-24 22:48:12 -07002224 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2225 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2226 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2227 + EXTRAS_KEY + " TEXT NOT NULL, "
2228 + EXTRAS_VALUE + " TEXT, "
2229 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2230
2231 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2232 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2233 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002234
Amith Yamasani67df64b2012-12-14 12:09:36 -08002235 createSharedAccountsTable(db);
2236
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002237 createAccountsDeletionTrigger(db);
2238 }
2239
Amith Yamasani67df64b2012-12-14 12:09:36 -08002240 private void createSharedAccountsTable(SQLiteDatabase db) {
2241 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2242 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2243 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2244 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2245 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2246 }
2247
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002248 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002249 db.execSQL(""
2250 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2251 + " BEGIN"
2252 + " DELETE FROM " + TABLE_AUTHTOKENS
2253 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2254 + " DELETE FROM " + TABLE_EXTRAS
2255 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002256 + " DELETE FROM " + TABLE_GRANTS
2257 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002258 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002259 }
2260
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002261 private void createGrantsTable(SQLiteDatabase db) {
2262 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2263 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2264 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2265 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2266 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2267 + "," + GRANTS_GRANTEE_UID + "))");
2268 }
2269
Fred Quintana60307342009-03-24 22:48:12 -07002270 @Override
2271 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002272 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002273
Fred Quintanaa698f422009-04-08 19:14:54 -07002274 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002275 // no longer need to do anything since the work is done
2276 // when upgrading from version 2
2277 oldVersion++;
2278 }
2279
2280 if (oldVersion == 2) {
2281 createGrantsTable(db);
2282 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2283 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002284 oldVersion++;
2285 }
Costin Manolache3348f142009-09-29 18:58:36 -07002286
2287 if (oldVersion == 3) {
2288 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2289 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2290 oldVersion++;
2291 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002292
2293 if (oldVersion == 4) {
2294 createSharedAccountsTable(db);
2295 oldVersion++;
2296 }
2297
2298 if (oldVersion != newVersion) {
2299 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2300 }
Fred Quintana60307342009-03-24 22:48:12 -07002301 }
2302
2303 @Override
2304 public void onOpen(SQLiteDatabase db) {
2305 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2306 }
2307 }
2308
Fred Quintana60307342009-03-24 22:48:12 -07002309 public IBinder onBind(Intent intent) {
2310 return asBinder();
2311 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002312
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002313 /**
2314 * Searches array of arguments for the specified string
2315 * @param args array of argument strings
2316 * @param value value to search for
2317 * @return true if the value is contained in the array
2318 */
2319 private static boolean scanArgs(String[] args, String value) {
2320 if (args != null) {
2321 for (String arg : args) {
2322 if (value.equals(arg)) {
2323 return true;
2324 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002325 }
2326 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002327 return false;
2328 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002329
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002330 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002331 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002332 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2333 != PackageManager.PERMISSION_GRANTED) {
2334 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2335 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2336 + " without permission " + android.Manifest.permission.DUMP);
2337 return;
2338 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002339 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002340 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002341
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002342 final List<UserInfo> users = getUserManager().getUsers();
2343 for (UserInfo user : users) {
2344 ipw.println("User " + user + ":");
2345 ipw.increaseIndent();
2346 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2347 ipw.println();
2348 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002349 }
2350 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002351
Amith Yamasani04e0d262012-02-14 11:50:53 -08002352 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2353 String[] args, boolean isCheckinRequest) {
2354 synchronized (userAccounts.cacheLock) {
2355 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002356
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002357 if (isCheckinRequest) {
2358 // This is a checkin request. *Only* upload the account types and the count of each.
2359 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2360 null, null, ACCOUNTS_TYPE, null, null);
2361 try {
2362 while (cursor.moveToNext()) {
2363 // print type,count
2364 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2365 }
2366 } finally {
2367 if (cursor != null) {
2368 cursor.close();
2369 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002370 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002371 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002372 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002373 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002374 fout.println("Accounts: " + accounts.length);
2375 for (Account account : accounts) {
2376 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002377 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002378
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002379 fout.println();
2380 synchronized (mSessions) {
2381 final long now = SystemClock.elapsedRealtime();
2382 fout.println("Active Sessions: " + mSessions.size());
2383 for (Session session : mSessions.values()) {
2384 fout.println(" " + session.toDebugString(now));
2385 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002386 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002387
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002388 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002389 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002390 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002391 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002392 }
2393
Amith Yamasani04e0d262012-02-14 11:50:53 -08002394 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002395 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002396 long identityToken = clearCallingIdentity();
2397 try {
2398 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2399 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2400 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002401
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002402 if (intent.getComponent() != null &&
2403 GrantCredentialsPermissionActivity.class.getName().equals(
2404 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002405 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002406 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002407 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002408 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002409 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2410 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002411 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002412 final String notificationTitleFormat =
2413 mContext.getText(R.string.notification_title).toString();
2414 n.setLatestEventInfo(mContext,
2415 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002416 message, PendingIntent.getActivityAsUser(
2417 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002418 null, user));
2419 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002420 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002421 } finally {
2422 restoreCallingIdentity(identityToken);
2423 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002424 }
2425
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002426 protected void installNotification(final int notificationId, final Notification n,
2427 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002428 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002429 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002430 }
2431
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002432 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002433 long identityToken = clearCallingIdentity();
2434 try {
2435 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002436 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002437 } finally {
2438 restoreCallingIdentity(identityToken);
2439 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002440 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002441
Fred Quintanab38eb142010-02-24 13:40:54 -08002442 /** Succeeds if any of the specified permissions are granted. */
2443 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002444 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002445
2446 for (String perm : permissions) {
2447 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2448 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002449 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002450 }
2451 return;
2452 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002453 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002454
2455 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002456 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002457 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002458 }
2459
Amith Yamasani67df64b2012-12-14 12:09:36 -08002460 private int handleIncomingUser(int userId) {
2461 try {
2462 return ActivityManagerNative.getDefault().handleIncomingUser(
2463 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2464 } catch (RemoteException re) {
2465 // Shouldn't happen, local.
2466 }
2467 return userId;
2468 }
2469
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002470 private boolean inSystemImage(int callingUid) {
2471 final int callingUserId = UserHandle.getUserId(callingUid);
2472
2473 final PackageManager userPackageManager;
2474 try {
2475 userPackageManager = mContext.createPackageContextAsUser(
2476 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2477 } catch (NameNotFoundException e) {
2478 return false;
2479 }
2480
2481 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002482 for (String name : packages) {
2483 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002484 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002485 if (packageInfo != null
2486 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002487 return true;
2488 }
2489 } catch (PackageManager.NameNotFoundException e) {
2490 return false;
2491 }
2492 }
2493 return false;
2494 }
2495
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002496 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002497 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002498 final boolean fromAuthenticator = account != null
2499 && hasAuthenticatorUid(account.type, callerUid);
2500 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002501 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002502 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2503 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002504 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002505 + ": is authenticator? " + fromAuthenticator
2506 + ", has explicit permission? " + hasExplicitGrants);
2507 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002508 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002509 }
2510
Fred Quintana1a231912009-10-15 11:31:30 -07002511 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002512 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002513 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002514 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002515 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002516 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002517 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002518 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002519 }
2520 }
2521 return false;
2522 }
2523
Amith Yamasani04e0d262012-02-14 11:50:53 -08002524 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2525 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002526 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002527 return true;
2528 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002529 UserAccounts accounts = getUserAccountsForCaller();
2530 synchronized (accounts.cacheLock) {
2531 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2532 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002533 account.name, account.type};
2534 final boolean permissionGranted =
2535 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2536 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2537 // TODO: Skip this check when running automated tests. Replace this
2538 // with a more general solution.
2539 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002540 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002541 + " but ignoring since device is in test harness.");
2542 return true;
2543 }
2544 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002545 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002546 }
2547
2548 private void checkCallingUidAgainstAuthenticator(Account account) {
2549 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002550 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002551 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2552 Log.w(TAG, msg);
2553 throw new SecurityException(msg);
2554 }
2555 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2556 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2557 }
2558 }
2559
2560 private void checkAuthenticateAccountsPermission(Account account) {
2561 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2562 checkCallingUidAgainstAuthenticator(account);
2563 }
2564
2565 private void checkReadAccountsPermission() {
2566 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2567 }
2568
2569 private void checkManageAccountsPermission() {
2570 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2571 }
2572
Fred Quintanab38eb142010-02-24 13:40:54 -08002573 private void checkManageAccountsOrUseCredentialsPermissions() {
2574 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2575 Manifest.permission.USE_CREDENTIALS);
2576 }
2577
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002578 private boolean canUserModifyAccounts(int callingUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002579 if (callingUid != Process.myUid()) {
2580 if (getUserManager().getUserRestrictions(
2581 new UserHandle(UserHandle.getUserId(callingUid)))
2582 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002583 return false;
2584 }
2585 }
2586 return true;
2587 }
2588
Fred Quintanad9640ec2012-05-23 12:37:00 -07002589 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2590 throws RemoteException {
2591 final int callingUid = getCallingUid();
2592
Amith Yamasani27db4682013-03-30 17:07:47 -07002593 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002594 throw new SecurityException();
2595 }
2596
2597 if (value) {
2598 grantAppPermission(account, authTokenType, uid);
2599 } else {
2600 revokeAppPermission(account, authTokenType, uid);
2601 }
2602 }
2603
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002604 /**
2605 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2606 * <p>
2607 * Although this is public it can only be accessed via the AccountManagerService object
2608 * which is in the system. This means we don't need to protect it with permissions.
2609 * @hide
2610 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002611 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002612 if (account == null || authTokenType == null) {
2613 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002614 return;
2615 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002616 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002617 synchronized (accounts.cacheLock) {
2618 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002619 db.beginTransaction();
2620 try {
2621 long accountId = getAccountIdLocked(db, account);
2622 if (accountId >= 0) {
2623 ContentValues values = new ContentValues();
2624 values.put(GRANTS_ACCOUNTS_ID, accountId);
2625 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2626 values.put(GRANTS_GRANTEE_UID, uid);
2627 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2628 db.setTransactionSuccessful();
2629 }
2630 } finally {
2631 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002632 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002633 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2634 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002635 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002636 }
2637
2638 /**
2639 * Don't allow callers with the given uid permission to get credentials for
2640 * account/authTokenType.
2641 * <p>
2642 * Although this is public it can only be accessed via the AccountManagerService object
2643 * which is in the system. This means we don't need to protect it with permissions.
2644 * @hide
2645 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002646 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002647 if (account == null || authTokenType == null) {
2648 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002649 return;
2650 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002651 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002652 synchronized (accounts.cacheLock) {
2653 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002654 db.beginTransaction();
2655 try {
2656 long accountId = getAccountIdLocked(db, account);
2657 if (accountId >= 0) {
2658 db.delete(TABLE_GRANTS,
2659 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2660 + GRANTS_GRANTEE_UID + "=?",
2661 new String[]{String.valueOf(accountId), authTokenType,
2662 String.valueOf(uid)});
2663 db.setTransactionSuccessful();
2664 }
2665 } finally {
2666 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002667 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002668 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2669 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002670 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002671 }
Fred Quintana56285a62010-12-02 14:20:51 -08002672
2673 static final private String stringArrayToString(String[] value) {
2674 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2675 }
2676
Amith Yamasani04e0d262012-02-14 11:50:53 -08002677 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2678 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002679 if (oldAccountsForType != null) {
2680 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2681 for (Account curAccount : oldAccountsForType) {
2682 if (!curAccount.equals(account)) {
2683 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002684 }
2685 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002686 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002687 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002688 } else {
2689 Account[] newAccountsForType = new Account[newAccountsList.size()];
2690 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002691 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002692 }
Fred Quintana56285a62010-12-02 14:20:51 -08002693 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002694 accounts.userDataCache.remove(account);
2695 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002696 }
2697
2698 /**
2699 * This assumes that the caller has already checked that the account is not already present.
2700 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002701 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2702 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002703 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2704 Account[] newAccountsForType = new Account[oldLength + 1];
2705 if (accountsForType != null) {
2706 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002707 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002708 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002709 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002710 }
2711
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002712 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07002713 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002714 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07002715 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002716 return unfiltered;
2717 }
2718 if (mUserManager.getUserInfo(userAccounts.userId).isRestricted()) {
2719 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002720 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002721 // otherwise return non-shared accounts only.
2722 // This might be a temporary way to specify a whitelist
2723 String whiteList = mContext.getResources().getString(
2724 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2725 for (String packageName : packages) {
2726 if (whiteList.contains(";" + packageName + ";")) {
2727 return unfiltered;
2728 }
2729 }
2730 ArrayList<Account> allowed = new ArrayList<Account>();
2731 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2732 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002733 String requiredAccountType = "";
2734 try {
2735 for (String packageName : packages) {
2736 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
2737 if (pi != null && pi.restrictedAccountType != null) {
2738 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07002739 // If it matches the package name of the original caller, use this choice.
2740 if (callingPackage != null && packageName.equals(callingPackage)) {
2741 break;
2742 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002743 }
2744 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002745 } catch (NameNotFoundException nnfe) {
2746 }
2747 for (Account account : unfiltered) {
2748 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002749 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002750 } else {
2751 boolean found = false;
2752 for (Account shared : sharedAccounts) {
2753 if (shared.equals(account)) {
2754 found = true;
2755 break;
2756 }
2757 }
2758 if (!found) {
2759 allowed.add(account);
2760 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002761 }
2762 }
2763 Account[] filtered = new Account[allowed.size()];
2764 allowed.toArray(filtered);
2765 return filtered;
2766 } else {
2767 return unfiltered;
2768 }
2769 }
2770
Amith Yamasani27db4682013-03-30 17:07:47 -07002771 /*
2772 * packageName can be null. If not null, it should be used to filter out restricted accounts
2773 * that the package is not allowed to access.
2774 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002775 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07002776 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002777 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002778 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002779 if (accounts == null) {
2780 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002781 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002782 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07002783 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002784 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002785 } else {
2786 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002787 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002788 totalLength += accounts.length;
2789 }
2790 if (totalLength == 0) {
2791 return EMPTY_ACCOUNT_ARRAY;
2792 }
2793 Account[] accounts = new Account[totalLength];
2794 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002795 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002796 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2797 accountsOfType.length);
2798 totalLength += accountsOfType.length;
2799 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002800 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002801 }
2802 }
2803
Amith Yamasani04e0d262012-02-14 11:50:53 -08002804 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2805 Account account, String key, String value) {
2806 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002807 if (userDataForAccount == null) {
2808 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002809 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002810 }
2811 if (value == null) {
2812 userDataForAccount.remove(key);
2813 } else {
2814 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002815 }
2816 }
2817
Amith Yamasani04e0d262012-02-14 11:50:53 -08002818 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2819 Account account, String key, String value) {
2820 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002821 if (authTokensForAccount == null) {
2822 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002823 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002824 }
2825 if (value == null) {
2826 authTokensForAccount.remove(key);
2827 } else {
2828 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002829 }
2830 }
2831
Amith Yamasani04e0d262012-02-14 11:50:53 -08002832 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2833 String authTokenType) {
2834 synchronized (accounts.cacheLock) {
2835 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002836 if (authTokensForAccount == null) {
2837 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002838 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002839 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002840 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002841 }
2842 return authTokensForAccount.get(authTokenType);
2843 }
2844 }
2845
Amith Yamasani04e0d262012-02-14 11:50:53 -08002846 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2847 synchronized (accounts.cacheLock) {
2848 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002849 if (userDataForAccount == null) {
2850 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002851 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002852 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002853 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002854 }
2855 return userDataForAccount.get(key);
2856 }
2857 }
2858
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002859 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2860 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002861 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002862 Cursor cursor = db.query(TABLE_EXTRAS,
2863 COLUMNS_EXTRAS_KEY_AND_VALUE,
2864 SELECTION_USERDATA_BY_ACCOUNT,
2865 new String[]{account.name, account.type},
2866 null, null, null);
2867 try {
2868 while (cursor.moveToNext()) {
2869 final String tmpkey = cursor.getString(0);
2870 final String value = cursor.getString(1);
2871 userDataForAccount.put(tmpkey, value);
2872 }
2873 } finally {
2874 cursor.close();
2875 }
2876 return userDataForAccount;
2877 }
2878
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002879 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2880 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002881 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002882 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2883 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2884 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2885 new String[]{account.name, account.type},
2886 null, null, null);
2887 try {
2888 while (cursor.moveToNext()) {
2889 final String type = cursor.getString(0);
2890 final String authToken = cursor.getString(1);
2891 authTokensForAccount.put(type, authToken);
2892 }
2893 } finally {
2894 cursor.close();
2895 }
2896 return authTokensForAccount;
2897 }
Fred Quintana60307342009-03-24 22:48:12 -07002898}