blob: e152ebeb275a0bba216583cfed9e4386e8b4c860 [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;
Amith Yamasani23c8b962013-04-10 13:37:18 -070025import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080026import android.accounts.GrantCredentialsPermissionActivity;
27import android.accounts.IAccountAuthenticator;
28import android.accounts.IAccountAuthenticatorResponse;
29import android.accounts.IAccountManager;
30import android.accounts.IAccountManagerResponse;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080031import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070032import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070033import android.app.AppGlobals;
Doug Zongker885cfc232009-10-21 16:52:44 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010037import android.app.admin.DevicePolicyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070038import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070039import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070040import android.content.ContentValues;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070044import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070045import android.content.pm.ApplicationInfo;
46import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070047import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070048import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070049import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070050import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070051import android.content.pm.ResolveInfo;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070052import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070053import android.database.Cursor;
54import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070055import android.database.sqlite.SQLiteDatabase;
56import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070057import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070058import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080059import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070060import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070061import android.os.IBinder;
62import android.os.Looper;
63import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070064import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070065import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import android.os.RemoteException;
67import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070069import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.text.TextUtils;
71import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070072import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070073import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080074import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070075
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070076import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080077import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080078import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070079import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070080import com.google.android.collect.Lists;
81import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070082
Oscar Montemayora8529f62009-11-18 10:14:20 -080083import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070084import java.io.FileDescriptor;
85import java.io.PrintWriter;
86import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080087import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070088import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070089import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070090import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080091import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070092import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080093import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070094import java.util.concurrent.atomic.AtomicInteger;
95import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070096
Fred Quintana60307342009-03-24 22:48:12 -070097/**
98 * A system service that provides account, password, and authtoken management for all
99 * accounts on the device. Some of these calls are implemented with the help of the corresponding
100 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
101 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700102 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700103 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700104 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700105public class AccountManagerService
106 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800107 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700108 private static final String TAG = "AccountManagerService";
109
110 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
111 private static final String DATABASE_NAME = "accounts.db";
Amith Yamasani67df64b2012-12-14 12:09:36 -0800112 private static final int DATABASE_VERSION = 5;
Fred Quintana60307342009-03-24 22:48:12 -0700113
114 private final Context mContext;
115
Fred Quintana56285a62010-12-02 14:20:51 -0800116 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700117 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800118
Fred Quintana60307342009-03-24 22:48:12 -0700119 private final MessageHandler mMessageHandler;
120
121 // Messages that can be sent on mHandler
122 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700123 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700124
Fred Quintana56285a62010-12-02 14:20:51 -0800125 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700126
127 private static final String TABLE_ACCOUNTS = "accounts";
128 private static final String ACCOUNTS_ID = "_id";
129 private static final String ACCOUNTS_NAME = "name";
130 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700131 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700132 private static final String ACCOUNTS_PASSWORD = "password";
133
134 private static final String TABLE_AUTHTOKENS = "authtokens";
135 private static final String AUTHTOKENS_ID = "_id";
136 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
137 private static final String AUTHTOKENS_TYPE = "type";
138 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
139
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700140 private static final String TABLE_GRANTS = "grants";
141 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
142 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
143 private static final String GRANTS_GRANTEE_UID = "uid";
144
Fred Quintana60307342009-03-24 22:48:12 -0700145 private static final String TABLE_EXTRAS = "extras";
146 private static final String EXTRAS_ID = "_id";
147 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
148 private static final String EXTRAS_KEY = "key";
149 private static final String EXTRAS_VALUE = "value";
150
151 private static final String TABLE_META = "meta";
152 private static final String META_KEY = "key";
153 private static final String META_VALUE = "value";
154
Amith Yamasani67df64b2012-12-14 12:09:36 -0800155 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
156
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700157 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
158 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700159 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700160
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700161 private static final String COUNT_OF_MATCHING_GRANTS = ""
162 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
163 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
164 + " AND " + GRANTS_GRANTEE_UID + "=?"
165 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
166 + " AND " + ACCOUNTS_NAME + "=?"
167 + " AND " + ACCOUNTS_TYPE + "=?";
168
Fred Quintana56285a62010-12-02 14:20:51 -0800169 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
170 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
171 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
172 AUTHTOKENS_AUTHTOKEN};
173
174 private static final String SELECTION_USERDATA_BY_ACCOUNT =
175 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
176 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
177
Fred Quintanaa698f422009-04-08 19:14:54 -0700178 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700179 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
180
Amith Yamasani04e0d262012-02-14 11:50:53 -0800181 static class UserAccounts {
182 private final int userId;
183 private final DatabaseHelper openHelper;
184 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
185 credentialsPermissionNotificationIds =
186 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
187 private final HashMap<Account, Integer> signinRequiredNotificationIds =
188 new HashMap<Account, Integer>();
189 private final Object cacheLock = new Object();
190 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700191 private final HashMap<String, Account[]> accountCache =
192 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800193 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800194 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800195 new HashMap<Account, HashMap<String, String>>();
196 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800197 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800198 new HashMap<Account, HashMap<String, String>>();
199
200 UserAccounts(Context context, int userId) {
201 this.userId = userId;
202 synchronized (cacheLock) {
203 openHelper = new DatabaseHelper(context, userId);
204 }
205 }
206 }
207
208 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
209
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700210 private static AtomicReference<AccountManagerService> sThis =
211 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700212 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700213
214 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700215 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700216 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
217 }
218
Fred Quintana56285a62010-12-02 14:20:51 -0800219
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700220 /**
221 * This should only be called by system code. One should only call this after the service
222 * has started.
223 * @return a reference to the AccountManagerService instance
224 * @hide
225 */
226 public static AccountManagerService getSingleton() {
227 return sThis.get();
228 }
Fred Quintana60307342009-03-24 22:48:12 -0700229
Fred Quintana56285a62010-12-02 14:20:51 -0800230 public AccountManagerService(Context context) {
231 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700232 }
233
Fred Quintana56285a62010-12-02 14:20:51 -0800234 public AccountManagerService(Context context, PackageManager packageManager,
235 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700236 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800237 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700238
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700239 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700240
Fred Quintana56285a62010-12-02 14:20:51 -0800241 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800242 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700243
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700244 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800245
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800246 IntentFilter intentFilter = new IntentFilter();
247 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
248 intentFilter.addDataScheme("package");
249 mContext.registerReceiver(new BroadcastReceiver() {
250 @Override
251 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800252 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800253 }
254 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800255
Amith Yamasani13593602012-03-22 16:16:17 -0700256 IntentFilter userFilter = new IntentFilter();
257 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800258 userFilter.addAction(Intent.ACTION_USER_STARTED);
259 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700260 @Override
261 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800262 String action = intent.getAction();
263 if (Intent.ACTION_USER_REMOVED.equals(action)) {
264 onUserRemoved(intent);
265 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
266 onUserStarted(intent);
267 }
Amith Yamasani13593602012-03-22 16:16:17 -0700268 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800269 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800270 }
271
Dianne Hackborn164371f2013-10-01 19:10:13 -0700272 @Override
273 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
274 throws RemoteException {
275 try {
276 return super.onTransact(code, data, reply, flags);
277 } catch (RuntimeException e) {
278 // The account manager only throws security exceptions, so let's
279 // log all others.
280 if (!(e instanceof SecurityException)) {
281 Slog.wtf(TAG, "Account Manager Crash", e);
282 }
283 throw e;
284 }
285 }
286
Kenny Root26ff6622012-07-30 12:58:03 -0700287 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700288 }
289
Amith Yamasani258848d2012-08-10 17:06:33 -0700290 private UserManager getUserManager() {
291 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700292 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700293 }
294 return mUserManager;
295 }
296
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700297 /* Caller should lock mUsers */
298 private UserAccounts initUserLocked(int userId) {
299 UserAccounts accounts = mUsers.get(userId);
300 if (accounts == null) {
301 accounts = new UserAccounts(mContext, userId);
302 mUsers.append(userId, accounts);
303 purgeOldGrants(accounts);
304 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800305 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700306 return accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800307 }
308
309 private void purgeOldGrantsAll() {
310 synchronized (mUsers) {
311 for (int i = 0; i < mUsers.size(); i++) {
312 purgeOldGrants(mUsers.valueAt(i));
313 }
314 }
315 }
316
317 private void purgeOldGrants(UserAccounts accounts) {
318 synchronized (accounts.cacheLock) {
319 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800320 final Cursor cursor = db.query(TABLE_GRANTS,
321 new String[]{GRANTS_GRANTEE_UID},
322 null, null, GRANTS_GRANTEE_UID, null, null);
323 try {
324 while (cursor.moveToNext()) {
325 final int uid = cursor.getInt(0);
326 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
327 if (packageExists) {
328 continue;
329 }
330 Log.d(TAG, "deleting grants for UID " + uid
331 + " because its package is no longer installed");
332 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
333 new String[]{Integer.toString(uid)});
334 }
335 } finally {
336 cursor.close();
337 }
338 }
339 }
340
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700341 /**
342 * Validate internal set of accounts against installed authenticators for
343 * given user. Clears cached authenticators before validating.
344 */
345 public void validateAccounts(int userId) {
346 final UserAccounts accounts = getUserAccounts(userId);
347
348 // Invalidate user-specific cache to make sure we catch any
349 // removed authenticators.
350 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
351 }
352
353 /**
354 * Validate internal set of accounts against installed authenticators for
355 * given user. Clear cached authenticators before validating when requested.
356 */
357 private void validateAccountsInternal(
358 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
359 if (invalidateAuthenticatorCache) {
360 mAuthenticatorCache.invalidateCache(accounts.userId);
361 }
362
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700363 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
364 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
365 mAuthenticatorCache.getAllServices(accounts.userId)) {
366 knownAuth.add(service.type);
367 }
368
Amith Yamasani04e0d262012-02-14 11:50:53 -0800369 synchronized (accounts.cacheLock) {
370 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800371 boolean accountDeleted = false;
372 Cursor cursor = db.query(TABLE_ACCOUNTS,
373 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
374 null, null, null, null, null);
375 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800376 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800377 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700378 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800379 while (cursor.moveToNext()) {
380 final long accountId = cursor.getLong(0);
381 final String accountType = cursor.getString(1);
382 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700383
384 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700385 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800386 + accountType + " no longer has a registered authenticator");
387 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
388 accountDeleted = true;
389 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800390 accounts.userDataCache.remove(account);
391 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800392 } else {
393 ArrayList<String> accountNames = accountNamesByType.get(accountType);
394 if (accountNames == null) {
395 accountNames = new ArrayList<String>();
396 accountNamesByType.put(accountType, accountNames);
397 }
398 accountNames.add(accountName);
399 }
400 }
Andy McFadden2f362292012-01-20 14:43:38 -0800401 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800402 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800403 final String accountType = cur.getKey();
404 final ArrayList<String> accountNames = cur.getValue();
405 final Account[] accountsForType = new Account[accountNames.size()];
406 int i = 0;
407 for (String accountName : accountNames) {
408 accountsForType[i] = new Account(accountName, accountType);
409 ++i;
410 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800411 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800412 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800413 } finally {
414 cursor.close();
415 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800416 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800417 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800418 }
419 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700420 }
421
Amith Yamasani04e0d262012-02-14 11:50:53 -0800422 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700423 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800424 }
425
426 protected UserAccounts getUserAccounts(int userId) {
427 synchronized (mUsers) {
428 UserAccounts accounts = mUsers.get(userId);
429 if (accounts == null) {
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700430 accounts = initUserLocked(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800431 mUsers.append(userId, accounts);
432 }
433 return accounts;
434 }
435 }
436
Amith Yamasani13593602012-03-22 16:16:17 -0700437 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700438 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700439 if (userId < 1) return;
440
441 UserAccounts accounts;
442 synchronized (mUsers) {
443 accounts = mUsers.get(userId);
444 mUsers.remove(userId);
445 }
446 if (accounts == null) {
447 File dbFile = new File(getDatabaseName(userId));
448 dbFile.delete();
449 return;
450 }
451
452 synchronized (accounts.cacheLock) {
453 accounts.openHelper.close();
454 File dbFile = new File(getDatabaseName(userId));
455 dbFile.delete();
456 }
457 }
458
Amith Yamasani67df64b2012-12-14 12:09:36 -0800459 private void onUserStarted(Intent intent) {
460 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
461 if (userId < 1) return;
462
463 // Check if there's a shared account that needs to be created as an account
464 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
465 if (sharedAccounts == null || sharedAccounts.length == 0) return;
466 Account[] accounts = getAccountsAsUser(null, userId);
467 for (Account sa : sharedAccounts) {
468 if (ArrayUtils.contains(accounts, sa)) continue;
469 // Account doesn't exist. Copy it now.
470 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
471 }
472 }
473
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700474 @Override
475 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700476 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700477 }
478
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800479 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700480 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800481 if (Log.isLoggable(TAG, Log.VERBOSE)) {
482 Log.v(TAG, "getPassword: " + account
483 + ", caller's uid " + Binder.getCallingUid()
484 + ", pid " + Binder.getCallingPid());
485 }
Fred Quintana382601f2010-03-25 12:25:10 -0700486 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700487 checkAuthenticateAccountsPermission(account);
488
Amith Yamasani04e0d262012-02-14 11:50:53 -0800489 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700490 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700491 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800492 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700493 } finally {
494 restoreCallingIdentity(identityToken);
495 }
496 }
497
Amith Yamasani04e0d262012-02-14 11:50:53 -0800498 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700499 if (account == null) {
500 return null;
501 }
502
Amith Yamasani04e0d262012-02-14 11:50:53 -0800503 synchronized (accounts.cacheLock) {
504 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800505 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
506 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
507 new String[]{account.name, account.type}, null, null, null);
508 try {
509 if (cursor.moveToNext()) {
510 return cursor.getString(0);
511 }
512 return null;
513 } finally {
514 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700516 }
517 }
518
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800519 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700520 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800521 if (Log.isLoggable(TAG, Log.VERBOSE)) {
522 Log.v(TAG, "getUserData: " + account
523 + ", key " + key
524 + ", caller's uid " + Binder.getCallingUid()
525 + ", pid " + Binder.getCallingPid());
526 }
Fred Quintana382601f2010-03-25 12:25:10 -0700527 if (account == null) throw new IllegalArgumentException("account is null");
528 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700529 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800530 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700531 long identityToken = clearCallingIdentity();
532 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800533 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700534 } finally {
535 restoreCallingIdentity(identityToken);
536 }
537 }
538
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800539 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100540 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800541 if (Log.isLoggable(TAG, Log.VERBOSE)) {
542 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100543 + "for user id " + userId
Fred Quintana56285a62010-12-02 14:20:51 -0800544 + "caller's uid " + Binder.getCallingUid()
545 + ", pid " + Binder.getCallingPid());
546 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100547 // Only allow the system process to read accounts of other users
548 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
549 + " trying get authenticator types for " + userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700550 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700551 try {
Fred Quintana97889762009-06-15 12:29:24 -0700552 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700553 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700554 AuthenticatorDescription[] types =
555 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700556 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700557 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700558 : authenticatorCollection) {
559 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700560 i++;
561 }
562 return types;
563 } finally {
564 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700565 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700566 }
567
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100568 private void enforceCrossUserPermission(int userId, String errorMessage) {
569 if (userId != UserHandle.getCallingUserId()
570 && Binder.getCallingUid() != Process.myUid()
571 && mContext.checkCallingOrSelfPermission(
572 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
573 != PackageManager.PERMISSION_GRANTED) {
574 throw new SecurityException(errorMessage);
575 }
576 }
577
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700578 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700579 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800580 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700581 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800582 + ", caller's uid " + Binder.getCallingUid()
583 + ", pid " + Binder.getCallingPid());
584 }
Fred Quintana382601f2010-03-25 12:25:10 -0700585 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700586 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700587 /*
588 * Child users are not allowed to add accounts. Only the accounts that are
589 * shared by the parent profile can be added to child profile.
590 *
591 * TODO: Only allow accounts that were shared to be added by
592 * a limited user.
593 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700594
Amith Yamasani04e0d262012-02-14 11:50:53 -0800595 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700596 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700597 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700598 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800599 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700600 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700601 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700602 }
603 }
604
Amith Yamasani67df64b2012-12-14 12:09:36 -0800605 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
606 final UserAccounts fromAccounts = getUserAccounts(userFrom);
607 final UserAccounts toAccounts = getUserAccounts(userTo);
608 if (fromAccounts == null || toAccounts == null) {
609 return false;
610 }
611
612 long identityToken = clearCallingIdentity();
613 try {
614 new Session(fromAccounts, null, account.type, false,
615 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700616 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800617 protected String toDebugString(long now) {
618 return super.toDebugString(now) + ", getAccountCredentialsForClone"
619 + ", " + account.type;
620 }
621
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700622 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800623 public void run() throws RemoteException {
624 mAuthenticator.getAccountCredentialsForCloning(this, account);
625 }
626
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700627 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800628 public void onResult(Bundle result) {
629 if (result != null) {
630 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
631 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800632 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800633 }
634 return;
635 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800636 super.onResult(result);
637 }
638 }
639 }.bind();
640 } finally {
641 restoreCallingIdentity(identityToken);
642 }
643 return true;
644 }
645
Amith Yamasani67df64b2012-12-14 12:09:36 -0800646 void completeCloningAccount(final Bundle result, final Account account,
647 final UserAccounts targetUser) {
648 long id = clearCallingIdentity();
649 try {
650 new Session(targetUser, null, account.type, false,
651 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700652 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800653 protected String toDebugString(long now) {
654 return super.toDebugString(now) + ", getAccountCredentialsForClone"
655 + ", " + account.type;
656 }
657
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700658 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800659 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700660 // Confirm that the owner's account still exists before this step.
661 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
662 synchronized (owner.cacheLock) {
663 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
664 for (Account acc : ownerAccounts) {
665 if (acc.equals(account)) {
666 mAuthenticator.addAccountFromCredentials(this, account, result);
667 break;
668 }
669 }
670 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800671 }
672
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700673 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800674 public void onResult(Bundle result) {
675 if (result != null) {
676 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
677 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800678 } else {
679 // TODO: Show error notification
680 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800681 }
682 return;
683 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800684 super.onResult(result);
685 }
686 }
687
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700688 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800689 public void onError(int errorCode, String errorMessage) {
690 super.onError(errorCode, errorMessage);
691 // TODO: Show error notification to user
692 // TODO: Should we remove the shadow account so that it doesn't keep trying?
693 }
694
695 }.bind();
696 } finally {
697 restoreCallingIdentity(id);
698 }
699 }
700
Amith Yamasani04e0d262012-02-14 11:50:53 -0800701 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800702 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700703 if (account == null) {
704 return false;
705 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800706 synchronized (accounts.cacheLock) {
707 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800708 db.beginTransaction();
709 try {
710 long numMatches = DatabaseUtils.longForQuery(db,
711 "select count(*) from " + TABLE_ACCOUNTS
712 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
713 new String[]{account.name, account.type});
714 if (numMatches > 0) {
715 Log.w(TAG, "insertAccountIntoDatabase: " + account
716 + ", skipping since the account already exists");
717 return false;
718 }
719 ContentValues values = new ContentValues();
720 values.put(ACCOUNTS_NAME, account.name);
721 values.put(ACCOUNTS_TYPE, account.type);
722 values.put(ACCOUNTS_PASSWORD, password);
723 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
724 if (accountId < 0) {
725 Log.w(TAG, "insertAccountIntoDatabase: " + account
726 + ", skipping the DB insert failed");
727 return false;
728 }
729 if (extras != null) {
730 for (String key : extras.keySet()) {
731 final String value = extras.getString(key);
732 if (insertExtraLocked(db, accountId, key, value) < 0) {
733 Log.w(TAG, "insertAccountIntoDatabase: " + account
734 + ", skipping since insertExtra failed for key " + key);
735 return false;
736 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700737 }
738 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800739 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800740 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800741 } finally {
742 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700743 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800744 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700745 }
746 if (accounts.userId == UserHandle.USER_OWNER) {
747 addAccountToLimitedUsers(account);
748 }
749 return true;
750 }
751
752 /**
753 * Adds the account to all limited users as shared accounts. If the user is currently
754 * running, then clone the account too.
755 * @param account the account to share with limited users
756 */
757 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700758 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700759 for (UserInfo user : users) {
760 if (user.isRestricted()) {
761 addSharedAccountAsUser(account, user.id);
762 try {
763 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
764 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
765 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
766 account));
767 }
768 } catch (RemoteException re) {
769 // Shouldn't happen
770 }
771 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700772 }
773 }
774
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800775 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700776 ContentValues values = new ContentValues();
777 values.put(EXTRAS_KEY, key);
778 values.put(EXTRAS_ACCOUNTS_ID, accountId);
779 values.put(EXTRAS_VALUE, value);
780 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
781 }
782
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800783 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -0800784 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800785 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800786 if (Log.isLoggable(TAG, Log.VERBOSE)) {
787 Log.v(TAG, "hasFeatures: " + account
788 + ", response " + response
789 + ", features " + stringArrayToString(features)
790 + ", caller's uid " + Binder.getCallingUid()
791 + ", pid " + Binder.getCallingPid());
792 }
Fred Quintana382601f2010-03-25 12:25:10 -0700793 if (response == null) throw new IllegalArgumentException("response is null");
794 if (account == null) throw new IllegalArgumentException("account is null");
795 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800796 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800797 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800798 long identityToken = clearCallingIdentity();
799 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800800 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800801 } finally {
802 restoreCallingIdentity(identityToken);
803 }
804 }
805
806 private class TestFeaturesSession extends Session {
807 private final String[] mFeatures;
808 private final Account mAccount;
809
Amith Yamasani04e0d262012-02-14 11:50:53 -0800810 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800811 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800812 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800813 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800814 mFeatures = features;
815 mAccount = account;
816 }
817
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700818 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800819 public void run() throws RemoteException {
820 try {
821 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
822 } catch (RemoteException e) {
823 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
824 }
825 }
826
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700827 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800828 public void onResult(Bundle result) {
829 IAccountManagerResponse response = getResponseAndClose();
830 if (response != null) {
831 try {
832 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700833 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800834 return;
835 }
Fred Quintana56285a62010-12-02 14:20:51 -0800836 if (Log.isLoggable(TAG, Log.VERBOSE)) {
837 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
838 + response);
839 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800840 final Bundle newResult = new Bundle();
841 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
842 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
843 response.onResult(newResult);
844 } catch (RemoteException e) {
845 // if the caller is dead then there is no one to care about remote exceptions
846 if (Log.isLoggable(TAG, Log.VERBOSE)) {
847 Log.v(TAG, "failure while notifying response", e);
848 }
849 }
850 }
851 }
852
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700853 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800854 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800855 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800856 + ", " + mAccount
857 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
858 }
859 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800860
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800861 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700862 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800863 if (Log.isLoggable(TAG, Log.VERBOSE)) {
864 Log.v(TAG, "removeAccount: " + account
865 + ", response " + response
866 + ", caller's uid " + Binder.getCallingUid()
867 + ", pid " + Binder.getCallingPid());
868 }
Fred Quintana382601f2010-03-25 12:25:10 -0700869 if (response == null) throw new IllegalArgumentException("response is null");
870 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700871 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700872 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800873 UserAccounts accounts = getUserAccountsForCaller();
Sander Alewijnseda1350f2014-05-08 16:59:42 +0100874 if (!canUserModifyAccounts(Binder.getCallingUid(), account.type)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800875 try {
876 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
877 "User cannot modify accounts");
878 } catch (RemoteException re) {
879 }
Amith Yamasani5934dbc2014-02-20 15:23:36 -0800880 return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800881 }
882
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700883 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800884
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700885 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800886 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800887 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800888 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800889 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800890 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700891 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800892 }
893 }
894 }
895
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700896 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800897 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700898 } finally {
899 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700900 }
Fred Quintana60307342009-03-24 22:48:12 -0700901 }
902
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700903 private class RemoveAccountSession extends Session {
904 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800905 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
906 Account account) {
907 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800908 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700909 mAccount = account;
910 }
911
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700912 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700913 protected String toDebugString(long now) {
914 return super.toDebugString(now) + ", removeAccount"
915 + ", account " + mAccount;
916 }
917
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700918 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700919 public void run() throws RemoteException {
920 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
921 }
922
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700923 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700924 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700925 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
926 && !result.containsKey(AccountManager.KEY_INTENT)) {
927 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700928 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800929 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700930 }
931 IAccountManagerResponse response = getResponseAndClose();
932 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800933 if (Log.isLoggable(TAG, Log.VERBOSE)) {
934 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
935 + response);
936 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700937 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700938 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700939 try {
940 response.onResult(result2);
941 } catch (RemoteException e) {
942 // ignore
943 }
944 }
945 }
946 super.onResult(result);
947 }
948 }
949
Amith Yamasani04e0d262012-02-14 11:50:53 -0800950 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800951 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800952 removeAccountInternal(getUserAccountsForCaller(), account);
953 }
954
955 private void removeAccountInternal(UserAccounts accounts, Account account) {
956 synchronized (accounts.cacheLock) {
957 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800958 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
959 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800960 removeAccountFromCacheLocked(accounts, account);
961 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800962 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800963 if (accounts.userId == UserHandle.USER_OWNER) {
964 // Owner's account was removed, remove from any users that are sharing
965 // this account.
966 long id = Binder.clearCallingIdentity();
967 try {
968 List<UserInfo> users = mUserManager.getUsers(true);
969 for (UserInfo user : users) {
970 if (!user.isPrimary() && user.isRestricted()) {
971 removeSharedAccountAsUser(account, user.id);
972 }
973 }
974 } finally {
975 Binder.restoreCallingIdentity(id);
976 }
977 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700978 }
979
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400980 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700981 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800982 if (Log.isLoggable(TAG, Log.VERBOSE)) {
983 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
984 + ", caller's uid " + Binder.getCallingUid()
985 + ", pid " + Binder.getCallingPid());
986 }
Fred Quintana382601f2010-03-25 12:25:10 -0700987 if (accountType == null) throw new IllegalArgumentException("accountType is null");
988 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800989 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800990 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700991 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700992 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800993 synchronized (accounts.cacheLock) {
994 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800995 db.beginTransaction();
996 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800997 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800998 db.setTransactionSuccessful();
999 } finally {
1000 db.endTransaction();
1001 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001002 }
Fred Quintana60307342009-03-24 22:48:12 -07001003 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001004 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001005 }
1006 }
1007
Amith Yamasani04e0d262012-02-14 11:50:53 -08001008 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1009 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001010 if (authToken == null || accountType == null) {
1011 return;
1012 }
Fred Quintana33269202009-04-20 16:05:10 -07001013 Cursor cursor = db.rawQuery(
1014 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1015 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1016 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1017 + " FROM " + TABLE_ACCOUNTS
1018 + " JOIN " + TABLE_AUTHTOKENS
1019 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1020 + " = " + AUTHTOKENS_ACCOUNTS_ID
1021 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1022 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1023 new String[]{authToken, accountType});
1024 try {
1025 while (cursor.moveToNext()) {
1026 long authTokenId = cursor.getLong(0);
1027 String accountName = cursor.getString(1);
1028 String authTokenType = cursor.getString(2);
1029 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001030 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001031 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -07001032 }
Fred Quintana33269202009-04-20 16:05:10 -07001033 } finally {
1034 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001035 }
1036 }
1037
Amith Yamasani04e0d262012-02-14 11:50:53 -08001038 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1039 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001040 if (account == null || type == null) {
1041 return false;
1042 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001043 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1044 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001045 synchronized (accounts.cacheLock) {
1046 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001047 db.beginTransaction();
1048 try {
1049 long accountId = getAccountIdLocked(db, account);
1050 if (accountId < 0) {
1051 return false;
1052 }
1053 db.delete(TABLE_AUTHTOKENS,
1054 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1055 new String[]{type});
1056 ContentValues values = new ContentValues();
1057 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1058 values.put(AUTHTOKENS_TYPE, type);
1059 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1060 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1061 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001062 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001063 return true;
1064 }
Fred Quintana33269202009-04-20 16:05:10 -07001065 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001066 } finally {
1067 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001068 }
Fred Quintana60307342009-03-24 22:48:12 -07001069 }
1070 }
1071
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001072 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001073 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001074 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1075 Log.v(TAG, "peekAuthToken: " + account
1076 + ", authTokenType " + authTokenType
1077 + ", caller's uid " + Binder.getCallingUid()
1078 + ", pid " + Binder.getCallingPid());
1079 }
Fred Quintana382601f2010-03-25 12:25:10 -07001080 if (account == null) throw new IllegalArgumentException("account is null");
1081 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001082 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001083 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001084 long identityToken = clearCallingIdentity();
1085 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001086 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001087 } finally {
1088 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001089 }
Fred Quintana60307342009-03-24 22:48:12 -07001090 }
1091
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001092 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001093 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001094 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1095 Log.v(TAG, "setAuthToken: " + account
1096 + ", authTokenType " + authTokenType
1097 + ", caller's uid " + Binder.getCallingUid()
1098 + ", pid " + Binder.getCallingPid());
1099 }
Fred Quintana382601f2010-03-25 12:25:10 -07001100 if (account == null) throw new IllegalArgumentException("account is null");
1101 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001102 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001103 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001104 long identityToken = clearCallingIdentity();
1105 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001106 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001107 } finally {
1108 restoreCallingIdentity(identityToken);
1109 }
Fred Quintana60307342009-03-24 22:48:12 -07001110 }
1111
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001112 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001113 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001114 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1115 Log.v(TAG, "setAuthToken: " + account
1116 + ", caller's uid " + Binder.getCallingUid()
1117 + ", pid " + Binder.getCallingPid());
1118 }
Fred Quintana382601f2010-03-25 12:25:10 -07001119 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001120 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001121 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001122 long identityToken = clearCallingIdentity();
1123 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001124 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001125 } finally {
1126 restoreCallingIdentity(identityToken);
1127 }
Fred Quintana60307342009-03-24 22:48:12 -07001128 }
1129
Amith Yamasani04e0d262012-02-14 11:50:53 -08001130 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001131 if (account == null) {
1132 return;
1133 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001134 synchronized (accounts.cacheLock) {
1135 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001136 db.beginTransaction();
1137 try {
1138 final ContentValues values = new ContentValues();
1139 values.put(ACCOUNTS_PASSWORD, password);
1140 final long accountId = getAccountIdLocked(db, account);
1141 if (accountId >= 0) {
1142 final String[] argsAccountId = {String.valueOf(accountId)};
1143 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1144 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001145 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001146 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001147 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001148 } finally {
1149 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001150 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001151 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001152 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001153 }
1154
Amith Yamasani04e0d262012-02-14 11:50:53 -08001155 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001156 Log.i(TAG, "the accounts changed, sending broadcast of "
1157 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001158 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001159 }
1160
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001161 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001162 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001163 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1164 Log.v(TAG, "clearPassword: " + account
1165 + ", caller's uid " + Binder.getCallingUid()
1166 + ", pid " + Binder.getCallingPid());
1167 }
Fred Quintana382601f2010-03-25 12:25:10 -07001168 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001169 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001170 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001171 long identityToken = clearCallingIdentity();
1172 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001173 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001174 } finally {
1175 restoreCallingIdentity(identityToken);
1176 }
Fred Quintana60307342009-03-24 22:48:12 -07001177 }
1178
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001179 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001180 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001181 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1182 Log.v(TAG, "setUserData: " + account
1183 + ", key " + key
1184 + ", caller's uid " + Binder.getCallingUid()
1185 + ", pid " + Binder.getCallingPid());
1186 }
Fred Quintana382601f2010-03-25 12:25:10 -07001187 if (key == null) throw new IllegalArgumentException("key is null");
1188 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001189 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001190 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001191 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001192 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001193 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001194 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001195 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001196 }
1197 }
1198
Amith Yamasani04e0d262012-02-14 11:50:53 -08001199 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1200 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001201 if (account == null || key == null) {
1202 return;
1203 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001204 synchronized (accounts.cacheLock) {
1205 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001206 db.beginTransaction();
1207 try {
1208 long accountId = getAccountIdLocked(db, account);
1209 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001210 return;
1211 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001212 long extrasId = getExtrasIdLocked(db, accountId, key);
1213 if (extrasId < 0 ) {
1214 extrasId = insertExtraLocked(db, accountId, key, value);
1215 if (extrasId < 0) {
1216 return;
1217 }
1218 } else {
1219 ContentValues values = new ContentValues();
1220 values.put(EXTRAS_VALUE, value);
1221 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1222 return;
1223 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001224
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001225 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001226 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001227 db.setTransactionSuccessful();
1228 } finally {
1229 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001230 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001231 }
1232 }
1233
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001234 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001235 if (result == null) {
1236 Log.e(TAG, "the result is unexpectedly null", new Exception());
1237 }
1238 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1239 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1240 + response);
1241 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001242 try {
1243 response.onResult(result);
1244 } catch (RemoteException e) {
1245 // if the caller is dead then there is no one to care about remote
1246 // exceptions
1247 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1248 Log.v(TAG, "failure while notifying response", e);
1249 }
1250 }
1251 }
1252
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001253 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001254 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1255 final String authTokenType)
1256 throws RemoteException {
1257 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001258 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1259
Fred Quintanad9640ec2012-05-23 12:37:00 -07001260 final int callingUid = getCallingUid();
1261 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001262 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001263 throw new SecurityException("can only call from system");
1264 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001265 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001266 long identityToken = clearCallingIdentity();
1267 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001268 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001269 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001270 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001271 protected String toDebugString(long now) {
1272 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001273 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001274 + ", authTokenType " + authTokenType;
1275 }
1276
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001277 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001278 public void run() throws RemoteException {
1279 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1280 }
1281
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001282 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001283 public void onResult(Bundle result) {
1284 if (result != null) {
1285 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1286 Bundle bundle = new Bundle();
1287 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1288 super.onResult(bundle);
1289 return;
1290 } else {
1291 super.onResult(result);
1292 }
1293 }
1294 }.bind();
1295 } finally {
1296 restoreCallingIdentity(identityToken);
1297 }
1298 }
1299
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001300 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001301 public void getAuthToken(IAccountManagerResponse response, final Account account,
1302 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001303 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001304 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1305 Log.v(TAG, "getAuthToken: " + account
1306 + ", response " + response
1307 + ", authTokenType " + authTokenType
1308 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1309 + ", expectActivityLaunch " + expectActivityLaunch
1310 + ", caller's uid " + Binder.getCallingUid()
1311 + ", pid " + Binder.getCallingPid());
1312 }
Fred Quintana382601f2010-03-25 12:25:10 -07001313 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001314 try {
1315 if (account == null) {
1316 Slog.w(TAG, "getAuthToken called with null account");
1317 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1318 return;
1319 }
1320 if (authTokenType == null) {
1321 Slog.w(TAG, "getAuthToken called with null authTokenType");
1322 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1323 return;
1324 }
1325 } catch (RemoteException e) {
1326 Slog.w(TAG, "Failed to report error back to the client." + e);
1327 return;
1328 }
1329
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001330 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001331 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001332 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1333 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1334 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001335 final boolean customTokens =
1336 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1337
1338 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001339 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001340 final boolean permissionGranted = customTokens ||
1341 permissionIsGranted(account, authTokenType, callerUid);
1342
Costin Manolachec6684f92011-01-14 11:25:39 -08001343 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1344 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001345 // let authenticator know the identity of the caller
1346 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1347 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1348 if (notifyOnAuthFailure) {
1349 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001350 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001351
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001352 long identityToken = clearCallingIdentity();
1353 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001354 // if the caller has permission, do the peek. otherwise go the more expensive
1355 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001356 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001357 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001358 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001359 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001360 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1361 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1362 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001363 onResult(response, result);
1364 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001365 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001366 }
1367
Amith Yamasani04e0d262012-02-14 11:50:53 -08001368 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001369 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001370 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001371 protected String toDebugString(long now) {
1372 if (loginOptions != null) loginOptions.keySet();
1373 return super.toDebugString(now) + ", getAuthToken"
1374 + ", " + account
1375 + ", authTokenType " + authTokenType
1376 + ", loginOptions " + loginOptions
1377 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1378 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001379
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001380 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001381 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001382 // If the caller doesn't have permission then create and return the
1383 // "grant permission" intent instead of the "getAuthToken" intent.
1384 if (!permissionGranted) {
1385 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1386 } else {
1387 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1388 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001389 }
1390
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001391 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001392 public void onResult(Bundle result) {
1393 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001394 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001395 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1396 new AccountAuthenticatorResponse(this),
1397 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001398 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001399 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001400 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001401 onResult(bundle);
1402 return;
1403 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001404 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001405 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001406 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1407 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001408 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001409 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001410 "the type and name should not be empty");
1411 return;
1412 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001413 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001414 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001415 authTokenType, authToken);
1416 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001417 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001418
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001419 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001420 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001421 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001422 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001423 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001424 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001425 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001426 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001427 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001428 }.bind();
1429 } finally {
1430 restoreCallingIdentity(identityToken);
1431 }
Fred Quintana60307342009-03-24 22:48:12 -07001432 }
1433
Dianne Hackborn41203752012-08-31 14:05:51 -07001434 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1435 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001436 int uid = intent.getIntExtra(
1437 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1438 String authTokenType = intent.getStringExtra(
1439 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1440 String authTokenLabel = intent.getStringExtra(
1441 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1442
1443 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1444 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001445 final String titleAndSubtitle =
1446 mContext.getString(R.string.permission_request_notification_with_subtitle,
1447 account.name);
1448 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001449 String title = titleAndSubtitle;
1450 String subtitle = "";
1451 if (index > 0) {
1452 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001453 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001454 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001455 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001456 n.setLatestEventInfo(mContext, title, subtitle,
1457 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001458 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1459 installNotification(getCredentialPermissionNotificationId(
1460 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001461 }
1462
Costin Manolache5f383ad92010-12-02 16:44:46 -08001463 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1464 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001465
1466 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001467 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001468 // Since it was set in Eclair+ we can't change it without breaking apps using
1469 // the intent from a non-Activity context.
1470 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001471 intent.addCategory(
1472 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001473
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001474 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001475 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1476 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001477 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001478
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001479 return intent;
1480 }
1481
1482 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1483 int uid) {
1484 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001485 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001486 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001487 final Pair<Pair<Account, String>, Integer> key =
1488 new Pair<Pair<Account, String>, Integer>(
1489 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001490 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001491 if (id == null) {
1492 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001493 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001494 }
1495 }
1496 return id;
1497 }
1498
Amith Yamasani04e0d262012-02-14 11:50:53 -08001499 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001500 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001501 synchronized (accounts.signinRequiredNotificationIds) {
1502 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001503 if (id == null) {
1504 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001505 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001506 }
1507 }
1508 return id;
1509 }
1510
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001511 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001512 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001513 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001514 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001515 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1516 Log.v(TAG, "addAccount: accountType " + accountType
1517 + ", response " + response
1518 + ", authTokenType " + authTokenType
1519 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1520 + ", expectActivityLaunch " + expectActivityLaunch
1521 + ", caller's uid " + Binder.getCallingUid()
1522 + ", pid " + Binder.getCallingPid());
1523 }
Fred Quintana382601f2010-03-25 12:25:10 -07001524 if (response == null) throw new IllegalArgumentException("response is null");
1525 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001526 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001527
Amith Yamasani71e6c692013-03-24 17:39:28 -07001528 // Is user disallowed from modifying accounts?
Sander Alewijnseda1350f2014-05-08 16:59:42 +01001529 if (!canUserModifyAccounts(Binder.getCallingUid(), accountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001530 try {
1531 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1532 "User is not allowed to add an account!");
1533 } catch (RemoteException re) {
1534 }
Amith Yamasani23c8b962013-04-10 13:37:18 -07001535 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1536 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1537 long identityToken = clearCallingIdentity();
1538 try {
1539 mContext.startActivityAsUser(cantAddAccount, UserHandle.CURRENT);
1540 } finally {
1541 restoreCallingIdentity(identityToken);
1542 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001543 return;
1544 }
1545
Amith Yamasani04e0d262012-02-14 11:50:53 -08001546 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001547 final int pid = Binder.getCallingPid();
1548 final int uid = Binder.getCallingUid();
1549 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1550 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1551 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1552
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001553 long identityToken = clearCallingIdentity();
1554 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001555 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001556 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001557 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001558 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001559 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001560 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001561 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001562
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001563 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001564 protected String toDebugString(long now) {
1565 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001566 + ", accountType " + accountType
1567 + ", requiredFeatures "
1568 + (requiredFeatures != null
1569 ? TextUtils.join(",", requiredFeatures)
1570 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001571 }
1572 }.bind();
1573 } finally {
1574 restoreCallingIdentity(identityToken);
1575 }
Fred Quintana60307342009-03-24 22:48:12 -07001576 }
1577
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001578 @Override
1579 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1580 final Account account, final Bundle options, final boolean expectActivityLaunch,
1581 int userId) {
1582 // Only allow the system process to read accounts of other users
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001583 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001584 + " trying to confirm account credentials for " + userId);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001585
Fred Quintana56285a62010-12-02 14:20:51 -08001586 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1587 Log.v(TAG, "confirmCredentials: " + account
1588 + ", response " + response
1589 + ", expectActivityLaunch " + expectActivityLaunch
1590 + ", caller's uid " + Binder.getCallingUid()
1591 + ", pid " + Binder.getCallingPid());
1592 }
Fred Quintana382601f2010-03-25 12:25:10 -07001593 if (response == null) throw new IllegalArgumentException("response is null");
1594 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001595 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001596 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001597 long identityToken = clearCallingIdentity();
1598 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001599 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001600 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001601 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001602 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001603 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001604 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001605 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001606 protected String toDebugString(long now) {
1607 return super.toDebugString(now) + ", confirmCredentials"
1608 + ", " + account;
1609 }
1610 }.bind();
1611 } finally {
1612 restoreCallingIdentity(identityToken);
1613 }
Fred Quintana60307342009-03-24 22:48:12 -07001614 }
1615
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001616 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001617 public void updateCredentials(IAccountManagerResponse response, final Account account,
1618 final String authTokenType, final boolean expectActivityLaunch,
1619 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001620 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1621 Log.v(TAG, "updateCredentials: " + account
1622 + ", response " + response
1623 + ", authTokenType " + authTokenType
1624 + ", expectActivityLaunch " + expectActivityLaunch
1625 + ", caller's uid " + Binder.getCallingUid()
1626 + ", pid " + Binder.getCallingPid());
1627 }
Fred Quintana382601f2010-03-25 12:25:10 -07001628 if (response == null) throw new IllegalArgumentException("response is null");
1629 if (account == null) throw new IllegalArgumentException("account is null");
1630 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001631 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001632 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001633 long identityToken = clearCallingIdentity();
1634 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001635 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001636 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001637 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001638 public void run() throws RemoteException {
1639 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1640 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001641 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001642 protected String toDebugString(long now) {
1643 if (loginOptions != null) loginOptions.keySet();
1644 return super.toDebugString(now) + ", updateCredentials"
1645 + ", " + account
1646 + ", authTokenType " + authTokenType
1647 + ", loginOptions " + loginOptions;
1648 }
1649 }.bind();
1650 } finally {
1651 restoreCallingIdentity(identityToken);
1652 }
Fred Quintana60307342009-03-24 22:48:12 -07001653 }
1654
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001655 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001656 public void editProperties(IAccountManagerResponse response, final String accountType,
1657 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001658 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1659 Log.v(TAG, "editProperties: accountType " + accountType
1660 + ", response " + response
1661 + ", expectActivityLaunch " + expectActivityLaunch
1662 + ", caller's uid " + Binder.getCallingUid()
1663 + ", pid " + Binder.getCallingPid());
1664 }
Fred Quintana382601f2010-03-25 12:25:10 -07001665 if (response == null) throw new IllegalArgumentException("response is null");
1666 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001667 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001668 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001669 long identityToken = clearCallingIdentity();
1670 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001671 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001672 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001673 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001674 public void run() throws RemoteException {
1675 mAuthenticator.editProperties(this, mAccountType);
1676 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001677 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001678 protected String toDebugString(long now) {
1679 return super.toDebugString(now) + ", editProperties"
1680 + ", accountType " + accountType;
1681 }
1682 }.bind();
1683 } finally {
1684 restoreCallingIdentity(identityToken);
1685 }
Fred Quintana60307342009-03-24 22:48:12 -07001686 }
1687
Fred Quintana33269202009-04-20 16:05:10 -07001688 private class GetAccountsByTypeAndFeatureSession extends Session {
1689 private final String[] mFeatures;
1690 private volatile Account[] mAccountsOfType = null;
1691 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1692 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001693 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001694
Amith Yamasani04e0d262012-02-14 11:50:53 -08001695 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001696 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001697 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001698 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001699 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001700 mFeatures = features;
1701 }
1702
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001703 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001704 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001705 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001706 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1707 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001708 }
Fred Quintana33269202009-04-20 16:05:10 -07001709 // check whether each account matches the requested features
1710 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1711 mCurrentAccount = 0;
1712
1713 checkAccount();
1714 }
1715
1716 public void checkAccount() {
1717 if (mCurrentAccount >= mAccountsOfType.length) {
1718 sendResult();
1719 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001720 }
Fred Quintana33269202009-04-20 16:05:10 -07001721
Fred Quintana29e94b82010-03-10 12:11:51 -08001722 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1723 if (accountAuthenticator == null) {
1724 // It is possible that the authenticator has died, which is indicated by
1725 // mAuthenticator being set to null. If this happens then just abort.
1726 // There is no need to send back a result or error in this case since
1727 // that already happened when mAuthenticator was cleared.
1728 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1729 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1730 + " connected to the authenticator, " + toDebugString());
1731 }
1732 return;
1733 }
Fred Quintana33269202009-04-20 16:05:10 -07001734 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001735 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001736 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001737 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001738 }
1739 }
1740
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001741 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001742 public void onResult(Bundle result) {
1743 mNumResults++;
1744 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001745 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001746 return;
1747 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001748 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001749 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1750 }
1751 mCurrentAccount++;
1752 checkAccount();
1753 }
1754
1755 public void sendResult() {
1756 IAccountManagerResponse response = getResponseAndClose();
1757 if (response != null) {
1758 try {
1759 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1760 for (int i = 0; i < accounts.length; i++) {
1761 accounts[i] = mAccountsWithFeatures.get(i);
1762 }
Fred Quintana56285a62010-12-02 14:20:51 -08001763 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1764 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1765 + response);
1766 }
Fred Quintana33269202009-04-20 16:05:10 -07001767 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001768 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001769 response.onResult(result);
1770 } catch (RemoteException e) {
1771 // if the caller is dead then there is no one to care about remote exceptions
1772 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1773 Log.v(TAG, "failure while notifying response", e);
1774 }
1775 }
1776 }
1777 }
1778
1779
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001780 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001781 protected String toDebugString(long now) {
1782 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1783 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1784 }
1785 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001786
Amith Yamasani04e0d262012-02-14 11:50:53 -08001787 /**
1788 * Returns the accounts for a specific user
1789 * @hide
1790 */
1791 public Account[] getAccounts(int userId) {
1792 checkReadAccountsPermission();
1793 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001794 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001795 long identityToken = clearCallingIdentity();
1796 try {
1797 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001798 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001799 }
1800 } finally {
1801 restoreCallingIdentity(identityToken);
1802 }
1803 }
1804
Amith Yamasanif29f2362012-04-05 18:29:52 -07001805 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001806 * Returns accounts for all running users.
1807 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001808 * @hide
1809 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001810 public AccountAndUser[] getRunningAccounts() {
1811 final int[] runningUserIds;
1812 try {
1813 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1814 } catch (RemoteException e) {
1815 // Running in system_server; should never happen
1816 throw new RuntimeException(e);
1817 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001818 return getAccounts(runningUserIds);
1819 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001820
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001821 /** {@hide} */
1822 public AccountAndUser[] getAllAccounts() {
1823 final List<UserInfo> users = getUserManager().getUsers();
1824 final int[] userIds = new int[users.size()];
1825 for (int i = 0; i < userIds.length; i++) {
1826 userIds[i] = users.get(i).id;
1827 }
1828 return getAccounts(userIds);
1829 }
1830
1831 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001832 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07001833 for (int userId : userIds) {
1834 UserAccounts userAccounts = getUserAccounts(userId);
1835 if (userAccounts == null) continue;
1836 synchronized (userAccounts.cacheLock) {
1837 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
1838 Binder.getCallingUid(), null);
1839 for (int a = 0; a < accounts.length; a++) {
1840 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001841 }
1842 }
1843 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001844
1845 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1846 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001847 }
1848
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001849 @Override
1850 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001851 return getAccountsAsUser(type, userId, null, -1);
1852 }
1853
1854 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
1855 int packageUid) {
1856 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001857 // Only allow the system process to read accounts of other users
1858 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001859 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001860 && mContext.checkCallingOrSelfPermission(
1861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1862 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001863 throw new SecurityException("User " + UserHandle.getCallingUserId()
1864 + " trying to get account for " + userId);
1865 }
1866
Fred Quintana56285a62010-12-02 14:20:51 -08001867 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1868 Log.v(TAG, "getAccounts: accountType " + type
1869 + ", caller's uid " + Binder.getCallingUid()
1870 + ", pid " + Binder.getCallingPid());
1871 }
Amith Yamasani27db4682013-03-30 17:07:47 -07001872 // If the original calling app was using the framework account chooser activity, we'll
1873 // be passed in the original caller's uid here, which is what should be used for filtering.
1874 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
1875 callingUid = packageUid;
1876 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001877 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001878 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001879 long identityToken = clearCallingIdentity();
1880 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001881 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001882 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001883 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001884 } finally {
1885 restoreCallingIdentity(identityToken);
1886 }
1887 }
1888
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001889 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001890 public boolean addSharedAccountAsUser(Account account, int userId) {
1891 userId = handleIncomingUser(userId);
1892 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1893 ContentValues values = new ContentValues();
1894 values.put(ACCOUNTS_NAME, account.name);
1895 values.put(ACCOUNTS_TYPE, account.type);
1896 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1897 new String[] {account.name, account.type});
1898 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1899 if (accountId < 0) {
1900 Log.w(TAG, "insertAccountIntoDatabase: " + account
1901 + ", skipping the DB insert failed");
1902 return false;
1903 }
1904 return true;
1905 }
1906
1907 @Override
1908 public boolean removeSharedAccountAsUser(Account account, int userId) {
1909 userId = handleIncomingUser(userId);
1910 UserAccounts accounts = getUserAccounts(userId);
1911 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1912 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1913 new String[] {account.name, account.type});
1914 if (r > 0) {
1915 removeAccountInternal(accounts, account);
1916 }
1917 return r > 0;
1918 }
1919
1920 @Override
1921 public Account[] getSharedAccountsAsUser(int userId) {
1922 userId = handleIncomingUser(userId);
1923 UserAccounts accounts = getUserAccounts(userId);
1924 ArrayList<Account> accountList = new ArrayList<Account>();
1925 Cursor cursor = null;
1926 try {
1927 cursor = accounts.openHelper.getReadableDatabase()
1928 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1929 null, null, null, null, null);
1930 if (cursor != null && cursor.moveToFirst()) {
1931 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1932 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1933 do {
1934 accountList.add(new Account(cursor.getString(nameIndex),
1935 cursor.getString(typeIndex)));
1936 } while (cursor.moveToNext());
1937 }
1938 } finally {
1939 if (cursor != null) {
1940 cursor.close();
1941 }
1942 }
1943 Account[] accountArray = new Account[accountList.size()];
1944 accountList.toArray(accountArray);
1945 return accountArray;
1946 }
1947
1948 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001949 public Account[] getAccounts(String type) {
1950 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1951 }
1952
Amith Yamasani27db4682013-03-30 17:07:47 -07001953 @Override
1954 public Account[] getAccountsForPackage(String packageName, int uid) {
1955 int callingUid = Binder.getCallingUid();
1956 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
1957 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
1958 + callingUid + " with uid=" + uid);
1959 }
1960 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
1961 }
1962
Amith Yamasani3b458ad2013-04-18 18:40:07 -07001963 @Override
1964 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
1965 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
1966 int packageUid = -1;
1967 try {
1968 packageUid = AppGlobals.getPackageManager().getPackageUid(
1969 packageName, UserHandle.getCallingUserId());
1970 } catch (RemoteException re) {
1971 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
1972 return new Account[0];
1973 }
1974 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
1975 }
1976
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001977 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001978 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001979 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001980 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1981 Log.v(TAG, "getAccounts: accountType " + type
1982 + ", response " + response
1983 + ", features " + stringArrayToString(features)
1984 + ", caller's uid " + Binder.getCallingUid()
1985 + ", pid " + Binder.getCallingPid());
1986 }
Fred Quintana382601f2010-03-25 12:25:10 -07001987 if (response == null) throw new IllegalArgumentException("response is null");
1988 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001989 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001990 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001991 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001992 long identityToken = clearCallingIdentity();
1993 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001994 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001995 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001996 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001997 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001998 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001999 Bundle result = new Bundle();
2000 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2001 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002002 return;
2003 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002004 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
2005 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002006 } finally {
2007 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002008 }
2009 }
2010
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002011 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002012 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002013 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002014 try {
2015 if (cursor.moveToNext()) {
2016 return cursor.getLong(0);
2017 }
2018 return -1;
2019 } finally {
2020 cursor.close();
2021 }
2022 }
2023
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002024 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002025 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2026 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2027 new String[]{key}, null, null, null);
2028 try {
2029 if (cursor.moveToNext()) {
2030 return cursor.getLong(0);
2031 }
2032 return -1;
2033 } finally {
2034 cursor.close();
2035 }
2036 }
2037
Fred Quintanaa698f422009-04-08 19:14:54 -07002038 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002039 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002040 IAccountManagerResponse mResponse;
2041 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002042 final boolean mExpectActivityLaunch;
2043 final long mCreationTime;
2044
Fred Quintana33269202009-04-20 16:05:10 -07002045 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002046 private int mNumRequestContinued = 0;
2047 private int mNumErrors = 0;
2048
Fred Quintana60307342009-03-24 22:48:12 -07002049 IAccountAuthenticator mAuthenticator = null;
2050
Fred Quintana8570f742010-02-18 10:32:54 -08002051 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002052 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002053
Amith Yamasani04e0d262012-02-14 11:50:53 -08002054 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08002055 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07002056 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002057 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002058 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002059 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002060 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002061 mResponse = response;
2062 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002063 mExpectActivityLaunch = expectActivityLaunch;
2064 mCreationTime = SystemClock.elapsedRealtime();
2065 synchronized (mSessions) {
2066 mSessions.put(toString(), this);
2067 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002068 if (response != null) {
2069 try {
2070 response.asBinder().linkToDeath(this, 0 /* flags */);
2071 } catch (RemoteException e) {
2072 mResponse = null;
2073 binderDied();
2074 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002075 }
Fred Quintana60307342009-03-24 22:48:12 -07002076 }
2077
Fred Quintanaa698f422009-04-08 19:14:54 -07002078 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002079 if (mResponse == null) {
2080 // this session has already been closed
2081 return null;
2082 }
Fred Quintana60307342009-03-24 22:48:12 -07002083 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002084 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002085 return response;
2086 }
2087
Fred Quintanaa698f422009-04-08 19:14:54 -07002088 private void close() {
2089 synchronized (mSessions) {
2090 if (mSessions.remove(toString()) == null) {
2091 // the session was already closed, so bail out now
2092 return;
2093 }
2094 }
2095 if (mResponse != null) {
2096 // stop listening for response deaths
2097 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2098
2099 // clear this so that we don't accidentally send any further results
2100 mResponse = null;
2101 }
2102 cancelTimeout();
2103 unbind();
2104 }
2105
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002106 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002107 public void binderDied() {
2108 mResponse = null;
2109 close();
2110 }
2111
2112 protected String toDebugString() {
2113 return toDebugString(SystemClock.elapsedRealtime());
2114 }
2115
2116 protected String toDebugString(long now) {
2117 return "Session: expectLaunch " + mExpectActivityLaunch
2118 + ", connected " + (mAuthenticator != null)
2119 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2120 + "/" + mNumErrors + ")"
2121 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2122 }
2123
Fred Quintana60307342009-03-24 22:48:12 -07002124 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002125 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2126 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2127 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002128 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002129 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002130 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002131 }
2132 }
2133
2134 private void unbind() {
2135 if (mAuthenticator != null) {
2136 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002137 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002138 }
2139 }
2140
2141 public void scheduleTimeout() {
2142 mMessageHandler.sendMessageDelayed(
2143 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2144 }
2145
2146 public void cancelTimeout() {
2147 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2148 }
2149
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002150 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002151 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002152 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002153 try {
2154 run();
2155 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002156 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002157 "remote exception");
2158 }
Fred Quintana60307342009-03-24 22:48:12 -07002159 }
2160
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002161 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002162 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002163 mAuthenticator = null;
2164 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002165 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002166 try {
2167 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2168 "disconnected");
2169 } catch (RemoteException e) {
2170 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2171 Log.v(TAG, "Session.onServiceDisconnected: "
2172 + "caught RemoteException while responding", e);
2173 }
2174 }
Fred Quintana60307342009-03-24 22:48:12 -07002175 }
2176 }
2177
Fred Quintanab839afc2009-10-14 15:57:28 -07002178 public abstract void run() throws RemoteException;
2179
Fred Quintana60307342009-03-24 22:48:12 -07002180 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002181 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002182 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002183 try {
2184 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2185 "timeout");
2186 } catch (RemoteException e) {
2187 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2188 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2189 e);
2190 }
2191 }
Fred Quintana60307342009-03-24 22:48:12 -07002192 }
2193 }
2194
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002195 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002196 public void onResult(Bundle result) {
2197 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002198 Intent intent = null;
2199 if (result != null
2200 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2201 /*
2202 * The Authenticator API allows third party authenticators to
2203 * supply arbitrary intents to other apps that they can run,
2204 * this can be very bad when those apps are in the system like
2205 * the System Settings.
2206 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002207 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07002208 long bid = Binder.clearCallingIdentity();
2209 try {
2210 PackageManager pm = mContext.getPackageManager();
2211 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2212 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2213 if (PackageManager.SIGNATURE_MATCH !=
2214 pm.checkSignatures(authenticatorUid, targetUid)) {
2215 throw new SecurityException(
2216 "Activity to be started with KEY_INTENT must " +
2217 "share Authenticator's signatures");
2218 }
2219 } finally {
2220 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002221 }
2222 }
2223 if (result != null
2224 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002225 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2226 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002227 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2228 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002229 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2230 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002231 }
Fred Quintana60307342009-03-24 22:48:12 -07002232 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002233 IAccountManagerResponse response;
2234 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002235 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002236 response = mResponse;
2237 } else {
2238 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002239 }
Fred Quintana60307342009-03-24 22:48:12 -07002240 if (response != null) {
2241 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002242 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002243 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2244 Log.v(TAG, getClass().getSimpleName()
2245 + " calling onError() on response " + response);
2246 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002247 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002248 "null bundle returned");
2249 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002250 if (mStripAuthTokenFromResult) {
2251 result.remove(AccountManager.KEY_AUTHTOKEN);
2252 }
Fred Quintana56285a62010-12-02 14:20:51 -08002253 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2254 Log.v(TAG, getClass().getSimpleName()
2255 + " calling onResult() on response " + response);
2256 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002257 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
2258 (intent == null)) {
2259 // All AccountManager error codes are greater than 0
2260 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
2261 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2262 } else {
2263 response.onResult(result);
2264 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002265 }
Fred Quintana60307342009-03-24 22:48:12 -07002266 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002267 // if the caller is dead then there is no one to care about remote exceptions
2268 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2269 Log.v(TAG, "failure while notifying response", e);
2270 }
Fred Quintana60307342009-03-24 22:48:12 -07002271 }
2272 }
2273 }
Fred Quintana60307342009-03-24 22:48:12 -07002274
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002275 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002276 public void onRequestContinued() {
2277 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002278 }
2279
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002280 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002281 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002282 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002283 IAccountManagerResponse response = getResponseAndClose();
2284 if (response != null) {
2285 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002286 Log.v(TAG, getClass().getSimpleName()
2287 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002288 }
2289 try {
2290 response.onError(errorCode, errorMessage);
2291 } catch (RemoteException e) {
2292 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2293 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2294 }
2295 }
2296 } else {
2297 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2298 Log.v(TAG, "Session.onError: already closed");
2299 }
Fred Quintana60307342009-03-24 22:48:12 -07002300 }
2301 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002302
2303 /**
2304 * find the component name for the authenticator and initiate a bind
2305 * if no authenticator or the bind fails then return false, otherwise return true
2306 */
2307 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002308 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2309 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2310 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002311 if (authenticatorInfo == null) {
2312 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2313 Log.v(TAG, "there is no authenticator for " + authenticatorType
2314 + ", bailing out");
2315 }
2316 return false;
2317 }
2318
2319 Intent intent = new Intent();
2320 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2321 intent.setComponent(authenticatorInfo.componentName);
2322 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2323 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2324 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002325 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2326 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002327 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2328 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2329 }
2330 return false;
2331 }
2332
2333
2334 return true;
2335 }
Fred Quintana60307342009-03-24 22:48:12 -07002336 }
2337
2338 private class MessageHandler extends Handler {
2339 MessageHandler(Looper looper) {
2340 super(looper);
2341 }
Costin Manolache3348f142009-09-29 18:58:36 -07002342
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002343 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002344 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002345 switch (msg.what) {
2346 case MESSAGE_TIMED_OUT:
2347 Session session = (Session)msg.obj;
2348 session.onTimedOut();
2349 break;
2350
Amith Yamasani5be347b2013-03-31 17:44:31 -07002351 case MESSAGE_COPY_SHARED_ACCOUNT:
2352 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2353 break;
2354
Fred Quintana60307342009-03-24 22:48:12 -07002355 default:
2356 throw new IllegalStateException("unhandled message: " + msg.what);
2357 }
2358 }
2359 }
2360
Amith Yamasani04e0d262012-02-14 11:50:53 -08002361 private static String getDatabaseName(int userId) {
2362 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002363 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002364 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002365 // Migrate old file, if it exists, to the new location.
2366 // Make sure the new file doesn't already exist. A dummy file could have been
2367 // accidentally created in the old location, causing the new one to become corrupted
2368 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002369 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002370 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002371 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002372 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002373 if (!userDir.exists()) {
2374 if (!userDir.mkdirs()) {
2375 throw new IllegalStateException("User dir cannot be created: " + userDir);
2376 }
2377 }
2378 if (!oldFile.renameTo(databaseFile)) {
2379 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2380 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002381 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002382 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002383 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002384 }
2385
Amith Yamasani04e0d262012-02-14 11:50:53 -08002386 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002387
Amith Yamasani04e0d262012-02-14 11:50:53 -08002388 public DatabaseHelper(Context context, int userId) {
2389 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002390 }
2391
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002392 /**
2393 * This call needs to be made while the mCacheLock is held. The way to
2394 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2395 * @param db The database.
2396 */
Fred Quintana60307342009-03-24 22:48:12 -07002397 @Override
2398 public void onCreate(SQLiteDatabase db) {
2399 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2400 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2401 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2402 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2403 + ACCOUNTS_PASSWORD + " TEXT, "
2404 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2405
2406 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2407 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2408 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2409 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2410 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2411 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2412
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002413 createGrantsTable(db);
2414
Fred Quintana60307342009-03-24 22:48:12 -07002415 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2416 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2417 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2418 + EXTRAS_KEY + " TEXT NOT NULL, "
2419 + EXTRAS_VALUE + " TEXT, "
2420 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2421
2422 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2423 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2424 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002425
Amith Yamasani67df64b2012-12-14 12:09:36 -08002426 createSharedAccountsTable(db);
2427
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002428 createAccountsDeletionTrigger(db);
2429 }
2430
Amith Yamasani67df64b2012-12-14 12:09:36 -08002431 private void createSharedAccountsTable(SQLiteDatabase db) {
2432 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2433 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2434 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2435 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2436 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2437 }
2438
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002439 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002440 db.execSQL(""
2441 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2442 + " BEGIN"
2443 + " DELETE FROM " + TABLE_AUTHTOKENS
2444 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2445 + " DELETE FROM " + TABLE_EXTRAS
2446 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002447 + " DELETE FROM " + TABLE_GRANTS
2448 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002449 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002450 }
2451
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002452 private void createGrantsTable(SQLiteDatabase db) {
2453 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2454 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2455 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2456 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2457 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2458 + "," + GRANTS_GRANTEE_UID + "))");
2459 }
2460
Fred Quintana60307342009-03-24 22:48:12 -07002461 @Override
2462 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002463 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002464
Fred Quintanaa698f422009-04-08 19:14:54 -07002465 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002466 // no longer need to do anything since the work is done
2467 // when upgrading from version 2
2468 oldVersion++;
2469 }
2470
2471 if (oldVersion == 2) {
2472 createGrantsTable(db);
2473 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2474 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002475 oldVersion++;
2476 }
Costin Manolache3348f142009-09-29 18:58:36 -07002477
2478 if (oldVersion == 3) {
2479 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2480 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2481 oldVersion++;
2482 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002483
2484 if (oldVersion == 4) {
2485 createSharedAccountsTable(db);
2486 oldVersion++;
2487 }
2488
2489 if (oldVersion != newVersion) {
2490 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2491 }
Fred Quintana60307342009-03-24 22:48:12 -07002492 }
2493
2494 @Override
2495 public void onOpen(SQLiteDatabase db) {
2496 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2497 }
2498 }
2499
Fred Quintana60307342009-03-24 22:48:12 -07002500 public IBinder onBind(Intent intent) {
2501 return asBinder();
2502 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002503
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002504 /**
2505 * Searches array of arguments for the specified string
2506 * @param args array of argument strings
2507 * @param value value to search for
2508 * @return true if the value is contained in the array
2509 */
2510 private static boolean scanArgs(String[] args, String value) {
2511 if (args != null) {
2512 for (String arg : args) {
2513 if (value.equals(arg)) {
2514 return true;
2515 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002516 }
2517 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002518 return false;
2519 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002520
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002521 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002522 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002523 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2524 != PackageManager.PERMISSION_GRANTED) {
2525 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2526 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2527 + " without permission " + android.Manifest.permission.DUMP);
2528 return;
2529 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002530 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002531 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002532
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002533 final List<UserInfo> users = getUserManager().getUsers();
2534 for (UserInfo user : users) {
2535 ipw.println("User " + user + ":");
2536 ipw.increaseIndent();
2537 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2538 ipw.println();
2539 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002540 }
2541 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002542
Amith Yamasani04e0d262012-02-14 11:50:53 -08002543 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2544 String[] args, boolean isCheckinRequest) {
2545 synchronized (userAccounts.cacheLock) {
2546 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002547
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002548 if (isCheckinRequest) {
2549 // This is a checkin request. *Only* upload the account types and the count of each.
2550 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2551 null, null, ACCOUNTS_TYPE, null, null);
2552 try {
2553 while (cursor.moveToNext()) {
2554 // print type,count
2555 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2556 }
2557 } finally {
2558 if (cursor != null) {
2559 cursor.close();
2560 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002561 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002562 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002563 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002564 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002565 fout.println("Accounts: " + accounts.length);
2566 for (Account account : accounts) {
2567 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002568 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002569
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002570 fout.println();
2571 synchronized (mSessions) {
2572 final long now = SystemClock.elapsedRealtime();
2573 fout.println("Active Sessions: " + mSessions.size());
2574 for (Session session : mSessions.values()) {
2575 fout.println(" " + session.toDebugString(now));
2576 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002577 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002578
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002579 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002580 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002581 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002582 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002583 }
2584
Amith Yamasani04e0d262012-02-14 11:50:53 -08002585 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002586 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002587 long identityToken = clearCallingIdentity();
2588 try {
2589 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2590 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2591 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002592
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002593 if (intent.getComponent() != null &&
2594 GrantCredentialsPermissionActivity.class.getName().equals(
2595 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002596 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002597 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002598 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002599 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002600 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2601 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002602 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002603 final String notificationTitleFormat =
2604 mContext.getText(R.string.notification_title).toString();
2605 n.setLatestEventInfo(mContext,
2606 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002607 message, PendingIntent.getActivityAsUser(
2608 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002609 null, user));
2610 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002611 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002612 } finally {
2613 restoreCallingIdentity(identityToken);
2614 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002615 }
2616
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002617 protected void installNotification(final int notificationId, final Notification n,
2618 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002619 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002620 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002621 }
2622
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002623 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002624 long identityToken = clearCallingIdentity();
2625 try {
2626 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002627 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002628 } finally {
2629 restoreCallingIdentity(identityToken);
2630 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002631 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002632
Fred Quintanab38eb142010-02-24 13:40:54 -08002633 /** Succeeds if any of the specified permissions are granted. */
2634 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002635 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002636
2637 for (String perm : permissions) {
2638 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2639 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002640 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002641 }
2642 return;
2643 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002644 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002645
2646 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002647 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002648 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002649 }
2650
Amith Yamasani67df64b2012-12-14 12:09:36 -08002651 private int handleIncomingUser(int userId) {
2652 try {
2653 return ActivityManagerNative.getDefault().handleIncomingUser(
2654 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2655 } catch (RemoteException re) {
2656 // Shouldn't happen, local.
2657 }
2658 return userId;
2659 }
2660
Christopher Tateccbf84f2013-05-08 15:25:41 -07002661 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002662 final int callingUserId = UserHandle.getUserId(callingUid);
2663
2664 final PackageManager userPackageManager;
2665 try {
2666 userPackageManager = mContext.createPackageContextAsUser(
2667 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2668 } catch (NameNotFoundException e) {
2669 return false;
2670 }
2671
2672 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002673 for (String name : packages) {
2674 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002675 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002676 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07002677 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002678 return true;
2679 }
2680 } catch (PackageManager.NameNotFoundException e) {
2681 return false;
2682 }
2683 }
2684 return false;
2685 }
2686
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002687 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07002688 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002689 final boolean fromAuthenticator = account != null
2690 && hasAuthenticatorUid(account.type, callerUid);
2691 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002692 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002693 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2694 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002695 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002696 + ": is authenticator? " + fromAuthenticator
2697 + ", has explicit permission? " + hasExplicitGrants);
2698 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07002699 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002700 }
2701
Fred Quintana1a231912009-10-15 11:31:30 -07002702 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002703 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002704 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002705 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002706 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002707 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002708 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002709 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002710 }
2711 }
2712 return false;
2713 }
2714
Amith Yamasani04e0d262012-02-14 11:50:53 -08002715 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2716 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002717 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002718 return true;
2719 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002720 UserAccounts accounts = getUserAccountsForCaller();
2721 synchronized (accounts.cacheLock) {
2722 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2723 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002724 account.name, account.type};
2725 final boolean permissionGranted =
2726 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2727 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2728 // TODO: Skip this check when running automated tests. Replace this
2729 // with a more general solution.
2730 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002731 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002732 + " but ignoring since device is in test harness.");
2733 return true;
2734 }
2735 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002736 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002737 }
2738
2739 private void checkCallingUidAgainstAuthenticator(Account account) {
2740 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002741 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002742 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2743 Log.w(TAG, msg);
2744 throw new SecurityException(msg);
2745 }
2746 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2747 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2748 }
2749 }
2750
2751 private void checkAuthenticateAccountsPermission(Account account) {
2752 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2753 checkCallingUidAgainstAuthenticator(account);
2754 }
2755
2756 private void checkReadAccountsPermission() {
2757 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2758 }
2759
2760 private void checkManageAccountsPermission() {
2761 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2762 }
2763
Fred Quintanab38eb142010-02-24 13:40:54 -08002764 private void checkManageAccountsOrUseCredentialsPermissions() {
2765 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2766 Manifest.permission.USE_CREDENTIALS);
2767 }
2768
Sander Alewijnseda1350f2014-05-08 16:59:42 +01002769 private boolean canUserModifyAccounts(int callingUid, String accountType) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002770 if (callingUid != Process.myUid()) {
2771 if (getUserManager().getUserRestrictions(
2772 new UserHandle(UserHandle.getUserId(callingUid)))
2773 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002774 return false;
2775 }
2776 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01002777
2778 DevicePolicyManager dpm = (DevicePolicyManager) mContext
2779 .getSystemService(Context.DEVICE_POLICY_SERVICE);
2780 String[] typesArray = dpm.getAccountTypesWithManagementDisabled();
2781 for (String forbiddenType : typesArray) {
2782 if (forbiddenType.equals(accountType)) {
2783 return false;
2784 }
2785 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002786 return true;
2787 }
2788
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002789 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002790 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2791 throws RemoteException {
2792 final int callingUid = getCallingUid();
2793
Amith Yamasani27db4682013-03-30 17:07:47 -07002794 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002795 throw new SecurityException();
2796 }
2797
2798 if (value) {
2799 grantAppPermission(account, authTokenType, uid);
2800 } else {
2801 revokeAppPermission(account, authTokenType, uid);
2802 }
2803 }
2804
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002805 /**
2806 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2807 * <p>
2808 * Although this is public it can only be accessed via the AccountManagerService object
2809 * which is in the system. This means we don't need to protect it with permissions.
2810 * @hide
2811 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002812 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002813 if (account == null || authTokenType == null) {
2814 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002815 return;
2816 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002817 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002818 synchronized (accounts.cacheLock) {
2819 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002820 db.beginTransaction();
2821 try {
2822 long accountId = getAccountIdLocked(db, account);
2823 if (accountId >= 0) {
2824 ContentValues values = new ContentValues();
2825 values.put(GRANTS_ACCOUNTS_ID, accountId);
2826 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2827 values.put(GRANTS_GRANTEE_UID, uid);
2828 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2829 db.setTransactionSuccessful();
2830 }
2831 } finally {
2832 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002833 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002834 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2835 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002836 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002837 }
2838
2839 /**
2840 * Don't allow callers with the given uid permission to get credentials for
2841 * account/authTokenType.
2842 * <p>
2843 * Although this is public it can only be accessed via the AccountManagerService object
2844 * which is in the system. This means we don't need to protect it with permissions.
2845 * @hide
2846 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002847 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002848 if (account == null || authTokenType == null) {
2849 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002850 return;
2851 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002852 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002853 synchronized (accounts.cacheLock) {
2854 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002855 db.beginTransaction();
2856 try {
2857 long accountId = getAccountIdLocked(db, account);
2858 if (accountId >= 0) {
2859 db.delete(TABLE_GRANTS,
2860 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2861 + GRANTS_GRANTEE_UID + "=?",
2862 new String[]{String.valueOf(accountId), authTokenType,
2863 String.valueOf(uid)});
2864 db.setTransactionSuccessful();
2865 }
2866 } finally {
2867 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002868 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002869 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2870 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002871 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002872 }
Fred Quintana56285a62010-12-02 14:20:51 -08002873
2874 static final private String stringArrayToString(String[] value) {
2875 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2876 }
2877
Amith Yamasani04e0d262012-02-14 11:50:53 -08002878 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2879 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002880 if (oldAccountsForType != null) {
2881 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2882 for (Account curAccount : oldAccountsForType) {
2883 if (!curAccount.equals(account)) {
2884 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002885 }
2886 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002887 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002888 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002889 } else {
2890 Account[] newAccountsForType = new Account[newAccountsList.size()];
2891 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002892 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002893 }
Fred Quintana56285a62010-12-02 14:20:51 -08002894 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002895 accounts.userDataCache.remove(account);
2896 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002897 }
2898
2899 /**
2900 * This assumes that the caller has already checked that the account is not already present.
2901 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002902 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2903 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002904 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2905 Account[] newAccountsForType = new Account[oldLength + 1];
2906 if (accountsForType != null) {
2907 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002908 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002909 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002910 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002911 }
2912
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002913 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07002914 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002915 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07002916 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002917 return unfiltered;
2918 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002919 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
2920 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002921 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002922 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002923 // otherwise return non-shared accounts only.
2924 // This might be a temporary way to specify a whitelist
2925 String whiteList = mContext.getResources().getString(
2926 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2927 for (String packageName : packages) {
2928 if (whiteList.contains(";" + packageName + ";")) {
2929 return unfiltered;
2930 }
2931 }
2932 ArrayList<Account> allowed = new ArrayList<Account>();
2933 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2934 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002935 String requiredAccountType = "";
2936 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07002937 // If there's an explicit callingPackage specified, check if that package
2938 // opted in to see restricted accounts.
2939 if (callingPackage != null) {
2940 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002941 if (pi != null && pi.restrictedAccountType != null) {
2942 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07002943 }
2944 } else {
2945 // Otherwise check if the callingUid has a package that has opted in
2946 for (String packageName : packages) {
2947 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
2948 if (pi != null && pi.restrictedAccountType != null) {
2949 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07002950 break;
2951 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002952 }
2953 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002954 } catch (NameNotFoundException nnfe) {
2955 }
2956 for (Account account : unfiltered) {
2957 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002958 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002959 } else {
2960 boolean found = false;
2961 for (Account shared : sharedAccounts) {
2962 if (shared.equals(account)) {
2963 found = true;
2964 break;
2965 }
2966 }
2967 if (!found) {
2968 allowed.add(account);
2969 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002970 }
2971 }
2972 Account[] filtered = new Account[allowed.size()];
2973 allowed.toArray(filtered);
2974 return filtered;
2975 } else {
2976 return unfiltered;
2977 }
2978 }
2979
Amith Yamasani27db4682013-03-30 17:07:47 -07002980 /*
2981 * packageName can be null. If not null, it should be used to filter out restricted accounts
2982 * that the package is not allowed to access.
2983 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002984 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07002985 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002986 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002987 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002988 if (accounts == null) {
2989 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002990 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002991 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07002992 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002993 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002994 } else {
2995 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002996 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002997 totalLength += accounts.length;
2998 }
2999 if (totalLength == 0) {
3000 return EMPTY_ACCOUNT_ARRAY;
3001 }
3002 Account[] accounts = new Account[totalLength];
3003 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003004 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003005 System.arraycopy(accountsOfType, 0, accounts, totalLength,
3006 accountsOfType.length);
3007 totalLength += accountsOfType.length;
3008 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003009 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003010 }
3011 }
3012
Amith Yamasani04e0d262012-02-14 11:50:53 -08003013 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3014 Account account, String key, String value) {
3015 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003016 if (userDataForAccount == null) {
3017 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003018 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003019 }
3020 if (value == null) {
3021 userDataForAccount.remove(key);
3022 } else {
3023 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003024 }
3025 }
3026
Amith Yamasani04e0d262012-02-14 11:50:53 -08003027 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3028 Account account, String key, String value) {
3029 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003030 if (authTokensForAccount == null) {
3031 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003032 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003033 }
3034 if (value == null) {
3035 authTokensForAccount.remove(key);
3036 } else {
3037 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003038 }
3039 }
3040
Amith Yamasani04e0d262012-02-14 11:50:53 -08003041 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
3042 String authTokenType) {
3043 synchronized (accounts.cacheLock) {
3044 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003045 if (authTokensForAccount == null) {
3046 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003047 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003048 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003049 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003050 }
3051 return authTokensForAccount.get(authTokenType);
3052 }
3053 }
3054
Amith Yamasani04e0d262012-02-14 11:50:53 -08003055 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
3056 synchronized (accounts.cacheLock) {
3057 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003058 if (userDataForAccount == null) {
3059 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003060 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003061 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003062 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003063 }
3064 return userDataForAccount.get(key);
3065 }
3066 }
3067
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003068 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3069 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003070 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003071 Cursor cursor = db.query(TABLE_EXTRAS,
3072 COLUMNS_EXTRAS_KEY_AND_VALUE,
3073 SELECTION_USERDATA_BY_ACCOUNT,
3074 new String[]{account.name, account.type},
3075 null, null, null);
3076 try {
3077 while (cursor.moveToNext()) {
3078 final String tmpkey = cursor.getString(0);
3079 final String value = cursor.getString(1);
3080 userDataForAccount.put(tmpkey, value);
3081 }
3082 } finally {
3083 cursor.close();
3084 }
3085 return userDataForAccount;
3086 }
3087
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003088 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3089 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003090 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003091 Cursor cursor = db.query(TABLE_AUTHTOKENS,
3092 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3093 SELECTION_AUTHTOKENS_BY_ACCOUNT,
3094 new String[]{account.name, account.type},
3095 null, null, null);
3096 try {
3097 while (cursor.moveToNext()) {
3098 final String type = cursor.getString(0);
3099 final String authToken = cursor.getString(1);
3100 authTokensForAccount.put(type, authToken);
3101 }
3102 } finally {
3103 cursor.close();
3104 }
3105 return authTokensForAccount;
3106 }
Fred Quintana60307342009-03-24 22:48:12 -07003107}