blob: 14d808f842d63e4a5e27f665311ed1cb625a1191 [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;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700119 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700120
Fred Quintana56285a62010-12-02 14:20:51 -0800121 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700122
123 private static final String TABLE_ACCOUNTS = "accounts";
124 private static final String ACCOUNTS_ID = "_id";
125 private static final String ACCOUNTS_NAME = "name";
126 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700127 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700128 private static final String ACCOUNTS_PASSWORD = "password";
129
130 private static final String TABLE_AUTHTOKENS = "authtokens";
131 private static final String AUTHTOKENS_ID = "_id";
132 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
133 private static final String AUTHTOKENS_TYPE = "type";
134 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
135
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700136 private static final String TABLE_GRANTS = "grants";
137 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
138 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
139 private static final String GRANTS_GRANTEE_UID = "uid";
140
Fred Quintana60307342009-03-24 22:48:12 -0700141 private static final String TABLE_EXTRAS = "extras";
142 private static final String EXTRAS_ID = "_id";
143 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
144 private static final String EXTRAS_KEY = "key";
145 private static final String EXTRAS_VALUE = "value";
146
147 private static final String TABLE_META = "meta";
148 private static final String META_KEY = "key";
149 private static final String META_VALUE = "value";
150
Amith Yamasani67df64b2012-12-14 12:09:36 -0800151 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
152
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700153 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
154 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700155 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700156
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700157 private static final String COUNT_OF_MATCHING_GRANTS = ""
158 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
159 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
160 + " AND " + GRANTS_GRANTEE_UID + "=?"
161 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
162 + " AND " + ACCOUNTS_NAME + "=?"
163 + " AND " + ACCOUNTS_TYPE + "=?";
164
Fred Quintana56285a62010-12-02 14:20:51 -0800165 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
166 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
167 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
168 AUTHTOKENS_AUTHTOKEN};
169
170 private static final String SELECTION_USERDATA_BY_ACCOUNT =
171 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
172 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
173
Fred Quintanaa698f422009-04-08 19:14:54 -0700174 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700175 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
176
Amith Yamasani04e0d262012-02-14 11:50:53 -0800177 static class UserAccounts {
178 private final int userId;
179 private final DatabaseHelper openHelper;
180 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
181 credentialsPermissionNotificationIds =
182 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
183 private final HashMap<Account, Integer> signinRequiredNotificationIds =
184 new HashMap<Account, Integer>();
185 private final Object cacheLock = new Object();
186 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700187 private final HashMap<String, Account[]> accountCache =
188 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800189 /** protected by the {@link #cacheLock} */
190 private HashMap<Account, HashMap<String, String>> userDataCache =
191 new HashMap<Account, HashMap<String, String>>();
192 /** protected by the {@link #cacheLock} */
193 private HashMap<Account, HashMap<String, String>> authTokenCache =
194 new HashMap<Account, HashMap<String, String>>();
195
196 UserAccounts(Context context, int userId) {
197 this.userId = userId;
198 synchronized (cacheLock) {
199 openHelper = new DatabaseHelper(context, userId);
200 }
201 }
202 }
203
204 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
205
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700206 private static AtomicReference<AccountManagerService> sThis =
207 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700208 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700209
210 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700211 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700212 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
213 }
214
Fred Quintana56285a62010-12-02 14:20:51 -0800215
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700216 /**
217 * This should only be called by system code. One should only call this after the service
218 * has started.
219 * @return a reference to the AccountManagerService instance
220 * @hide
221 */
222 public static AccountManagerService getSingleton() {
223 return sThis.get();
224 }
Fred Quintana60307342009-03-24 22:48:12 -0700225
Fred Quintana56285a62010-12-02 14:20:51 -0800226 public AccountManagerService(Context context) {
227 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700228 }
229
Fred Quintana56285a62010-12-02 14:20:51 -0800230 public AccountManagerService(Context context, PackageManager packageManager,
231 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700232 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800233 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700234
Fred Quintana60307342009-03-24 22:48:12 -0700235 mMessageThread = new HandlerThread("AccountManagerService");
236 mMessageThread.start();
237 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
238
Fred Quintana56285a62010-12-02 14:20:51 -0800239 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800240 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700241
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700242 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800243
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800244 IntentFilter intentFilter = new IntentFilter();
245 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
246 intentFilter.addDataScheme("package");
247 mContext.registerReceiver(new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800250 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800251 }
252 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800253
Amith Yamasani13593602012-03-22 16:16:17 -0700254 IntentFilter userFilter = new IntentFilter();
255 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800256 userFilter.addAction(Intent.ACTION_USER_STARTED);
257 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700258 @Override
259 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800260 String action = intent.getAction();
261 if (Intent.ACTION_USER_REMOVED.equals(action)) {
262 onUserRemoved(intent);
263 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
264 onUserStarted(intent);
265 }
Amith Yamasani13593602012-03-22 16:16:17 -0700266 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800267 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800268 }
269
Kenny Root26ff6622012-07-30 12:58:03 -0700270 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700271 }
272
Amith Yamasani258848d2012-08-10 17:06:33 -0700273 private UserManager getUserManager() {
274 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700275 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700276 }
277 return mUserManager;
278 }
279
Amith Yamasani04e0d262012-02-14 11:50:53 -0800280 private UserAccounts initUser(int userId) {
281 synchronized (mUsers) {
282 UserAccounts accounts = mUsers.get(userId);
283 if (accounts == null) {
284 accounts = new UserAccounts(mContext, userId);
285 mUsers.append(userId, accounts);
286 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700287 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800288 }
289 return accounts;
290 }
291 }
292
293 private void purgeOldGrantsAll() {
294 synchronized (mUsers) {
295 for (int i = 0; i < mUsers.size(); i++) {
296 purgeOldGrants(mUsers.valueAt(i));
297 }
298 }
299 }
300
301 private void purgeOldGrants(UserAccounts accounts) {
302 synchronized (accounts.cacheLock) {
303 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800304 final Cursor cursor = db.query(TABLE_GRANTS,
305 new String[]{GRANTS_GRANTEE_UID},
306 null, null, GRANTS_GRANTEE_UID, null, null);
307 try {
308 while (cursor.moveToNext()) {
309 final int uid = cursor.getInt(0);
310 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
311 if (packageExists) {
312 continue;
313 }
314 Log.d(TAG, "deleting grants for UID " + uid
315 + " because its package is no longer installed");
316 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
317 new String[]{Integer.toString(uid)});
318 }
319 } finally {
320 cursor.close();
321 }
322 }
323 }
324
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700325 /**
326 * Validate internal set of accounts against installed authenticators for
327 * given user. Clears cached authenticators before validating.
328 */
329 public void validateAccounts(int userId) {
330 final UserAccounts accounts = getUserAccounts(userId);
331
332 // Invalidate user-specific cache to make sure we catch any
333 // removed authenticators.
334 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
335 }
336
337 /**
338 * Validate internal set of accounts against installed authenticators for
339 * given user. Clear cached authenticators before validating when requested.
340 */
341 private void validateAccountsInternal(
342 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
343 if (invalidateAuthenticatorCache) {
344 mAuthenticatorCache.invalidateCache(accounts.userId);
345 }
346
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700347 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
348 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
349 mAuthenticatorCache.getAllServices(accounts.userId)) {
350 knownAuth.add(service.type);
351 }
352
Amith Yamasani04e0d262012-02-14 11:50:53 -0800353 synchronized (accounts.cacheLock) {
354 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800355 boolean accountDeleted = false;
356 Cursor cursor = db.query(TABLE_ACCOUNTS,
357 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
358 null, null, null, null, null);
359 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800360 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800361 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700362 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800363 while (cursor.moveToNext()) {
364 final long accountId = cursor.getLong(0);
365 final String accountType = cursor.getString(1);
366 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700367
368 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700369 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800370 + accountType + " no longer has a registered authenticator");
371 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
372 accountDeleted = true;
373 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800374 accounts.userDataCache.remove(account);
375 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800376 } else {
377 ArrayList<String> accountNames = accountNamesByType.get(accountType);
378 if (accountNames == null) {
379 accountNames = new ArrayList<String>();
380 accountNamesByType.put(accountType, accountNames);
381 }
382 accountNames.add(accountName);
383 }
384 }
Andy McFadden2f362292012-01-20 14:43:38 -0800385 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800386 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800387 final String accountType = cur.getKey();
388 final ArrayList<String> accountNames = cur.getValue();
389 final Account[] accountsForType = new Account[accountNames.size()];
390 int i = 0;
391 for (String accountName : accountNames) {
392 accountsForType[i] = new Account(accountName, accountType);
393 ++i;
394 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800395 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800396 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800397 } finally {
398 cursor.close();
399 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800400 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800401 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800402 }
403 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700404 }
405
Amith Yamasani04e0d262012-02-14 11:50:53 -0800406 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700407 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800408 }
409
410 protected UserAccounts getUserAccounts(int userId) {
411 synchronized (mUsers) {
412 UserAccounts accounts = mUsers.get(userId);
413 if (accounts == null) {
414 accounts = initUser(userId);
415 mUsers.append(userId, accounts);
416 }
417 return accounts;
418 }
419 }
420
Amith Yamasani13593602012-03-22 16:16:17 -0700421 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700422 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700423 if (userId < 1) return;
424
425 UserAccounts accounts;
426 synchronized (mUsers) {
427 accounts = mUsers.get(userId);
428 mUsers.remove(userId);
429 }
430 if (accounts == null) {
431 File dbFile = new File(getDatabaseName(userId));
432 dbFile.delete();
433 return;
434 }
435
436 synchronized (accounts.cacheLock) {
437 accounts.openHelper.close();
438 File dbFile = new File(getDatabaseName(userId));
439 dbFile.delete();
440 }
441 }
442
Amith Yamasani67df64b2012-12-14 12:09:36 -0800443 private void onUserStarted(Intent intent) {
444 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
445 if (userId < 1) return;
446
447 // Check if there's a shared account that needs to be created as an account
448 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
449 if (sharedAccounts == null || sharedAccounts.length == 0) return;
450 Account[] accounts = getAccountsAsUser(null, userId);
451 for (Account sa : sharedAccounts) {
452 if (ArrayUtils.contains(accounts, sa)) continue;
453 // Account doesn't exist. Copy it now.
454 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
455 }
456 }
457
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700458 @Override
459 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700460 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700461 }
462
Fred Quintanaa698f422009-04-08 19:14:54 -0700463 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800464 if (Log.isLoggable(TAG, Log.VERBOSE)) {
465 Log.v(TAG, "getPassword: " + account
466 + ", caller's uid " + Binder.getCallingUid()
467 + ", pid " + Binder.getCallingPid());
468 }
Fred Quintana382601f2010-03-25 12:25:10 -0700469 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700470 checkAuthenticateAccountsPermission(account);
471
Amith Yamasani04e0d262012-02-14 11:50:53 -0800472 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700473 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700474 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800475 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700476 } finally {
477 restoreCallingIdentity(identityToken);
478 }
479 }
480
Amith Yamasani04e0d262012-02-14 11:50:53 -0800481 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700482 if (account == null) {
483 return null;
484 }
485
Amith Yamasani04e0d262012-02-14 11:50:53 -0800486 synchronized (accounts.cacheLock) {
487 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800488 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
489 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
490 new String[]{account.name, account.type}, null, null, null);
491 try {
492 if (cursor.moveToNext()) {
493 return cursor.getString(0);
494 }
495 return null;
496 } finally {
497 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700498 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700499 }
500 }
501
502 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800503 if (Log.isLoggable(TAG, Log.VERBOSE)) {
504 Log.v(TAG, "getUserData: " + account
505 + ", key " + key
506 + ", caller's uid " + Binder.getCallingUid()
507 + ", pid " + Binder.getCallingPid());
508 }
Fred Quintana382601f2010-03-25 12:25:10 -0700509 if (account == null) throw new IllegalArgumentException("account is null");
510 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700511 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800512 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700513 long identityToken = clearCallingIdentity();
514 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800515 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700516 } finally {
517 restoreCallingIdentity(identityToken);
518 }
519 }
520
Fred Quintana97889762009-06-15 12:29:24 -0700521 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800522 if (Log.isLoggable(TAG, Log.VERBOSE)) {
523 Log.v(TAG, "getAuthenticatorTypes: "
524 + "caller's uid " + Binder.getCallingUid()
525 + ", pid " + Binder.getCallingPid());
526 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700527 final int userId = UserHandle.getCallingUserId();
528 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700529 try {
Fred Quintana97889762009-06-15 12:29:24 -0700530 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700531 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700532 AuthenticatorDescription[] types =
533 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700534 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700535 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700536 : authenticatorCollection) {
537 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700538 i++;
539 }
540 return types;
541 } finally {
542 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700543 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700544 }
545
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700546 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700547 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800548 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700549 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800550 + ", caller's uid " + Binder.getCallingUid()
551 + ", pid " + Binder.getCallingPid());
552 }
Fred Quintana382601f2010-03-25 12:25:10 -0700553 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700554 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700555 /*
556 * Child users are not allowed to add accounts. Only the accounts that are
557 * shared by the parent profile can be added to child profile.
558 *
559 * TODO: Only allow accounts that were shared to be added by
560 * a limited user.
561 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700562
Amith Yamasani04e0d262012-02-14 11:50:53 -0800563 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700564 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700565 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700566 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800567 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700568 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700569 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700570 }
571 }
572
Amith Yamasani67df64b2012-12-14 12:09:36 -0800573 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
574 final UserAccounts fromAccounts = getUserAccounts(userFrom);
575 final UserAccounts toAccounts = getUserAccounts(userTo);
576 if (fromAccounts == null || toAccounts == null) {
577 return false;
578 }
579
580 long identityToken = clearCallingIdentity();
581 try {
582 new Session(fromAccounts, null, account.type, false,
583 false /* stripAuthTokenFromResult */) {
584 protected String toDebugString(long now) {
585 return super.toDebugString(now) + ", getAccountCredentialsForClone"
586 + ", " + account.type;
587 }
588
589 public void run() throws RemoteException {
590 mAuthenticator.getAccountCredentialsForCloning(this, account);
591 }
592
593 public void onResult(Bundle result) {
594 if (result != null) {
595 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
596 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800597 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800598 }
599 return;
600 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800601 super.onResult(result);
602 }
603 }
604 }.bind();
605 } finally {
606 restoreCallingIdentity(identityToken);
607 }
608 return true;
609 }
610
Amith Yamasani67df64b2012-12-14 12:09:36 -0800611 void completeCloningAccount(final Bundle result, final Account account,
612 final UserAccounts targetUser) {
613 long id = clearCallingIdentity();
614 try {
615 new Session(targetUser, null, account.type, false,
616 false /* stripAuthTokenFromResult */) {
617 protected String toDebugString(long now) {
618 return super.toDebugString(now) + ", getAccountCredentialsForClone"
619 + ", " + account.type;
620 }
621
622 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700623 // Confirm that the owner's account still exists before this step.
624 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
625 synchronized (owner.cacheLock) {
626 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
627 for (Account acc : ownerAccounts) {
628 if (acc.equals(account)) {
629 mAuthenticator.addAccountFromCredentials(this, account, result);
630 break;
631 }
632 }
633 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800634 }
635
636 public void onResult(Bundle result) {
637 if (result != null) {
638 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
639 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800640 } else {
641 // TODO: Show error notification
642 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800643 }
644 return;
645 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800646 super.onResult(result);
647 }
648 }
649
650 public void onError(int errorCode, String errorMessage) {
651 super.onError(errorCode, errorMessage);
652 // TODO: Show error notification to user
653 // TODO: Should we remove the shadow account so that it doesn't keep trying?
654 }
655
656 }.bind();
657 } finally {
658 restoreCallingIdentity(id);
659 }
660 }
661
Amith Yamasani04e0d262012-02-14 11:50:53 -0800662 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800663 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700664 if (account == null) {
665 return false;
666 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800667 synchronized (accounts.cacheLock) {
668 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800669 db.beginTransaction();
670 try {
671 long numMatches = DatabaseUtils.longForQuery(db,
672 "select count(*) from " + TABLE_ACCOUNTS
673 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
674 new String[]{account.name, account.type});
675 if (numMatches > 0) {
676 Log.w(TAG, "insertAccountIntoDatabase: " + account
677 + ", skipping since the account already exists");
678 return false;
679 }
680 ContentValues values = new ContentValues();
681 values.put(ACCOUNTS_NAME, account.name);
682 values.put(ACCOUNTS_TYPE, account.type);
683 values.put(ACCOUNTS_PASSWORD, password);
684 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
685 if (accountId < 0) {
686 Log.w(TAG, "insertAccountIntoDatabase: " + account
687 + ", skipping the DB insert failed");
688 return false;
689 }
690 if (extras != null) {
691 for (String key : extras.keySet()) {
692 final String value = extras.getString(key);
693 if (insertExtraLocked(db, accountId, key, value) < 0) {
694 Log.w(TAG, "insertAccountIntoDatabase: " + account
695 + ", skipping since insertExtra failed for key " + key);
696 return false;
697 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700698 }
699 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800700 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800701 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800702 } finally {
703 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700704 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800705 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700706 }
707 if (accounts.userId == UserHandle.USER_OWNER) {
708 addAccountToLimitedUsers(account);
709 }
710 return true;
711 }
712
713 /**
714 * Adds the account to all limited users as shared accounts. If the user is currently
715 * running, then clone the account too.
716 * @param account the account to share with limited users
717 */
718 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700719 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700720 for (UserInfo user : users) {
721 if (user.isRestricted()) {
722 addSharedAccountAsUser(account, user.id);
723 try {
724 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
725 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
726 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
727 account));
728 }
729 } catch (RemoteException re) {
730 // Shouldn't happen
731 }
732 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700733 }
734 }
735
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800736 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700737 ContentValues values = new ContentValues();
738 values.put(EXTRAS_KEY, key);
739 values.put(EXTRAS_ACCOUNTS_ID, accountId);
740 values.put(EXTRAS_VALUE, value);
741 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
742 }
743
Fred Quintana3084a6f2010-01-14 18:02:03 -0800744 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800745 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800746 if (Log.isLoggable(TAG, Log.VERBOSE)) {
747 Log.v(TAG, "hasFeatures: " + account
748 + ", response " + response
749 + ", features " + stringArrayToString(features)
750 + ", caller's uid " + Binder.getCallingUid()
751 + ", pid " + Binder.getCallingPid());
752 }
Fred Quintana382601f2010-03-25 12:25:10 -0700753 if (response == null) throw new IllegalArgumentException("response is null");
754 if (account == null) throw new IllegalArgumentException("account is null");
755 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800756 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800757 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800758 long identityToken = clearCallingIdentity();
759 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800760 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800761 } finally {
762 restoreCallingIdentity(identityToken);
763 }
764 }
765
766 private class TestFeaturesSession extends Session {
767 private final String[] mFeatures;
768 private final Account mAccount;
769
Amith Yamasani04e0d262012-02-14 11:50:53 -0800770 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800771 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800772 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800773 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800774 mFeatures = features;
775 mAccount = account;
776 }
777
778 public void run() throws RemoteException {
779 try {
780 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
781 } catch (RemoteException e) {
782 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
783 }
784 }
785
786 public void onResult(Bundle result) {
787 IAccountManagerResponse response = getResponseAndClose();
788 if (response != null) {
789 try {
790 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700791 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800792 return;
793 }
Fred Quintana56285a62010-12-02 14:20:51 -0800794 if (Log.isLoggable(TAG, Log.VERBOSE)) {
795 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
796 + response);
797 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800798 final Bundle newResult = new Bundle();
799 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
800 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
801 response.onResult(newResult);
802 } catch (RemoteException e) {
803 // if the caller is dead then there is no one to care about remote exceptions
804 if (Log.isLoggable(TAG, Log.VERBOSE)) {
805 Log.v(TAG, "failure while notifying response", e);
806 }
807 }
808 }
809 }
810
811 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800812 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800813 + ", " + mAccount
814 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
815 }
816 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800817
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700818 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800819 if (Log.isLoggable(TAG, Log.VERBOSE)) {
820 Log.v(TAG, "removeAccount: " + account
821 + ", response " + response
822 + ", caller's uid " + Binder.getCallingUid()
823 + ", pid " + Binder.getCallingPid());
824 }
Fred Quintana382601f2010-03-25 12:25:10 -0700825 if (response == null) throw new IllegalArgumentException("response is null");
826 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700827 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700828 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800829 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800830 if (!canUserModifyAccounts(Binder.getCallingUid())) {
831 try {
832 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
833 "User cannot modify accounts");
834 } catch (RemoteException re) {
835 }
836 }
837
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700838 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800839
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700840 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800841 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800842 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800843 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800844 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800845 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700846 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800847 }
848 }
849 }
850
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700851 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800852 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700853 } finally {
854 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700855 }
Fred Quintana60307342009-03-24 22:48:12 -0700856 }
857
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700858 private class RemoveAccountSession extends Session {
859 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800860 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
861 Account account) {
862 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800863 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700864 mAccount = account;
865 }
866
867 protected String toDebugString(long now) {
868 return super.toDebugString(now) + ", removeAccount"
869 + ", account " + mAccount;
870 }
871
872 public void run() throws RemoteException {
873 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
874 }
875
876 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700877 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
878 && !result.containsKey(AccountManager.KEY_INTENT)) {
879 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700880 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800881 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700882 }
883 IAccountManagerResponse response = getResponseAndClose();
884 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800885 if (Log.isLoggable(TAG, Log.VERBOSE)) {
886 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
887 + response);
888 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700889 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700890 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700891 try {
892 response.onResult(result2);
893 } catch (RemoteException e) {
894 // ignore
895 }
896 }
897 }
898 super.onResult(result);
899 }
900 }
901
Amith Yamasani04e0d262012-02-14 11:50:53 -0800902 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800903 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800904 removeAccountInternal(getUserAccountsForCaller(), account);
905 }
906
907 private void removeAccountInternal(UserAccounts accounts, Account account) {
908 synchronized (accounts.cacheLock) {
909 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800910 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
911 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800912 removeAccountFromCacheLocked(accounts, account);
913 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800914 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800915 if (accounts.userId == UserHandle.USER_OWNER) {
916 // Owner's account was removed, remove from any users that are sharing
917 // this account.
918 long id = Binder.clearCallingIdentity();
919 try {
920 List<UserInfo> users = mUserManager.getUsers(true);
921 for (UserInfo user : users) {
922 if (!user.isPrimary() && user.isRestricted()) {
923 removeSharedAccountAsUser(account, user.id);
924 }
925 }
926 } finally {
927 Binder.restoreCallingIdentity(id);
928 }
929 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700930 }
931
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400932 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700933 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800934 if (Log.isLoggable(TAG, Log.VERBOSE)) {
935 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
936 + ", caller's uid " + Binder.getCallingUid()
937 + ", pid " + Binder.getCallingPid());
938 }
Fred Quintana382601f2010-03-25 12:25:10 -0700939 if (accountType == null) throw new IllegalArgumentException("accountType is null");
940 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800941 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800942 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700943 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700944 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800945 synchronized (accounts.cacheLock) {
946 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800947 db.beginTransaction();
948 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800949 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800950 db.setTransactionSuccessful();
951 } finally {
952 db.endTransaction();
953 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700954 }
Fred Quintana60307342009-03-24 22:48:12 -0700955 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700956 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700957 }
958 }
959
Amith Yamasani04e0d262012-02-14 11:50:53 -0800960 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
961 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700962 if (authToken == null || accountType == null) {
963 return;
964 }
Fred Quintana33269202009-04-20 16:05:10 -0700965 Cursor cursor = db.rawQuery(
966 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
967 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
968 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
969 + " FROM " + TABLE_ACCOUNTS
970 + " JOIN " + TABLE_AUTHTOKENS
971 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
972 + " = " + AUTHTOKENS_ACCOUNTS_ID
973 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
974 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
975 new String[]{authToken, accountType});
976 try {
977 while (cursor.moveToNext()) {
978 long authTokenId = cursor.getLong(0);
979 String accountName = cursor.getString(1);
980 String authTokenType = cursor.getString(2);
981 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800982 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800983 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700984 }
Fred Quintana33269202009-04-20 16:05:10 -0700985 } finally {
986 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700987 }
988 }
989
Amith Yamasani04e0d262012-02-14 11:50:53 -0800990 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
991 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700992 if (account == null || type == null) {
993 return false;
994 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700995 cancelNotification(getSigninRequiredNotificationId(accounts, account),
996 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800997 synchronized (accounts.cacheLock) {
998 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800999 db.beginTransaction();
1000 try {
1001 long accountId = getAccountIdLocked(db, account);
1002 if (accountId < 0) {
1003 return false;
1004 }
1005 db.delete(TABLE_AUTHTOKENS,
1006 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1007 new String[]{type});
1008 ContentValues values = new ContentValues();
1009 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1010 values.put(AUTHTOKENS_TYPE, type);
1011 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1012 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1013 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001014 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001015 return true;
1016 }
Fred Quintana33269202009-04-20 16:05:10 -07001017 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001018 } finally {
1019 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001020 }
Fred Quintana60307342009-03-24 22:48:12 -07001021 }
1022 }
1023
Fred Quintanaa698f422009-04-08 19:14:54 -07001024 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001025 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1026 Log.v(TAG, "peekAuthToken: " + account
1027 + ", authTokenType " + authTokenType
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");
1032 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001033 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001034 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001035 long identityToken = clearCallingIdentity();
1036 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001037 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001038 } finally {
1039 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001040 }
Fred Quintana60307342009-03-24 22:48:12 -07001041 }
1042
Fred Quintanaa698f422009-04-08 19:14:54 -07001043 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001044 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1045 Log.v(TAG, "setAuthToken: " + account
1046 + ", authTokenType " + authTokenType
1047 + ", caller's uid " + Binder.getCallingUid()
1048 + ", pid " + Binder.getCallingPid());
1049 }
Fred Quintana382601f2010-03-25 12:25:10 -07001050 if (account == null) throw new IllegalArgumentException("account is null");
1051 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001052 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001053 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001054 long identityToken = clearCallingIdentity();
1055 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001056 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001057 } finally {
1058 restoreCallingIdentity(identityToken);
1059 }
Fred Quintana60307342009-03-24 22:48:12 -07001060 }
1061
Fred Quintanaa698f422009-04-08 19:14:54 -07001062 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001063 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1064 Log.v(TAG, "setAuthToken: " + account
1065 + ", caller's uid " + Binder.getCallingUid()
1066 + ", pid " + Binder.getCallingPid());
1067 }
Fred Quintana382601f2010-03-25 12:25:10 -07001068 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001069 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001070 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001071 long identityToken = clearCallingIdentity();
1072 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001073 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001074 } finally {
1075 restoreCallingIdentity(identityToken);
1076 }
Fred Quintana60307342009-03-24 22:48:12 -07001077 }
1078
Amith Yamasani04e0d262012-02-14 11:50:53 -08001079 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001080 if (account == null) {
1081 return;
1082 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001083 synchronized (accounts.cacheLock) {
1084 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001085 db.beginTransaction();
1086 try {
1087 final ContentValues values = new ContentValues();
1088 values.put(ACCOUNTS_PASSWORD, password);
1089 final long accountId = getAccountIdLocked(db, account);
1090 if (accountId >= 0) {
1091 final String[] argsAccountId = {String.valueOf(accountId)};
1092 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1093 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001094 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001095 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001096 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001097 } finally {
1098 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001099 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001100 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001101 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001102 }
1103
Amith Yamasani04e0d262012-02-14 11:50:53 -08001104 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001105 Log.i(TAG, "the accounts changed, sending broadcast of "
1106 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001107 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001108 }
1109
Fred Quintanaa698f422009-04-08 19:14:54 -07001110 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001111 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1112 Log.v(TAG, "clearPassword: " + account
1113 + ", caller's uid " + Binder.getCallingUid()
1114 + ", pid " + Binder.getCallingPid());
1115 }
Fred Quintana382601f2010-03-25 12:25:10 -07001116 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001117 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001118 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001119 long identityToken = clearCallingIdentity();
1120 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001121 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001122 } finally {
1123 restoreCallingIdentity(identityToken);
1124 }
Fred Quintana60307342009-03-24 22:48:12 -07001125 }
1126
Fred Quintanaa698f422009-04-08 19:14:54 -07001127 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001128 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1129 Log.v(TAG, "setUserData: " + account
1130 + ", key " + key
1131 + ", caller's uid " + Binder.getCallingUid()
1132 + ", pid " + Binder.getCallingPid());
1133 }
Fred Quintana382601f2010-03-25 12:25:10 -07001134 if (key == null) throw new IllegalArgumentException("key is null");
1135 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001136 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001137 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001138 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001139 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001140 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001141 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001142 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001143 }
1144 }
1145
Amith Yamasani04e0d262012-02-14 11:50:53 -08001146 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1147 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001148 if (account == null || key == null) {
1149 return;
1150 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001151 synchronized (accounts.cacheLock) {
1152 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001153 db.beginTransaction();
1154 try {
1155 long accountId = getAccountIdLocked(db, account);
1156 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001157 return;
1158 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001159 long extrasId = getExtrasIdLocked(db, accountId, key);
1160 if (extrasId < 0 ) {
1161 extrasId = insertExtraLocked(db, accountId, key, value);
1162 if (extrasId < 0) {
1163 return;
1164 }
1165 } else {
1166 ContentValues values = new ContentValues();
1167 values.put(EXTRAS_VALUE, value);
1168 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1169 return;
1170 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001171
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001172 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001173 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001174 db.setTransactionSuccessful();
1175 } finally {
1176 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001177 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001178 }
1179 }
1180
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001181 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001182 if (result == null) {
1183 Log.e(TAG, "the result is unexpectedly null", new Exception());
1184 }
1185 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1186 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1187 + response);
1188 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001189 try {
1190 response.onResult(result);
1191 } catch (RemoteException e) {
1192 // if the caller is dead then there is no one to care about remote
1193 // exceptions
1194 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1195 Log.v(TAG, "failure while notifying response", e);
1196 }
1197 }
1198 }
1199
Fred Quintanad9640ec2012-05-23 12:37:00 -07001200 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1201 final String authTokenType)
1202 throws RemoteException {
1203 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001204 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1205
Fred Quintanad9640ec2012-05-23 12:37:00 -07001206 final int callingUid = getCallingUid();
1207 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001208 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001209 throw new SecurityException("can only call from system");
1210 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001211 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001212 long identityToken = clearCallingIdentity();
1213 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001214 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001215 false /* stripAuthTokenFromResult */) {
1216 protected String toDebugString(long now) {
1217 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001218 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001219 + ", authTokenType " + authTokenType;
1220 }
1221
1222 public void run() throws RemoteException {
1223 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1224 }
1225
1226 public void onResult(Bundle result) {
1227 if (result != null) {
1228 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1229 Bundle bundle = new Bundle();
1230 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1231 super.onResult(bundle);
1232 return;
1233 } else {
1234 super.onResult(result);
1235 }
1236 }
1237 }.bind();
1238 } finally {
1239 restoreCallingIdentity(identityToken);
1240 }
1241 }
1242
Fred Quintanaa698f422009-04-08 19:14:54 -07001243 public void getAuthToken(IAccountManagerResponse response, final Account account,
1244 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001245 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001246 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1247 Log.v(TAG, "getAuthToken: " + account
1248 + ", response " + response
1249 + ", authTokenType " + authTokenType
1250 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1251 + ", expectActivityLaunch " + expectActivityLaunch
1252 + ", caller's uid " + Binder.getCallingUid()
1253 + ", pid " + Binder.getCallingPid());
1254 }
Fred Quintana382601f2010-03-25 12:25:10 -07001255 if (response == null) throw new IllegalArgumentException("response is null");
1256 if (account == null) throw new IllegalArgumentException("account is null");
1257 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001258 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001259 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001260 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1261 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1262 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001263 final boolean customTokens =
1264 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1265
1266 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001267 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001268 final boolean permissionGranted = customTokens ||
1269 permissionIsGranted(account, authTokenType, callerUid);
1270
Costin Manolachec6684f92011-01-14 11:25:39 -08001271 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1272 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001273 // let authenticator know the identity of the caller
1274 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1275 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1276 if (notifyOnAuthFailure) {
1277 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001278 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001279
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001280 long identityToken = clearCallingIdentity();
1281 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001282 // if the caller has permission, do the peek. otherwise go the more expensive
1283 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001284 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001285 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001286 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001287 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001288 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1289 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1290 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001291 onResult(response, result);
1292 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001293 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001294 }
1295
Amith Yamasani04e0d262012-02-14 11:50:53 -08001296 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001297 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001298 protected String toDebugString(long now) {
1299 if (loginOptions != null) loginOptions.keySet();
1300 return super.toDebugString(now) + ", getAuthToken"
1301 + ", " + account
1302 + ", authTokenType " + authTokenType
1303 + ", loginOptions " + loginOptions
1304 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1305 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001306
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001307 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001308 // If the caller doesn't have permission then create and return the
1309 // "grant permission" intent instead of the "getAuthToken" intent.
1310 if (!permissionGranted) {
1311 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1312 } else {
1313 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1314 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001315 }
1316
1317 public void onResult(Bundle result) {
1318 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001319 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001320 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1321 new AccountAuthenticatorResponse(this),
1322 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001323 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001324 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001325 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001326 onResult(bundle);
1327 return;
1328 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001329 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001330 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001331 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1332 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001333 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001334 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001335 "the type and name should not be empty");
1336 return;
1337 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001338 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001339 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001340 authTokenType, authToken);
1341 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001342 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001343
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001344 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001345 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001346 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001347 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001348 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001349 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001350 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001351 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001352 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001353 }.bind();
1354 } finally {
1355 restoreCallingIdentity(identityToken);
1356 }
Fred Quintana60307342009-03-24 22:48:12 -07001357 }
1358
Dianne Hackborn41203752012-08-31 14:05:51 -07001359 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1360 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001361 int uid = intent.getIntExtra(
1362 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1363 String authTokenType = intent.getStringExtra(
1364 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1365 String authTokenLabel = intent.getStringExtra(
1366 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1367
1368 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1369 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001370 final String titleAndSubtitle =
1371 mContext.getString(R.string.permission_request_notification_with_subtitle,
1372 account.name);
1373 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001374 String title = titleAndSubtitle;
1375 String subtitle = "";
1376 if (index > 0) {
1377 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001378 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001379 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001380 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001381 n.setLatestEventInfo(mContext, title, subtitle,
1382 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001383 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1384 installNotification(getCredentialPermissionNotificationId(
1385 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001386 }
1387
Costin Manolache5f383ad92010-12-02 16:44:46 -08001388 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1389 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001390
1391 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001392 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001393 // Since it was set in Eclair+ we can't change it without breaking apps using
1394 // the intent from a non-Activity context.
1395 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001396 intent.addCategory(
1397 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001398
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001399 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001400 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1401 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001402 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001403
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001404 return intent;
1405 }
1406
1407 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1408 int uid) {
1409 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001410 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001411 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001412 final Pair<Pair<Account, String>, Integer> key =
1413 new Pair<Pair<Account, String>, Integer>(
1414 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001415 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001416 if (id == null) {
1417 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001418 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001419 }
1420 }
1421 return id;
1422 }
1423
Amith Yamasani04e0d262012-02-14 11:50:53 -08001424 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001425 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001426 synchronized (accounts.signinRequiredNotificationIds) {
1427 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001428 if (id == null) {
1429 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001430 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001431 }
1432 }
1433 return id;
1434 }
1435
Amith Yamasani27db4682013-03-30 17:07:47 -07001436 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001437 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001438 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001439 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1440 Log.v(TAG, "addAccount: accountType " + accountType
1441 + ", response " + response
1442 + ", authTokenType " + authTokenType
1443 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1444 + ", expectActivityLaunch " + expectActivityLaunch
1445 + ", caller's uid " + Binder.getCallingUid()
1446 + ", pid " + Binder.getCallingPid());
1447 }
Fred Quintana382601f2010-03-25 12:25:10 -07001448 if (response == null) throw new IllegalArgumentException("response is null");
1449 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001450 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001451
Amith Yamasani71e6c692013-03-24 17:39:28 -07001452 // Is user disallowed from modifying accounts?
Amith Yamasani27db4682013-03-30 17:07:47 -07001453 if (!canUserModifyAccounts(Binder.getCallingUid())) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001454 try {
1455 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1456 "User is not allowed to add an account!");
1457 } catch (RemoteException re) {
1458 }
1459 return;
1460 }
1461
Amith Yamasani04e0d262012-02-14 11:50:53 -08001462 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001463 final int pid = Binder.getCallingPid();
1464 final int uid = Binder.getCallingUid();
1465 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1466 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1467 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1468
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001469 long identityToken = clearCallingIdentity();
1470 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001471 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001472 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001473 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001474 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001475 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001476 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001477
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001478 protected String toDebugString(long now) {
1479 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001480 + ", accountType " + accountType
1481 + ", requiredFeatures "
1482 + (requiredFeatures != null
1483 ? TextUtils.join(",", requiredFeatures)
1484 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001485 }
1486 }.bind();
1487 } finally {
1488 restoreCallingIdentity(identityToken);
1489 }
Fred Quintana60307342009-03-24 22:48:12 -07001490 }
1491
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001492 @Override
1493 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1494 final Account account, final Bundle options, final boolean expectActivityLaunch,
1495 int userId) {
1496 // Only allow the system process to read accounts of other users
1497 if (userId != UserHandle.getCallingUserId()
Amith Yamasani27db4682013-03-30 17:07:47 -07001498 && Binder.getCallingUid() != Process.myUid()) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001499 throw new SecurityException("User " + UserHandle.getCallingUserId()
1500 + " trying to confirm account credentials for " + userId);
1501 }
1502
Fred Quintana56285a62010-12-02 14:20:51 -08001503 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1504 Log.v(TAG, "confirmCredentials: " + account
1505 + ", response " + response
1506 + ", expectActivityLaunch " + expectActivityLaunch
1507 + ", caller's uid " + Binder.getCallingUid()
1508 + ", pid " + Binder.getCallingPid());
1509 }
Fred Quintana382601f2010-03-25 12:25:10 -07001510 if (response == null) throw new IllegalArgumentException("response is null");
1511 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001512 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001513 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001514 long identityToken = clearCallingIdentity();
1515 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001516 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001517 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001518 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001519 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001520 }
1521 protected String toDebugString(long now) {
1522 return super.toDebugString(now) + ", confirmCredentials"
1523 + ", " + account;
1524 }
1525 }.bind();
1526 } finally {
1527 restoreCallingIdentity(identityToken);
1528 }
Fred Quintana60307342009-03-24 22:48:12 -07001529 }
1530
Fred Quintanaa698f422009-04-08 19:14:54 -07001531 public void updateCredentials(IAccountManagerResponse response, final Account account,
1532 final String authTokenType, final boolean expectActivityLaunch,
1533 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001534 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1535 Log.v(TAG, "updateCredentials: " + account
1536 + ", response " + response
1537 + ", authTokenType " + authTokenType
1538 + ", expectActivityLaunch " + expectActivityLaunch
1539 + ", caller's uid " + Binder.getCallingUid()
1540 + ", pid " + Binder.getCallingPid());
1541 }
Fred Quintana382601f2010-03-25 12:25:10 -07001542 if (response == null) throw new IllegalArgumentException("response is null");
1543 if (account == null) throw new IllegalArgumentException("account is null");
1544 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001545 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001546 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001547 long identityToken = clearCallingIdentity();
1548 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001549 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001550 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001551 public void run() throws RemoteException {
1552 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1553 }
1554 protected String toDebugString(long now) {
1555 if (loginOptions != null) loginOptions.keySet();
1556 return super.toDebugString(now) + ", updateCredentials"
1557 + ", " + account
1558 + ", authTokenType " + authTokenType
1559 + ", loginOptions " + loginOptions;
1560 }
1561 }.bind();
1562 } finally {
1563 restoreCallingIdentity(identityToken);
1564 }
Fred Quintana60307342009-03-24 22:48:12 -07001565 }
1566
Fred Quintanaa698f422009-04-08 19:14:54 -07001567 public void editProperties(IAccountManagerResponse response, final String accountType,
1568 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001569 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1570 Log.v(TAG, "editProperties: accountType " + accountType
1571 + ", response " + response
1572 + ", expectActivityLaunch " + expectActivityLaunch
1573 + ", caller's uid " + Binder.getCallingUid()
1574 + ", pid " + Binder.getCallingPid());
1575 }
Fred Quintana382601f2010-03-25 12:25:10 -07001576 if (response == null) throw new IllegalArgumentException("response is null");
1577 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001578 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001579 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001580 long identityToken = clearCallingIdentity();
1581 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001582 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001583 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001584 public void run() throws RemoteException {
1585 mAuthenticator.editProperties(this, mAccountType);
1586 }
1587 protected String toDebugString(long now) {
1588 return super.toDebugString(now) + ", editProperties"
1589 + ", accountType " + accountType;
1590 }
1591 }.bind();
1592 } finally {
1593 restoreCallingIdentity(identityToken);
1594 }
Fred Quintana60307342009-03-24 22:48:12 -07001595 }
1596
Fred Quintana33269202009-04-20 16:05:10 -07001597 private class GetAccountsByTypeAndFeatureSession extends Session {
1598 private final String[] mFeatures;
1599 private volatile Account[] mAccountsOfType = null;
1600 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1601 private volatile int mCurrentAccount = 0;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001602 private int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001603
Amith Yamasani04e0d262012-02-14 11:50:53 -08001604 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001605 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001606 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001607 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001608 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001609 mFeatures = features;
1610 }
1611
1612 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001613 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001614 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1615 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001616 }
Fred Quintana33269202009-04-20 16:05:10 -07001617 // check whether each account matches the requested features
1618 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1619 mCurrentAccount = 0;
1620
1621 checkAccount();
1622 }
1623
1624 public void checkAccount() {
1625 if (mCurrentAccount >= mAccountsOfType.length) {
1626 sendResult();
1627 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001628 }
Fred Quintana33269202009-04-20 16:05:10 -07001629
Fred Quintana29e94b82010-03-10 12:11:51 -08001630 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1631 if (accountAuthenticator == null) {
1632 // It is possible that the authenticator has died, which is indicated by
1633 // mAuthenticator being set to null. If this happens then just abort.
1634 // There is no need to send back a result or error in this case since
1635 // that already happened when mAuthenticator was cleared.
1636 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1637 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1638 + " connected to the authenticator, " + toDebugString());
1639 }
1640 return;
1641 }
Fred Quintana33269202009-04-20 16:05:10 -07001642 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001643 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001644 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001645 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001646 }
1647 }
1648
1649 public void onResult(Bundle result) {
1650 mNumResults++;
1651 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001652 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001653 return;
1654 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001655 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001656 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1657 }
1658 mCurrentAccount++;
1659 checkAccount();
1660 }
1661
1662 public void sendResult() {
1663 IAccountManagerResponse response = getResponseAndClose();
1664 if (response != null) {
1665 try {
1666 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1667 for (int i = 0; i < accounts.length; i++) {
1668 accounts[i] = mAccountsWithFeatures.get(i);
1669 }
Fred Quintana56285a62010-12-02 14:20:51 -08001670 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1671 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1672 + response);
1673 }
Fred Quintana33269202009-04-20 16:05:10 -07001674 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001675 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001676 response.onResult(result);
1677 } catch (RemoteException e) {
1678 // if the caller is dead then there is no one to care about remote exceptions
1679 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1680 Log.v(TAG, "failure while notifying response", e);
1681 }
1682 }
1683 }
1684 }
1685
1686
1687 protected String toDebugString(long now) {
1688 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1689 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1690 }
1691 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001692
Amith Yamasani04e0d262012-02-14 11:50:53 -08001693 /**
1694 * Returns the accounts for a specific user
1695 * @hide
1696 */
1697 public Account[] getAccounts(int userId) {
1698 checkReadAccountsPermission();
1699 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001700 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001701 long identityToken = clearCallingIdentity();
1702 try {
1703 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001704 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001705 }
1706 } finally {
1707 restoreCallingIdentity(identityToken);
1708 }
1709 }
1710
Amith Yamasanif29f2362012-04-05 18:29:52 -07001711 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001712 * Returns accounts for all running users.
1713 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001714 * @hide
1715 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001716 public AccountAndUser[] getRunningAccounts() {
1717 final int[] runningUserIds;
1718 try {
1719 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1720 } catch (RemoteException e) {
1721 // Running in system_server; should never happen
1722 throw new RuntimeException(e);
1723 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001724 return getAccounts(runningUserIds);
1725 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001726
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001727 /** {@hide} */
1728 public AccountAndUser[] getAllAccounts() {
1729 final List<UserInfo> users = getUserManager().getUsers();
1730 final int[] userIds = new int[users.size()];
1731 for (int i = 0; i < userIds.length; i++) {
1732 userIds[i] = users.get(i).id;
1733 }
1734 return getAccounts(userIds);
1735 }
1736
1737 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001738 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1739 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001740 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001741 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001742 if (userAccounts == null) continue;
1743 synchronized (userAccounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001744 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
Amith Yamasani27db4682013-03-30 17:07:47 -07001745 Binder.getCallingUid(), null);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001746 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001747 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001748 }
1749 }
1750 }
1751 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001752
1753 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1754 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001755 }
1756
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001757 @Override
1758 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001759 return getAccountsAsUser(type, userId, null, -1);
1760 }
1761
1762 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
1763 int packageUid) {
1764 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001765 // Only allow the system process to read accounts of other users
1766 if (userId != UserHandle.getCallingUserId()
Amith Yamasani27db4682013-03-30 17:07:47 -07001767 && callingUid != Process.myUid()) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001768 throw new SecurityException("User " + UserHandle.getCallingUserId()
1769 + " trying to get account for " + userId);
1770 }
1771
Fred Quintana56285a62010-12-02 14:20:51 -08001772 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1773 Log.v(TAG, "getAccounts: accountType " + type
1774 + ", caller's uid " + Binder.getCallingUid()
1775 + ", pid " + Binder.getCallingPid());
1776 }
Amith Yamasani27db4682013-03-30 17:07:47 -07001777 // If the original calling app was using the framework account chooser activity, we'll
1778 // be passed in the original caller's uid here, which is what should be used for filtering.
1779 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
1780 callingUid = packageUid;
1781 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001782 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001783 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001784 long identityToken = clearCallingIdentity();
1785 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001786 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001787 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001788 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001789 } finally {
1790 restoreCallingIdentity(identityToken);
1791 }
1792 }
1793
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001794 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001795 public boolean addSharedAccountAsUser(Account account, int userId) {
1796 userId = handleIncomingUser(userId);
1797 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1798 ContentValues values = new ContentValues();
1799 values.put(ACCOUNTS_NAME, account.name);
1800 values.put(ACCOUNTS_TYPE, account.type);
1801 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1802 new String[] {account.name, account.type});
1803 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1804 if (accountId < 0) {
1805 Log.w(TAG, "insertAccountIntoDatabase: " + account
1806 + ", skipping the DB insert failed");
1807 return false;
1808 }
1809 return true;
1810 }
1811
1812 @Override
1813 public boolean removeSharedAccountAsUser(Account account, int userId) {
1814 userId = handleIncomingUser(userId);
1815 UserAccounts accounts = getUserAccounts(userId);
1816 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1817 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1818 new String[] {account.name, account.type});
1819 if (r > 0) {
1820 removeAccountInternal(accounts, account);
1821 }
1822 return r > 0;
1823 }
1824
1825 @Override
1826 public Account[] getSharedAccountsAsUser(int userId) {
1827 userId = handleIncomingUser(userId);
1828 UserAccounts accounts = getUserAccounts(userId);
1829 ArrayList<Account> accountList = new ArrayList<Account>();
1830 Cursor cursor = null;
1831 try {
1832 cursor = accounts.openHelper.getReadableDatabase()
1833 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1834 null, null, null, null, null);
1835 if (cursor != null && cursor.moveToFirst()) {
1836 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1837 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1838 do {
1839 accountList.add(new Account(cursor.getString(nameIndex),
1840 cursor.getString(typeIndex)));
1841 } while (cursor.moveToNext());
1842 }
1843 } finally {
1844 if (cursor != null) {
1845 cursor.close();
1846 }
1847 }
1848 Account[] accountArray = new Account[accountList.size()];
1849 accountList.toArray(accountArray);
1850 return accountArray;
1851 }
1852
1853 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001854 public Account[] getAccounts(String type) {
1855 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1856 }
1857
Amith Yamasani27db4682013-03-30 17:07:47 -07001858 @Override
1859 public Account[] getAccountsForPackage(String packageName, int uid) {
1860 int callingUid = Binder.getCallingUid();
1861 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
1862 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
1863 + callingUid + " with uid=" + uid);
1864 }
1865 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
1866 }
1867
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001868 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001869 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001870 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1871 Log.v(TAG, "getAccounts: accountType " + type
1872 + ", response " + response
1873 + ", features " + stringArrayToString(features)
1874 + ", caller's uid " + Binder.getCallingUid()
1875 + ", pid " + Binder.getCallingPid());
1876 }
Fred Quintana382601f2010-03-25 12:25:10 -07001877 if (response == null) throw new IllegalArgumentException("response is null");
1878 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001879 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001880 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001881 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001882 long identityToken = clearCallingIdentity();
1883 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001884 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001885 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001886 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001887 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001888 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001889 Bundle result = new Bundle();
1890 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1891 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001892 return;
1893 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001894 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
1895 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001896 } finally {
1897 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001898 }
1899 }
1900
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001901 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001902 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001903 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001904 try {
1905 if (cursor.moveToNext()) {
1906 return cursor.getLong(0);
1907 }
1908 return -1;
1909 } finally {
1910 cursor.close();
1911 }
1912 }
1913
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001914 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001915 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1916 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1917 new String[]{key}, null, null, null);
1918 try {
1919 if (cursor.moveToNext()) {
1920 return cursor.getLong(0);
1921 }
1922 return -1;
1923 } finally {
1924 cursor.close();
1925 }
1926 }
1927
Fred Quintanaa698f422009-04-08 19:14:54 -07001928 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001929 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001930 IAccountManagerResponse mResponse;
1931 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001932 final boolean mExpectActivityLaunch;
1933 final long mCreationTime;
1934
Fred Quintana33269202009-04-20 16:05:10 -07001935 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001936 private int mNumRequestContinued = 0;
1937 private int mNumErrors = 0;
1938
Fred Quintana60307342009-03-24 22:48:12 -07001939 IAccountAuthenticator mAuthenticator = null;
1940
Fred Quintana8570f742010-02-18 10:32:54 -08001941 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001942 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001943
Amith Yamasani04e0d262012-02-14 11:50:53 -08001944 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001945 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001946 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001947 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001948 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001949 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001950 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001951 mResponse = response;
1952 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001953 mExpectActivityLaunch = expectActivityLaunch;
1954 mCreationTime = SystemClock.elapsedRealtime();
1955 synchronized (mSessions) {
1956 mSessions.put(toString(), this);
1957 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001958 if (response != null) {
1959 try {
1960 response.asBinder().linkToDeath(this, 0 /* flags */);
1961 } catch (RemoteException e) {
1962 mResponse = null;
1963 binderDied();
1964 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001965 }
Fred Quintana60307342009-03-24 22:48:12 -07001966 }
1967
Fred Quintanaa698f422009-04-08 19:14:54 -07001968 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001969 if (mResponse == null) {
1970 // this session has already been closed
1971 return null;
1972 }
Fred Quintana60307342009-03-24 22:48:12 -07001973 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001974 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001975 return response;
1976 }
1977
Fred Quintanaa698f422009-04-08 19:14:54 -07001978 private void close() {
1979 synchronized (mSessions) {
1980 if (mSessions.remove(toString()) == null) {
1981 // the session was already closed, so bail out now
1982 return;
1983 }
1984 }
1985 if (mResponse != null) {
1986 // stop listening for response deaths
1987 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1988
1989 // clear this so that we don't accidentally send any further results
1990 mResponse = null;
1991 }
1992 cancelTimeout();
1993 unbind();
1994 }
1995
1996 public void binderDied() {
1997 mResponse = null;
1998 close();
1999 }
2000
2001 protected String toDebugString() {
2002 return toDebugString(SystemClock.elapsedRealtime());
2003 }
2004
2005 protected String toDebugString(long now) {
2006 return "Session: expectLaunch " + mExpectActivityLaunch
2007 + ", connected " + (mAuthenticator != null)
2008 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2009 + "/" + mNumErrors + ")"
2010 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2011 }
2012
Fred Quintana60307342009-03-24 22:48:12 -07002013 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002014 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2015 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2016 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002017 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002018 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002019 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002020 }
2021 }
2022
2023 private void unbind() {
2024 if (mAuthenticator != null) {
2025 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002026 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002027 }
2028 }
2029
2030 public void scheduleTimeout() {
2031 mMessageHandler.sendMessageDelayed(
2032 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2033 }
2034
2035 public void cancelTimeout() {
2036 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2037 }
2038
Fred Quintanab839afc2009-10-14 15:57:28 -07002039 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002040 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002041 try {
2042 run();
2043 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002044 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002045 "remote exception");
2046 }
Fred Quintana60307342009-03-24 22:48:12 -07002047 }
2048
Fred Quintanab839afc2009-10-14 15:57:28 -07002049 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002050 mAuthenticator = null;
2051 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002052 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002053 try {
2054 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2055 "disconnected");
2056 } catch (RemoteException e) {
2057 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2058 Log.v(TAG, "Session.onServiceDisconnected: "
2059 + "caught RemoteException while responding", e);
2060 }
2061 }
Fred Quintana60307342009-03-24 22:48:12 -07002062 }
2063 }
2064
Fred Quintanab839afc2009-10-14 15:57:28 -07002065 public abstract void run() throws RemoteException;
2066
Fred Quintana60307342009-03-24 22:48:12 -07002067 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002068 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002069 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002070 try {
2071 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2072 "timeout");
2073 } catch (RemoteException e) {
2074 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2075 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2076 e);
2077 }
2078 }
Fred Quintana60307342009-03-24 22:48:12 -07002079 }
2080 }
2081
Fred Quintanaa698f422009-04-08 19:14:54 -07002082 public void onResult(Bundle result) {
2083 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002084 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
2085 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2086 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002087 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2088 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002089 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2090 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002091 }
Fred Quintana60307342009-03-24 22:48:12 -07002092 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002093 IAccountManagerResponse response;
2094 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002095 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002096 response = mResponse;
2097 } else {
2098 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002099 }
Fred Quintana60307342009-03-24 22:48:12 -07002100 if (response != null) {
2101 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002102 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002103 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2104 Log.v(TAG, getClass().getSimpleName()
2105 + " calling onError() on response " + response);
2106 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002107 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002108 "null bundle returned");
2109 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002110 if (mStripAuthTokenFromResult) {
2111 result.remove(AccountManager.KEY_AUTHTOKEN);
2112 }
Fred Quintana56285a62010-12-02 14:20:51 -08002113 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2114 Log.v(TAG, getClass().getSimpleName()
2115 + " calling onResult() on response " + response);
2116 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002117 response.onResult(result);
2118 }
Fred Quintana60307342009-03-24 22:48:12 -07002119 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002120 // if the caller is dead then there is no one to care about remote exceptions
2121 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2122 Log.v(TAG, "failure while notifying response", e);
2123 }
Fred Quintana60307342009-03-24 22:48:12 -07002124 }
2125 }
2126 }
Fred Quintana60307342009-03-24 22:48:12 -07002127
Fred Quintanaa698f422009-04-08 19:14:54 -07002128 public void onRequestContinued() {
2129 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002130 }
2131
2132 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002133 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002134 IAccountManagerResponse response = getResponseAndClose();
2135 if (response != null) {
2136 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002137 Log.v(TAG, getClass().getSimpleName()
2138 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002139 }
2140 try {
2141 response.onError(errorCode, errorMessage);
2142 } catch (RemoteException e) {
2143 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2144 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2145 }
2146 }
2147 } else {
2148 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2149 Log.v(TAG, "Session.onError: already closed");
2150 }
Fred Quintana60307342009-03-24 22:48:12 -07002151 }
2152 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002153
2154 /**
2155 * find the component name for the authenticator and initiate a bind
2156 * if no authenticator or the bind fails then return false, otherwise return true
2157 */
2158 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002159 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2160 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2161 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002162 if (authenticatorInfo == null) {
2163 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2164 Log.v(TAG, "there is no authenticator for " + authenticatorType
2165 + ", bailing out");
2166 }
2167 return false;
2168 }
2169
2170 Intent intent = new Intent();
2171 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2172 intent.setComponent(authenticatorInfo.componentName);
2173 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2174 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2175 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002176 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2177 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002178 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2179 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2180 }
2181 return false;
2182 }
2183
2184
2185 return true;
2186 }
Fred Quintana60307342009-03-24 22:48:12 -07002187 }
2188
2189 private class MessageHandler extends Handler {
2190 MessageHandler(Looper looper) {
2191 super(looper);
2192 }
Costin Manolache3348f142009-09-29 18:58:36 -07002193
Fred Quintana60307342009-03-24 22:48:12 -07002194 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002195 switch (msg.what) {
2196 case MESSAGE_TIMED_OUT:
2197 Session session = (Session)msg.obj;
2198 session.onTimedOut();
2199 break;
2200
Amith Yamasani5be347b2013-03-31 17:44:31 -07002201 case MESSAGE_COPY_SHARED_ACCOUNT:
2202 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2203 break;
2204
Fred Quintana60307342009-03-24 22:48:12 -07002205 default:
2206 throw new IllegalStateException("unhandled message: " + msg.what);
2207 }
2208 }
2209 }
2210
Amith Yamasani04e0d262012-02-14 11:50:53 -08002211 private static String getDatabaseName(int userId) {
2212 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002213 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002214 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002215 // Migrate old file, if it exists, to the new location.
2216 // Make sure the new file doesn't already exist. A dummy file could have been
2217 // accidentally created in the old location, causing the new one to become corrupted
2218 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002219 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002220 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002221 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002222 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002223 if (!userDir.exists()) {
2224 if (!userDir.mkdirs()) {
2225 throw new IllegalStateException("User dir cannot be created: " + userDir);
2226 }
2227 }
2228 if (!oldFile.renameTo(databaseFile)) {
2229 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2230 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002231 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002232 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002233 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002234 }
2235
Amith Yamasani04e0d262012-02-14 11:50:53 -08002236 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002237
Amith Yamasani04e0d262012-02-14 11:50:53 -08002238 public DatabaseHelper(Context context, int userId) {
2239 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002240 }
2241
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002242 /**
2243 * This call needs to be made while the mCacheLock is held. The way to
2244 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2245 * @param db The database.
2246 */
Fred Quintana60307342009-03-24 22:48:12 -07002247 @Override
2248 public void onCreate(SQLiteDatabase db) {
2249 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2250 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2251 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2252 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2253 + ACCOUNTS_PASSWORD + " TEXT, "
2254 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2255
2256 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2257 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2258 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2259 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2260 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2261 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2262
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002263 createGrantsTable(db);
2264
Fred Quintana60307342009-03-24 22:48:12 -07002265 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2266 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2267 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2268 + EXTRAS_KEY + " TEXT NOT NULL, "
2269 + EXTRAS_VALUE + " TEXT, "
2270 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2271
2272 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2273 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2274 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002275
Amith Yamasani67df64b2012-12-14 12:09:36 -08002276 createSharedAccountsTable(db);
2277
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002278 createAccountsDeletionTrigger(db);
2279 }
2280
Amith Yamasani67df64b2012-12-14 12:09:36 -08002281 private void createSharedAccountsTable(SQLiteDatabase db) {
2282 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2283 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2284 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2285 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2286 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2287 }
2288
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002289 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002290 db.execSQL(""
2291 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2292 + " BEGIN"
2293 + " DELETE FROM " + TABLE_AUTHTOKENS
2294 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2295 + " DELETE FROM " + TABLE_EXTRAS
2296 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002297 + " DELETE FROM " + TABLE_GRANTS
2298 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002299 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002300 }
2301
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002302 private void createGrantsTable(SQLiteDatabase db) {
2303 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2304 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2305 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2306 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2307 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2308 + "," + GRANTS_GRANTEE_UID + "))");
2309 }
2310
Fred Quintana60307342009-03-24 22:48:12 -07002311 @Override
2312 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002313 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002314
Fred Quintanaa698f422009-04-08 19:14:54 -07002315 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002316 // no longer need to do anything since the work is done
2317 // when upgrading from version 2
2318 oldVersion++;
2319 }
2320
2321 if (oldVersion == 2) {
2322 createGrantsTable(db);
2323 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2324 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002325 oldVersion++;
2326 }
Costin Manolache3348f142009-09-29 18:58:36 -07002327
2328 if (oldVersion == 3) {
2329 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2330 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2331 oldVersion++;
2332 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002333
2334 if (oldVersion == 4) {
2335 createSharedAccountsTable(db);
2336 oldVersion++;
2337 }
2338
2339 if (oldVersion != newVersion) {
2340 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2341 }
Fred Quintana60307342009-03-24 22:48:12 -07002342 }
2343
2344 @Override
2345 public void onOpen(SQLiteDatabase db) {
2346 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2347 }
2348 }
2349
Fred Quintana60307342009-03-24 22:48:12 -07002350 public IBinder onBind(Intent intent) {
2351 return asBinder();
2352 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002353
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002354 /**
2355 * Searches array of arguments for the specified string
2356 * @param args array of argument strings
2357 * @param value value to search for
2358 * @return true if the value is contained in the array
2359 */
2360 private static boolean scanArgs(String[] args, String value) {
2361 if (args != null) {
2362 for (String arg : args) {
2363 if (value.equals(arg)) {
2364 return true;
2365 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002366 }
2367 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002368 return false;
2369 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002370
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002371 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002372 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002373 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2374 != PackageManager.PERMISSION_GRANTED) {
2375 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2376 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2377 + " without permission " + android.Manifest.permission.DUMP);
2378 return;
2379 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002380 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002381 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002382
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002383 final List<UserInfo> users = getUserManager().getUsers();
2384 for (UserInfo user : users) {
2385 ipw.println("User " + user + ":");
2386 ipw.increaseIndent();
2387 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2388 ipw.println();
2389 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002390 }
2391 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002392
Amith Yamasani04e0d262012-02-14 11:50:53 -08002393 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2394 String[] args, boolean isCheckinRequest) {
2395 synchronized (userAccounts.cacheLock) {
2396 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002397
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002398 if (isCheckinRequest) {
2399 // This is a checkin request. *Only* upload the account types and the count of each.
2400 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2401 null, null, ACCOUNTS_TYPE, null, null);
2402 try {
2403 while (cursor.moveToNext()) {
2404 // print type,count
2405 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2406 }
2407 } finally {
2408 if (cursor != null) {
2409 cursor.close();
2410 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002411 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002412 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002413 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002414 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002415 fout.println("Accounts: " + accounts.length);
2416 for (Account account : accounts) {
2417 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002418 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002419
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002420 fout.println();
2421 synchronized (mSessions) {
2422 final long now = SystemClock.elapsedRealtime();
2423 fout.println("Active Sessions: " + mSessions.size());
2424 for (Session session : mSessions.values()) {
2425 fout.println(" " + session.toDebugString(now));
2426 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002427 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002428
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002429 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002430 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002431 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002432 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002433 }
2434
Amith Yamasani04e0d262012-02-14 11:50:53 -08002435 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002436 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002437 long identityToken = clearCallingIdentity();
2438 try {
2439 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2440 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2441 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002442
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002443 if (intent.getComponent() != null &&
2444 GrantCredentialsPermissionActivity.class.getName().equals(
2445 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002446 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002447 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002448 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002449 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002450 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2451 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002452 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002453 final String notificationTitleFormat =
2454 mContext.getText(R.string.notification_title).toString();
2455 n.setLatestEventInfo(mContext,
2456 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002457 message, PendingIntent.getActivityAsUser(
2458 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002459 null, user));
2460 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002461 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002462 } finally {
2463 restoreCallingIdentity(identityToken);
2464 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002465 }
2466
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002467 protected void installNotification(final int notificationId, final Notification n,
2468 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002469 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002470 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002471 }
2472
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002473 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002474 long identityToken = clearCallingIdentity();
2475 try {
2476 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002477 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002478 } finally {
2479 restoreCallingIdentity(identityToken);
2480 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002481 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002482
Fred Quintanab38eb142010-02-24 13:40:54 -08002483 /** Succeeds if any of the specified permissions are granted. */
2484 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002485 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002486
2487 for (String perm : permissions) {
2488 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2489 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002490 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002491 }
2492 return;
2493 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002494 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002495
2496 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002497 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002498 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002499 }
2500
Amith Yamasani67df64b2012-12-14 12:09:36 -08002501 private int handleIncomingUser(int userId) {
2502 try {
2503 return ActivityManagerNative.getDefault().handleIncomingUser(
2504 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2505 } catch (RemoteException re) {
2506 // Shouldn't happen, local.
2507 }
2508 return userId;
2509 }
2510
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002511 private boolean inSystemImage(int callingUid) {
2512 final int callingUserId = UserHandle.getUserId(callingUid);
2513
2514 final PackageManager userPackageManager;
2515 try {
2516 userPackageManager = mContext.createPackageContextAsUser(
2517 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2518 } catch (NameNotFoundException e) {
2519 return false;
2520 }
2521
2522 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002523 for (String name : packages) {
2524 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002525 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002526 if (packageInfo != null
2527 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002528 return true;
2529 }
2530 } catch (PackageManager.NameNotFoundException e) {
2531 return false;
2532 }
2533 }
2534 return false;
2535 }
2536
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002537 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002538 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002539 final boolean fromAuthenticator = account != null
2540 && hasAuthenticatorUid(account.type, callerUid);
2541 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002542 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002543 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2544 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002545 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002546 + ": is authenticator? " + fromAuthenticator
2547 + ", has explicit permission? " + hasExplicitGrants);
2548 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002549 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002550 }
2551
Fred Quintana1a231912009-10-15 11:31:30 -07002552 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002553 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002554 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002555 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002556 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002557 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002558 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002559 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002560 }
2561 }
2562 return false;
2563 }
2564
Amith Yamasani04e0d262012-02-14 11:50:53 -08002565 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2566 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002567 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002568 return true;
2569 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002570 UserAccounts accounts = getUserAccountsForCaller();
2571 synchronized (accounts.cacheLock) {
2572 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2573 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002574 account.name, account.type};
2575 final boolean permissionGranted =
2576 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2577 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2578 // TODO: Skip this check when running automated tests. Replace this
2579 // with a more general solution.
2580 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002581 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002582 + " but ignoring since device is in test harness.");
2583 return true;
2584 }
2585 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002586 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002587 }
2588
2589 private void checkCallingUidAgainstAuthenticator(Account account) {
2590 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002591 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002592 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2593 Log.w(TAG, msg);
2594 throw new SecurityException(msg);
2595 }
2596 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2597 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2598 }
2599 }
2600
2601 private void checkAuthenticateAccountsPermission(Account account) {
2602 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2603 checkCallingUidAgainstAuthenticator(account);
2604 }
2605
2606 private void checkReadAccountsPermission() {
2607 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2608 }
2609
2610 private void checkManageAccountsPermission() {
2611 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2612 }
2613
Fred Quintanab38eb142010-02-24 13:40:54 -08002614 private void checkManageAccountsOrUseCredentialsPermissions() {
2615 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2616 Manifest.permission.USE_CREDENTIALS);
2617 }
2618
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002619 private boolean canUserModifyAccounts(int callingUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002620 if (callingUid != Process.myUid()) {
2621 if (getUserManager().getUserRestrictions(
2622 new UserHandle(UserHandle.getUserId(callingUid)))
2623 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002624 return false;
2625 }
2626 }
2627 return true;
2628 }
2629
Fred Quintanad9640ec2012-05-23 12:37:00 -07002630 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2631 throws RemoteException {
2632 final int callingUid = getCallingUid();
2633
Amith Yamasani27db4682013-03-30 17:07:47 -07002634 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002635 throw new SecurityException();
2636 }
2637
2638 if (value) {
2639 grantAppPermission(account, authTokenType, uid);
2640 } else {
2641 revokeAppPermission(account, authTokenType, uid);
2642 }
2643 }
2644
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002645 /**
2646 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2647 * <p>
2648 * Although this is public it can only be accessed via the AccountManagerService object
2649 * which is in the system. This means we don't need to protect it with permissions.
2650 * @hide
2651 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002652 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002653 if (account == null || authTokenType == null) {
2654 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002655 return;
2656 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002657 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002658 synchronized (accounts.cacheLock) {
2659 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002660 db.beginTransaction();
2661 try {
2662 long accountId = getAccountIdLocked(db, account);
2663 if (accountId >= 0) {
2664 ContentValues values = new ContentValues();
2665 values.put(GRANTS_ACCOUNTS_ID, accountId);
2666 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2667 values.put(GRANTS_GRANTEE_UID, uid);
2668 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2669 db.setTransactionSuccessful();
2670 }
2671 } finally {
2672 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002673 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002674 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2675 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002676 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002677 }
2678
2679 /**
2680 * Don't allow callers with the given uid permission to get credentials for
2681 * account/authTokenType.
2682 * <p>
2683 * Although this is public it can only be accessed via the AccountManagerService object
2684 * which is in the system. This means we don't need to protect it with permissions.
2685 * @hide
2686 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002687 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002688 if (account == null || authTokenType == null) {
2689 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002690 return;
2691 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002692 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002693 synchronized (accounts.cacheLock) {
2694 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002695 db.beginTransaction();
2696 try {
2697 long accountId = getAccountIdLocked(db, account);
2698 if (accountId >= 0) {
2699 db.delete(TABLE_GRANTS,
2700 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2701 + GRANTS_GRANTEE_UID + "=?",
2702 new String[]{String.valueOf(accountId), authTokenType,
2703 String.valueOf(uid)});
2704 db.setTransactionSuccessful();
2705 }
2706 } finally {
2707 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002708 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002709 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2710 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002711 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002712 }
Fred Quintana56285a62010-12-02 14:20:51 -08002713
2714 static final private String stringArrayToString(String[] value) {
2715 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2716 }
2717
Amith Yamasani04e0d262012-02-14 11:50:53 -08002718 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2719 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002720 if (oldAccountsForType != null) {
2721 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2722 for (Account curAccount : oldAccountsForType) {
2723 if (!curAccount.equals(account)) {
2724 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002725 }
2726 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002727 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002728 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002729 } else {
2730 Account[] newAccountsForType = new Account[newAccountsList.size()];
2731 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002732 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002733 }
Fred Quintana56285a62010-12-02 14:20:51 -08002734 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002735 accounts.userDataCache.remove(account);
2736 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002737 }
2738
2739 /**
2740 * This assumes that the caller has already checked that the account is not already present.
2741 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002742 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2743 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002744 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2745 Account[] newAccountsForType = new Account[oldLength + 1];
2746 if (accountsForType != null) {
2747 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002748 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002749 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002750 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002751 }
2752
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002753 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07002754 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002755 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07002756 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002757 return unfiltered;
2758 }
2759 if (mUserManager.getUserInfo(userAccounts.userId).isRestricted()) {
2760 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002761 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002762 // otherwise return non-shared accounts only.
2763 // This might be a temporary way to specify a whitelist
2764 String whiteList = mContext.getResources().getString(
2765 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2766 for (String packageName : packages) {
2767 if (whiteList.contains(";" + packageName + ";")) {
2768 return unfiltered;
2769 }
2770 }
2771 ArrayList<Account> allowed = new ArrayList<Account>();
2772 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2773 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002774 String requiredAccountType = "";
2775 try {
2776 for (String packageName : packages) {
2777 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
2778 if (pi != null && pi.restrictedAccountType != null) {
2779 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07002780 // If it matches the package name of the original caller, use this choice.
2781 if (callingPackage != null && packageName.equals(callingPackage)) {
2782 break;
2783 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002784 }
2785 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002786 } catch (NameNotFoundException nnfe) {
2787 }
2788 for (Account account : unfiltered) {
2789 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002790 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002791 } else {
2792 boolean found = false;
2793 for (Account shared : sharedAccounts) {
2794 if (shared.equals(account)) {
2795 found = true;
2796 break;
2797 }
2798 }
2799 if (!found) {
2800 allowed.add(account);
2801 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002802 }
2803 }
2804 Account[] filtered = new Account[allowed.size()];
2805 allowed.toArray(filtered);
2806 return filtered;
2807 } else {
2808 return unfiltered;
2809 }
2810 }
2811
Amith Yamasani27db4682013-03-30 17:07:47 -07002812 /*
2813 * packageName can be null. If not null, it should be used to filter out restricted accounts
2814 * that the package is not allowed to access.
2815 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002816 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07002817 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002818 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002819 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002820 if (accounts == null) {
2821 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002822 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002823 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07002824 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002825 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002826 } else {
2827 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002828 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002829 totalLength += accounts.length;
2830 }
2831 if (totalLength == 0) {
2832 return EMPTY_ACCOUNT_ARRAY;
2833 }
2834 Account[] accounts = new Account[totalLength];
2835 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002836 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002837 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2838 accountsOfType.length);
2839 totalLength += accountsOfType.length;
2840 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002841 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002842 }
2843 }
2844
Amith Yamasani04e0d262012-02-14 11:50:53 -08002845 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2846 Account account, String key, String value) {
2847 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002848 if (userDataForAccount == null) {
2849 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002850 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002851 }
2852 if (value == null) {
2853 userDataForAccount.remove(key);
2854 } else {
2855 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002856 }
2857 }
2858
Amith Yamasani04e0d262012-02-14 11:50:53 -08002859 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2860 Account account, String key, String value) {
2861 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002862 if (authTokensForAccount == null) {
2863 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002864 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002865 }
2866 if (value == null) {
2867 authTokensForAccount.remove(key);
2868 } else {
2869 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002870 }
2871 }
2872
Amith Yamasani04e0d262012-02-14 11:50:53 -08002873 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2874 String authTokenType) {
2875 synchronized (accounts.cacheLock) {
2876 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002877 if (authTokensForAccount == null) {
2878 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002879 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002880 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002881 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002882 }
2883 return authTokensForAccount.get(authTokenType);
2884 }
2885 }
2886
Amith Yamasani04e0d262012-02-14 11:50:53 -08002887 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2888 synchronized (accounts.cacheLock) {
2889 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002890 if (userDataForAccount == null) {
2891 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002892 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002893 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002894 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002895 }
2896 return userDataForAccount.get(key);
2897 }
2898 }
2899
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002900 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2901 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002902 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002903 Cursor cursor = db.query(TABLE_EXTRAS,
2904 COLUMNS_EXTRAS_KEY_AND_VALUE,
2905 SELECTION_USERDATA_BY_ACCOUNT,
2906 new String[]{account.name, account.type},
2907 null, null, null);
2908 try {
2909 while (cursor.moveToNext()) {
2910 final String tmpkey = cursor.getString(0);
2911 final String value = cursor.getString(1);
2912 userDataForAccount.put(tmpkey, value);
2913 }
2914 } finally {
2915 cursor.close();
2916 }
2917 return userDataForAccount;
2918 }
2919
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002920 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2921 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002922 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002923 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2924 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2925 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2926 new String[]{account.name, account.type},
2927 null, null, null);
2928 try {
2929 while (cursor.moveToNext()) {
2930 final String type = cursor.getString(0);
2931 final String authToken = cursor.getString(1);
2932 authTokensForAccount.put(type, authToken);
2933 }
2934 } finally {
2935 cursor.close();
2936 }
2937 return authTokensForAccount;
2938 }
Fred Quintana60307342009-03-24 22:48:12 -07002939}