blob: 36d67eef8af2c1b6ca923f0d098311443a31192e [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();
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100874 int userId = Binder.getCallingUserHandle().getIdentifier();
875 if (!canUserModifyAccounts(userId)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800876 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100877 // TODO: This should be ERROR_CODE_USER_RESTRICTED instead. See http://b/16322768
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800878 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
879 "User cannot modify accounts");
880 } catch (RemoteException re) {
881 }
Amith Yamasani5934dbc2014-02-20 15:23:36 -0800882 return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800883 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100884 if (!canUserModifyAccountsForType(userId, account.type)) {
885 try {
886 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
887 "User cannot modify accounts of this type (policy).");
888 } catch (RemoteException re) {
889 }
890 return;
891 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800892
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700893 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800894
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700895 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Alexandra Gherghina999d3942014-07-03 11:40:08 +0100896 synchronized (accounts.credentialsPermissionNotificationIds) {
897 for (Pair<Pair<Account, String>, Integer> pair:
898 accounts.credentialsPermissionNotificationIds.keySet()) {
899 if (account.equals(pair.first.first)) {
900 int id = accounts.credentialsPermissionNotificationIds.get(pair);
901 cancelNotification(id, user);
902 }
903 }
904 }
905
906 try {
907 new RemoveAccountSession(accounts, response, account).bind();
908 } finally {
909 restoreCallingIdentity(identityToken);
910 }
911 }
912
913 @Override
914 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
915 int userId) {
916 if (Log.isLoggable(TAG, Log.VERBOSE)) {
917 Log.v(TAG, "removeAccount: " + account
918 + ", response " + response
919 + ", caller's uid " + Binder.getCallingUid()
920 + ", pid " + Binder.getCallingPid()
921 + ", for user id " + userId);
922 }
923 if (response == null) throw new IllegalArgumentException("response is null");
924 if (account == null) throw new IllegalArgumentException("account is null");
925
926 // Only allow the system process to modify accounts of other users
927 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
928 + " trying to remove account for " + userId);
929 checkManageAccountsPermission();
930
931 UserAccounts accounts = getUserAccounts(userId);
932 if (!canUserModifyAccounts(userId)) {
933 try {
934 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
935 "User cannot modify accounts");
936 } catch (RemoteException re) {
937 }
938 return;
939 }
940 if (!canUserModifyAccountsForType(userId, account.type)) {
941 try {
942 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
943 "User cannot modify accounts of this type (policy).");
944 } catch (RemoteException re) {
945 }
946 return;
947 }
948
949 UserHandle user = new UserHandle(userId);
950 long identityToken = clearCallingIdentity();
951
952 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800953 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800954 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800955 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800956 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800957 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700958 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800959 }
960 }
961 }
962
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700963 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800964 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700965 } finally {
966 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700967 }
Fred Quintana60307342009-03-24 22:48:12 -0700968 }
969
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700970 private class RemoveAccountSession extends Session {
971 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800972 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
973 Account account) {
974 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800975 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700976 mAccount = account;
977 }
978
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700979 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700980 protected String toDebugString(long now) {
981 return super.toDebugString(now) + ", removeAccount"
982 + ", account " + mAccount;
983 }
984
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700985 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700986 public void run() throws RemoteException {
987 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
988 }
989
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700990 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700991 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700992 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
993 && !result.containsKey(AccountManager.KEY_INTENT)) {
994 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700995 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800996 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700997 }
998 IAccountManagerResponse response = getResponseAndClose();
999 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001000 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1001 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1002 + response);
1003 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001004 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001005 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001006 try {
1007 response.onResult(result2);
1008 } catch (RemoteException e) {
1009 // ignore
1010 }
1011 }
1012 }
1013 super.onResult(result);
1014 }
1015 }
1016
Amith Yamasani04e0d262012-02-14 11:50:53 -08001017 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001018 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001019 removeAccountInternal(getUserAccountsForCaller(), account);
1020 }
1021
1022 private void removeAccountInternal(UserAccounts accounts, Account account) {
1023 synchronized (accounts.cacheLock) {
1024 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001025 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1026 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001027 removeAccountFromCacheLocked(accounts, account);
1028 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001029 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001030 if (accounts.userId == UserHandle.USER_OWNER) {
1031 // Owner's account was removed, remove from any users that are sharing
1032 // this account.
1033 long id = Binder.clearCallingIdentity();
1034 try {
1035 List<UserInfo> users = mUserManager.getUsers(true);
1036 for (UserInfo user : users) {
1037 if (!user.isPrimary() && user.isRestricted()) {
1038 removeSharedAccountAsUser(account, user.id);
1039 }
1040 }
1041 } finally {
1042 Binder.restoreCallingIdentity(id);
1043 }
1044 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001045 }
1046
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001047 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001048 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001049 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1050 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
1051 + ", caller's uid " + Binder.getCallingUid()
1052 + ", pid " + Binder.getCallingPid());
1053 }
Fred Quintana382601f2010-03-25 12:25:10 -07001054 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1055 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -08001056 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001057 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001058 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001059 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001060 synchronized (accounts.cacheLock) {
1061 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001062 db.beginTransaction();
1063 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001064 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001065 db.setTransactionSuccessful();
1066 } finally {
1067 db.endTransaction();
1068 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001069 }
Fred Quintana60307342009-03-24 22:48:12 -07001070 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001071 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001072 }
1073 }
1074
Amith Yamasani04e0d262012-02-14 11:50:53 -08001075 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1076 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001077 if (authToken == null || accountType == null) {
1078 return;
1079 }
Fred Quintana33269202009-04-20 16:05:10 -07001080 Cursor cursor = db.rawQuery(
1081 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1082 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1083 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1084 + " FROM " + TABLE_ACCOUNTS
1085 + " JOIN " + TABLE_AUTHTOKENS
1086 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1087 + " = " + AUTHTOKENS_ACCOUNTS_ID
1088 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1089 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1090 new String[]{authToken, accountType});
1091 try {
1092 while (cursor.moveToNext()) {
1093 long authTokenId = cursor.getLong(0);
1094 String accountName = cursor.getString(1);
1095 String authTokenType = cursor.getString(2);
1096 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001097 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001098 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -07001099 }
Fred Quintana33269202009-04-20 16:05:10 -07001100 } finally {
1101 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001102 }
1103 }
1104
Amith Yamasani04e0d262012-02-14 11:50:53 -08001105 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1106 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001107 if (account == null || type == null) {
1108 return false;
1109 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001110 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1111 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001112 synchronized (accounts.cacheLock) {
1113 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001114 db.beginTransaction();
1115 try {
1116 long accountId = getAccountIdLocked(db, account);
1117 if (accountId < 0) {
1118 return false;
1119 }
1120 db.delete(TABLE_AUTHTOKENS,
1121 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1122 new String[]{type});
1123 ContentValues values = new ContentValues();
1124 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1125 values.put(AUTHTOKENS_TYPE, type);
1126 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1127 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1128 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001129 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001130 return true;
1131 }
Fred Quintana33269202009-04-20 16:05:10 -07001132 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001133 } finally {
1134 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001135 }
Fred Quintana60307342009-03-24 22:48:12 -07001136 }
1137 }
1138
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001139 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001140 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001141 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1142 Log.v(TAG, "peekAuthToken: " + account
1143 + ", authTokenType " + authTokenType
1144 + ", caller's uid " + Binder.getCallingUid()
1145 + ", pid " + Binder.getCallingPid());
1146 }
Fred Quintana382601f2010-03-25 12:25:10 -07001147 if (account == null) throw new IllegalArgumentException("account is null");
1148 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001149 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001150 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001151 long identityToken = clearCallingIdentity();
1152 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001153 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001154 } finally {
1155 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001156 }
Fred Quintana60307342009-03-24 22:48:12 -07001157 }
1158
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001159 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001160 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001161 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1162 Log.v(TAG, "setAuthToken: " + account
1163 + ", authTokenType " + authTokenType
1164 + ", caller's uid " + Binder.getCallingUid()
1165 + ", pid " + Binder.getCallingPid());
1166 }
Fred Quintana382601f2010-03-25 12:25:10 -07001167 if (account == null) throw new IllegalArgumentException("account is null");
1168 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001169 checkAuthenticateAccountsPermission(account);
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 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
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 setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001181 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1182 Log.v(TAG, "setAuthToken: " + account
1183 + ", caller's uid " + Binder.getCallingUid()
1184 + ", pid " + Binder.getCallingPid());
1185 }
Fred Quintana382601f2010-03-25 12:25:10 -07001186 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001187 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001188 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001189 long identityToken = clearCallingIdentity();
1190 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001191 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001192 } finally {
1193 restoreCallingIdentity(identityToken);
1194 }
Fred Quintana60307342009-03-24 22:48:12 -07001195 }
1196
Amith Yamasani04e0d262012-02-14 11:50:53 -08001197 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001198 if (account == null) {
1199 return;
1200 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001201 synchronized (accounts.cacheLock) {
1202 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001203 db.beginTransaction();
1204 try {
1205 final ContentValues values = new ContentValues();
1206 values.put(ACCOUNTS_PASSWORD, password);
1207 final long accountId = getAccountIdLocked(db, account);
1208 if (accountId >= 0) {
1209 final String[] argsAccountId = {String.valueOf(accountId)};
1210 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1211 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001212 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001213 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001214 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001215 } finally {
1216 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001217 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001218 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001219 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001220 }
1221
Amith Yamasani04e0d262012-02-14 11:50:53 -08001222 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001223 Log.i(TAG, "the accounts changed, sending broadcast of "
1224 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001225 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001226 }
1227
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001228 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001229 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001230 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1231 Log.v(TAG, "clearPassword: " + account
1232 + ", caller's uid " + Binder.getCallingUid()
1233 + ", pid " + Binder.getCallingPid());
1234 }
Fred Quintana382601f2010-03-25 12:25:10 -07001235 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001236 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001237 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001238 long identityToken = clearCallingIdentity();
1239 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001240 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001241 } finally {
1242 restoreCallingIdentity(identityToken);
1243 }
Fred Quintana60307342009-03-24 22:48:12 -07001244 }
1245
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001246 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001247 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001248 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1249 Log.v(TAG, "setUserData: " + account
1250 + ", key " + key
1251 + ", caller's uid " + Binder.getCallingUid()
1252 + ", pid " + Binder.getCallingPid());
1253 }
Fred Quintana382601f2010-03-25 12:25:10 -07001254 if (key == null) throw new IllegalArgumentException("key is null");
1255 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001256 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001257 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001258 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001259 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001260 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001261 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001262 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001263 }
1264 }
1265
Amith Yamasani04e0d262012-02-14 11:50:53 -08001266 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1267 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001268 if (account == null || key == null) {
1269 return;
1270 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001271 synchronized (accounts.cacheLock) {
1272 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001273 db.beginTransaction();
1274 try {
1275 long accountId = getAccountIdLocked(db, account);
1276 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001277 return;
1278 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001279 long extrasId = getExtrasIdLocked(db, accountId, key);
1280 if (extrasId < 0 ) {
1281 extrasId = insertExtraLocked(db, accountId, key, value);
1282 if (extrasId < 0) {
1283 return;
1284 }
1285 } else {
1286 ContentValues values = new ContentValues();
1287 values.put(EXTRAS_VALUE, value);
1288 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1289 return;
1290 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001291
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001292 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001293 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001294 db.setTransactionSuccessful();
1295 } finally {
1296 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001297 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001298 }
1299 }
1300
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001301 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001302 if (result == null) {
1303 Log.e(TAG, "the result is unexpectedly null", new Exception());
1304 }
1305 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1306 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1307 + response);
1308 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001309 try {
1310 response.onResult(result);
1311 } catch (RemoteException e) {
1312 // if the caller is dead then there is no one to care about remote
1313 // exceptions
1314 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1315 Log.v(TAG, "failure while notifying response", e);
1316 }
1317 }
1318 }
1319
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001320 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001321 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1322 final String authTokenType)
1323 throws RemoteException {
1324 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001325 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1326
Fred Quintanad9640ec2012-05-23 12:37:00 -07001327 final int callingUid = getCallingUid();
1328 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001329 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001330 throw new SecurityException("can only call from system");
1331 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001332 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001333 long identityToken = clearCallingIdentity();
1334 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001335 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001336 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001337 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001338 protected String toDebugString(long now) {
1339 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001340 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001341 + ", authTokenType " + authTokenType;
1342 }
1343
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001344 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001345 public void run() throws RemoteException {
1346 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1347 }
1348
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001349 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001350 public void onResult(Bundle result) {
1351 if (result != null) {
1352 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1353 Bundle bundle = new Bundle();
1354 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1355 super.onResult(bundle);
1356 return;
1357 } else {
1358 super.onResult(result);
1359 }
1360 }
1361 }.bind();
1362 } finally {
1363 restoreCallingIdentity(identityToken);
1364 }
1365 }
1366
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001367 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001368 public void getAuthToken(IAccountManagerResponse response, final Account account,
1369 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001370 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001371 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1372 Log.v(TAG, "getAuthToken: " + account
1373 + ", response " + response
1374 + ", authTokenType " + authTokenType
1375 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1376 + ", expectActivityLaunch " + expectActivityLaunch
1377 + ", caller's uid " + Binder.getCallingUid()
1378 + ", pid " + Binder.getCallingPid());
1379 }
Fred Quintana382601f2010-03-25 12:25:10 -07001380 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001381 try {
1382 if (account == null) {
1383 Slog.w(TAG, "getAuthToken called with null account");
1384 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1385 return;
1386 }
1387 if (authTokenType == null) {
1388 Slog.w(TAG, "getAuthToken called with null authTokenType");
1389 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1390 return;
1391 }
1392 } catch (RemoteException e) {
1393 Slog.w(TAG, "Failed to report error back to the client." + e);
1394 return;
1395 }
1396
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001397 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001398 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001399 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1400 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1401 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001402 final boolean customTokens =
1403 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1404
1405 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001406 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001407 final boolean permissionGranted = customTokens ||
1408 permissionIsGranted(account, authTokenType, callerUid);
1409
Costin Manolachec6684f92011-01-14 11:25:39 -08001410 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1411 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001412 // let authenticator know the identity of the caller
1413 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1414 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1415 if (notifyOnAuthFailure) {
1416 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001417 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001418
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001419 long identityToken = clearCallingIdentity();
1420 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001421 // if the caller has permission, do the peek. otherwise go the more expensive
1422 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001423 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001424 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001425 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001426 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001427 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1428 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1429 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001430 onResult(response, result);
1431 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001432 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001433 }
1434
Amith Yamasani04e0d262012-02-14 11:50:53 -08001435 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001436 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001437 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001438 protected String toDebugString(long now) {
1439 if (loginOptions != null) loginOptions.keySet();
1440 return super.toDebugString(now) + ", getAuthToken"
1441 + ", " + account
1442 + ", authTokenType " + authTokenType
1443 + ", loginOptions " + loginOptions
1444 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1445 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001446
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001447 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001448 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001449 // If the caller doesn't have permission then create and return the
1450 // "grant permission" intent instead of the "getAuthToken" intent.
1451 if (!permissionGranted) {
1452 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1453 } else {
1454 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1455 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001456 }
1457
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001458 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001459 public void onResult(Bundle result) {
1460 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001461 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001462 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1463 new AccountAuthenticatorResponse(this),
1464 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001465 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001466 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001467 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001468 onResult(bundle);
1469 return;
1470 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001471 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001472 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001473 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1474 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001475 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001476 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001477 "the type and name should not be empty");
1478 return;
1479 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001480 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001481 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001482 authTokenType, authToken);
1483 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001484 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001485
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001486 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001487 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001488 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001489 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001490 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001491 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001492 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001493 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001494 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001495 }.bind();
1496 } finally {
1497 restoreCallingIdentity(identityToken);
1498 }
Fred Quintana60307342009-03-24 22:48:12 -07001499 }
1500
Dianne Hackborn41203752012-08-31 14:05:51 -07001501 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1502 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001503 int uid = intent.getIntExtra(
1504 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1505 String authTokenType = intent.getStringExtra(
1506 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1507 String authTokenLabel = intent.getStringExtra(
1508 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1509
1510 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1511 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001512 final String titleAndSubtitle =
1513 mContext.getString(R.string.permission_request_notification_with_subtitle,
1514 account.name);
1515 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001516 String title = titleAndSubtitle;
1517 String subtitle = "";
1518 if (index > 0) {
1519 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001520 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001521 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001522 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001523 n.setLatestEventInfo(mContext, title, subtitle,
1524 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001525 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1526 installNotification(getCredentialPermissionNotificationId(
1527 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001528 }
1529
Costin Manolache5f383ad92010-12-02 16:44:46 -08001530 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1531 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001532
1533 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001534 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001535 // Since it was set in Eclair+ we can't change it without breaking apps using
1536 // the intent from a non-Activity context.
1537 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001538 intent.addCategory(
1539 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001540
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001541 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001542 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1543 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001544 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001545
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001546 return intent;
1547 }
1548
1549 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1550 int uid) {
1551 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001552 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001553 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001554 final Pair<Pair<Account, String>, Integer> key =
1555 new Pair<Pair<Account, String>, Integer>(
1556 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001557 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001558 if (id == null) {
1559 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001560 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001561 }
1562 }
1563 return id;
1564 }
1565
Amith Yamasani04e0d262012-02-14 11:50:53 -08001566 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001567 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001568 synchronized (accounts.signinRequiredNotificationIds) {
1569 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001570 if (id == null) {
1571 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001572 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001573 }
1574 }
1575 return id;
1576 }
1577
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001578 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001579 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001580 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001581 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001582 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1583 Log.v(TAG, "addAccount: accountType " + accountType
1584 + ", response " + response
1585 + ", authTokenType " + authTokenType
1586 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1587 + ", expectActivityLaunch " + expectActivityLaunch
1588 + ", caller's uid " + Binder.getCallingUid()
1589 + ", pid " + Binder.getCallingPid());
1590 }
Fred Quintana382601f2010-03-25 12:25:10 -07001591 if (response == null) throw new IllegalArgumentException("response is null");
1592 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001593 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001594
Amith Yamasani71e6c692013-03-24 17:39:28 -07001595 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001596 int userId = Binder.getCallingUserHandle().getIdentifier();
1597 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001598 try {
1599 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1600 "User is not allowed to add an account!");
1601 } catch (RemoteException re) {
1602 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001603 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED);
1604 return;
1605 }
1606 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07001607 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001608 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1609 "User cannot modify accounts of this type (policy).");
1610 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07001611 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001612 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001613 return;
1614 }
1615
Amith Yamasani04e0d262012-02-14 11:50:53 -08001616 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001617 final int pid = Binder.getCallingPid();
1618 final int uid = Binder.getCallingUid();
1619 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1620 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1621 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1622
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001623 long identityToken = clearCallingIdentity();
1624 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001625 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001626 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001627 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001628 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001629 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001630 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001631 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001632
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001633 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001634 protected String toDebugString(long now) {
1635 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001636 + ", accountType " + accountType
1637 + ", requiredFeatures "
1638 + (requiredFeatures != null
1639 ? TextUtils.join(",", requiredFeatures)
1640 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001641 }
1642 }.bind();
1643 } finally {
1644 restoreCallingIdentity(identityToken);
1645 }
Fred Quintana60307342009-03-24 22:48:12 -07001646 }
1647
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001648 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001649 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
1650 final String authTokenType, final String[] requiredFeatures,
1651 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
1652 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1653 Log.v(TAG, "addAccount: accountType " + accountType
1654 + ", response " + response
1655 + ", authTokenType " + authTokenType
1656 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1657 + ", expectActivityLaunch " + expectActivityLaunch
1658 + ", caller's uid " + Binder.getCallingUid()
1659 + ", pid " + Binder.getCallingPid()
1660 + ", for user id " + userId);
1661 }
1662 if (response == null) throw new IllegalArgumentException("response is null");
1663 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1664 checkManageAccountsPermission();
1665
1666 // Only allow the system process to add accounts of other users
1667 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1668 + " trying to add account for " + userId);
1669
1670 // Is user disallowed from modifying accounts?
1671 if (!canUserModifyAccounts(userId)) {
1672 try {
1673 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1674 "User is not allowed to add an account!");
1675 } catch (RemoteException re) {
1676 }
1677 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED);
1678 return;
1679 }
1680 if (!canUserModifyAccountsForType(userId, accountType)) {
1681 try {
1682 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1683 "User cannot modify accounts of this type (policy).");
1684 } catch (RemoteException re) {
1685 }
1686 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
1687 return;
1688 }
1689
1690 UserAccounts accounts = getUserAccounts(userId);
1691 final int pid = Binder.getCallingPid();
1692 final int uid = Binder.getCallingUid();
1693 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1694 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1695 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1696
1697 long identityToken = clearCallingIdentity();
1698 try {
1699 new Session(accounts, response, accountType, expectActivityLaunch,
1700 true /* stripAuthTokenFromResult */) {
1701 @Override
1702 public void run() throws RemoteException {
1703 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
1704 options);
1705 }
1706
1707 @Override
1708 protected String toDebugString(long now) {
1709 return super.toDebugString(now) + ", addAccount"
1710 + ", accountType " + accountType
1711 + ", requiredFeatures "
1712 + (requiredFeatures != null
1713 ? TextUtils.join(",", requiredFeatures)
1714 : null);
1715 }
1716 }.bind();
1717 } finally {
1718 restoreCallingIdentity(identityToken);
1719 }
1720 }
1721
1722 private void showCantAddAccount(int errorCode) {
1723 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1724 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
1725 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1726 long identityToken = clearCallingIdentity();
1727 try {
1728 mContext.startActivity(cantAddAccount);
1729 } finally {
1730 restoreCallingIdentity(identityToken);
1731 }
1732 }
1733
1734 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001735 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1736 final Account account, final Bundle options, final boolean expectActivityLaunch,
1737 int userId) {
1738 // Only allow the system process to read accounts of other users
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001739 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001740 + " trying to confirm account credentials for " + userId);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001741
Fred Quintana56285a62010-12-02 14:20:51 -08001742 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1743 Log.v(TAG, "confirmCredentials: " + account
1744 + ", response " + response
1745 + ", expectActivityLaunch " + expectActivityLaunch
1746 + ", caller's uid " + Binder.getCallingUid()
1747 + ", pid " + Binder.getCallingPid());
1748 }
Fred Quintana382601f2010-03-25 12:25:10 -07001749 if (response == null) throw new IllegalArgumentException("response is null");
1750 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001751 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001752 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001753 long identityToken = clearCallingIdentity();
1754 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001755 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001756 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001757 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001758 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001759 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001760 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001761 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001762 protected String toDebugString(long now) {
1763 return super.toDebugString(now) + ", confirmCredentials"
1764 + ", " + account;
1765 }
1766 }.bind();
1767 } finally {
1768 restoreCallingIdentity(identityToken);
1769 }
Fred Quintana60307342009-03-24 22:48:12 -07001770 }
1771
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001772 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001773 public void updateCredentials(IAccountManagerResponse response, final Account account,
1774 final String authTokenType, final boolean expectActivityLaunch,
1775 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001776 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1777 Log.v(TAG, "updateCredentials: " + account
1778 + ", response " + response
1779 + ", authTokenType " + authTokenType
1780 + ", expectActivityLaunch " + expectActivityLaunch
1781 + ", caller's uid " + Binder.getCallingUid()
1782 + ", pid " + Binder.getCallingPid());
1783 }
Fred Quintana382601f2010-03-25 12:25:10 -07001784 if (response == null) throw new IllegalArgumentException("response is null");
1785 if (account == null) throw new IllegalArgumentException("account is null");
1786 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001787 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001788 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001789 long identityToken = clearCallingIdentity();
1790 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001791 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001792 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001793 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001794 public void run() throws RemoteException {
1795 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1796 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001797 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001798 protected String toDebugString(long now) {
1799 if (loginOptions != null) loginOptions.keySet();
1800 return super.toDebugString(now) + ", updateCredentials"
1801 + ", " + account
1802 + ", authTokenType " + authTokenType
1803 + ", loginOptions " + loginOptions;
1804 }
1805 }.bind();
1806 } finally {
1807 restoreCallingIdentity(identityToken);
1808 }
Fred Quintana60307342009-03-24 22:48:12 -07001809 }
1810
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001811 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001812 public void editProperties(IAccountManagerResponse response, final String accountType,
1813 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001814 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1815 Log.v(TAG, "editProperties: accountType " + accountType
1816 + ", response " + response
1817 + ", expectActivityLaunch " + expectActivityLaunch
1818 + ", caller's uid " + Binder.getCallingUid()
1819 + ", pid " + Binder.getCallingPid());
1820 }
Fred Quintana382601f2010-03-25 12:25:10 -07001821 if (response == null) throw new IllegalArgumentException("response is null");
1822 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001823 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001824 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001825 long identityToken = clearCallingIdentity();
1826 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001827 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001828 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001829 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001830 public void run() throws RemoteException {
1831 mAuthenticator.editProperties(this, mAccountType);
1832 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001833 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001834 protected String toDebugString(long now) {
1835 return super.toDebugString(now) + ", editProperties"
1836 + ", accountType " + accountType;
1837 }
1838 }.bind();
1839 } finally {
1840 restoreCallingIdentity(identityToken);
1841 }
Fred Quintana60307342009-03-24 22:48:12 -07001842 }
1843
Fred Quintana33269202009-04-20 16:05:10 -07001844 private class GetAccountsByTypeAndFeatureSession extends Session {
1845 private final String[] mFeatures;
1846 private volatile Account[] mAccountsOfType = null;
1847 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1848 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001849 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001850
Amith Yamasani04e0d262012-02-14 11:50:53 -08001851 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001852 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001853 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001854 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001855 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001856 mFeatures = features;
1857 }
1858
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001859 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001860 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001861 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001862 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1863 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001864 }
Fred Quintana33269202009-04-20 16:05:10 -07001865 // check whether each account matches the requested features
1866 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1867 mCurrentAccount = 0;
1868
1869 checkAccount();
1870 }
1871
1872 public void checkAccount() {
1873 if (mCurrentAccount >= mAccountsOfType.length) {
1874 sendResult();
1875 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001876 }
Fred Quintana33269202009-04-20 16:05:10 -07001877
Fred Quintana29e94b82010-03-10 12:11:51 -08001878 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1879 if (accountAuthenticator == null) {
1880 // It is possible that the authenticator has died, which is indicated by
1881 // mAuthenticator being set to null. If this happens then just abort.
1882 // There is no need to send back a result or error in this case since
1883 // that already happened when mAuthenticator was cleared.
1884 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1885 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1886 + " connected to the authenticator, " + toDebugString());
1887 }
1888 return;
1889 }
Fred Quintana33269202009-04-20 16:05:10 -07001890 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001891 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001892 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001893 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001894 }
1895 }
1896
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001897 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001898 public void onResult(Bundle result) {
1899 mNumResults++;
1900 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001901 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001902 return;
1903 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001904 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001905 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1906 }
1907 mCurrentAccount++;
1908 checkAccount();
1909 }
1910
1911 public void sendResult() {
1912 IAccountManagerResponse response = getResponseAndClose();
1913 if (response != null) {
1914 try {
1915 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1916 for (int i = 0; i < accounts.length; i++) {
1917 accounts[i] = mAccountsWithFeatures.get(i);
1918 }
Fred Quintana56285a62010-12-02 14:20:51 -08001919 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1920 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1921 + response);
1922 }
Fred Quintana33269202009-04-20 16:05:10 -07001923 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001924 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001925 response.onResult(result);
1926 } catch (RemoteException e) {
1927 // if the caller is dead then there is no one to care about remote exceptions
1928 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1929 Log.v(TAG, "failure while notifying response", e);
1930 }
1931 }
1932 }
1933 }
1934
1935
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001936 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001937 protected String toDebugString(long now) {
1938 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1939 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1940 }
1941 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001942
Amith Yamasani04e0d262012-02-14 11:50:53 -08001943 /**
1944 * Returns the accounts for a specific user
1945 * @hide
1946 */
1947 public Account[] getAccounts(int userId) {
1948 checkReadAccountsPermission();
1949 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001950 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001951 long identityToken = clearCallingIdentity();
1952 try {
1953 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001954 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001955 }
1956 } finally {
1957 restoreCallingIdentity(identityToken);
1958 }
1959 }
1960
Amith Yamasanif29f2362012-04-05 18:29:52 -07001961 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001962 * Returns accounts for all running users.
1963 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001964 * @hide
1965 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001966 public AccountAndUser[] getRunningAccounts() {
1967 final int[] runningUserIds;
1968 try {
1969 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1970 } catch (RemoteException e) {
1971 // Running in system_server; should never happen
1972 throw new RuntimeException(e);
1973 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001974 return getAccounts(runningUserIds);
1975 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001976
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001977 /** {@hide} */
1978 public AccountAndUser[] getAllAccounts() {
1979 final List<UserInfo> users = getUserManager().getUsers();
1980 final int[] userIds = new int[users.size()];
1981 for (int i = 0; i < userIds.length; i++) {
1982 userIds[i] = users.get(i).id;
1983 }
1984 return getAccounts(userIds);
1985 }
1986
1987 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001988 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07001989 for (int userId : userIds) {
1990 UserAccounts userAccounts = getUserAccounts(userId);
1991 if (userAccounts == null) continue;
1992 synchronized (userAccounts.cacheLock) {
1993 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
1994 Binder.getCallingUid(), null);
1995 for (int a = 0; a < accounts.length; a++) {
1996 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001997 }
1998 }
1999 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002000
2001 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2002 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002003 }
2004
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002005 @Override
2006 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002007 return getAccountsAsUser(type, userId, null, -1);
2008 }
2009
2010 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
2011 int packageUid) {
2012 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002013 // Only allow the system process to read accounts of other users
2014 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002015 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002016 && mContext.checkCallingOrSelfPermission(
2017 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2018 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002019 throw new SecurityException("User " + UserHandle.getCallingUserId()
2020 + " trying to get account for " + userId);
2021 }
2022
Fred Quintana56285a62010-12-02 14:20:51 -08002023 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2024 Log.v(TAG, "getAccounts: accountType " + type
2025 + ", caller's uid " + Binder.getCallingUid()
2026 + ", pid " + Binder.getCallingPid());
2027 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002028 // If the original calling app was using the framework account chooser activity, we'll
2029 // be passed in the original caller's uid here, which is what should be used for filtering.
2030 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2031 callingUid = packageUid;
2032 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002033 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002034 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002035 long identityToken = clearCallingIdentity();
2036 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002037 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002038 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002039 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002040 } finally {
2041 restoreCallingIdentity(identityToken);
2042 }
2043 }
2044
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002045 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002046 public boolean addSharedAccountAsUser(Account account, int userId) {
2047 userId = handleIncomingUser(userId);
2048 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
2049 ContentValues values = new ContentValues();
2050 values.put(ACCOUNTS_NAME, account.name);
2051 values.put(ACCOUNTS_TYPE, account.type);
2052 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2053 new String[] {account.name, account.type});
2054 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2055 if (accountId < 0) {
2056 Log.w(TAG, "insertAccountIntoDatabase: " + account
2057 + ", skipping the DB insert failed");
2058 return false;
2059 }
2060 return true;
2061 }
2062
2063 @Override
2064 public boolean removeSharedAccountAsUser(Account account, int userId) {
2065 userId = handleIncomingUser(userId);
2066 UserAccounts accounts = getUserAccounts(userId);
2067 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2068 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2069 new String[] {account.name, account.type});
2070 if (r > 0) {
2071 removeAccountInternal(accounts, account);
2072 }
2073 return r > 0;
2074 }
2075
2076 @Override
2077 public Account[] getSharedAccountsAsUser(int userId) {
2078 userId = handleIncomingUser(userId);
2079 UserAccounts accounts = getUserAccounts(userId);
2080 ArrayList<Account> accountList = new ArrayList<Account>();
2081 Cursor cursor = null;
2082 try {
2083 cursor = accounts.openHelper.getReadableDatabase()
2084 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2085 null, null, null, null, null);
2086 if (cursor != null && cursor.moveToFirst()) {
2087 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2088 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2089 do {
2090 accountList.add(new Account(cursor.getString(nameIndex),
2091 cursor.getString(typeIndex)));
2092 } while (cursor.moveToNext());
2093 }
2094 } finally {
2095 if (cursor != null) {
2096 cursor.close();
2097 }
2098 }
2099 Account[] accountArray = new Account[accountList.size()];
2100 accountList.toArray(accountArray);
2101 return accountArray;
2102 }
2103
2104 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002105 public Account[] getAccounts(String type) {
2106 return getAccountsAsUser(type, UserHandle.getCallingUserId());
2107 }
2108
Amith Yamasani27db4682013-03-30 17:07:47 -07002109 @Override
2110 public Account[] getAccountsForPackage(String packageName, int uid) {
2111 int callingUid = Binder.getCallingUid();
2112 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2113 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2114 + callingUid + " with uid=" + uid);
2115 }
2116 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
2117 }
2118
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002119 @Override
2120 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
2121 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
2122 int packageUid = -1;
2123 try {
2124 packageUid = AppGlobals.getPackageManager().getPackageUid(
2125 packageName, UserHandle.getCallingUserId());
2126 } catch (RemoteException re) {
2127 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2128 return new Account[0];
2129 }
2130 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
2131 }
2132
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002133 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002134 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07002135 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08002136 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2137 Log.v(TAG, "getAccounts: accountType " + type
2138 + ", response " + response
2139 + ", features " + stringArrayToString(features)
2140 + ", caller's uid " + Binder.getCallingUid()
2141 + ", pid " + Binder.getCallingPid());
2142 }
Fred Quintana382601f2010-03-25 12:25:10 -07002143 if (response == null) throw new IllegalArgumentException("response is null");
2144 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002145 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002146 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002147 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07002148 long identityToken = clearCallingIdentity();
2149 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002150 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002151 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002152 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002153 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002154 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002155 Bundle result = new Bundle();
2156 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2157 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002158 return;
2159 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002160 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
2161 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002162 } finally {
2163 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002164 }
2165 }
2166
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002167 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002168 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002169 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002170 try {
2171 if (cursor.moveToNext()) {
2172 return cursor.getLong(0);
2173 }
2174 return -1;
2175 } finally {
2176 cursor.close();
2177 }
2178 }
2179
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002180 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002181 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2182 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2183 new String[]{key}, null, null, null);
2184 try {
2185 if (cursor.moveToNext()) {
2186 return cursor.getLong(0);
2187 }
2188 return -1;
2189 } finally {
2190 cursor.close();
2191 }
2192 }
2193
Fred Quintanaa698f422009-04-08 19:14:54 -07002194 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002195 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002196 IAccountManagerResponse mResponse;
2197 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002198 final boolean mExpectActivityLaunch;
2199 final long mCreationTime;
2200
Fred Quintana33269202009-04-20 16:05:10 -07002201 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002202 private int mNumRequestContinued = 0;
2203 private int mNumErrors = 0;
2204
Fred Quintana60307342009-03-24 22:48:12 -07002205 IAccountAuthenticator mAuthenticator = null;
2206
Fred Quintana8570f742010-02-18 10:32:54 -08002207 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002208 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002209
Amith Yamasani04e0d262012-02-14 11:50:53 -08002210 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08002211 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07002212 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002213 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002214 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002215 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002216 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002217 mResponse = response;
2218 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002219 mExpectActivityLaunch = expectActivityLaunch;
2220 mCreationTime = SystemClock.elapsedRealtime();
2221 synchronized (mSessions) {
2222 mSessions.put(toString(), this);
2223 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002224 if (response != null) {
2225 try {
2226 response.asBinder().linkToDeath(this, 0 /* flags */);
2227 } catch (RemoteException e) {
2228 mResponse = null;
2229 binderDied();
2230 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002231 }
Fred Quintana60307342009-03-24 22:48:12 -07002232 }
2233
Fred Quintanaa698f422009-04-08 19:14:54 -07002234 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002235 if (mResponse == null) {
2236 // this session has already been closed
2237 return null;
2238 }
Fred Quintana60307342009-03-24 22:48:12 -07002239 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002240 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002241 return response;
2242 }
2243
Fred Quintanaa698f422009-04-08 19:14:54 -07002244 private void close() {
2245 synchronized (mSessions) {
2246 if (mSessions.remove(toString()) == null) {
2247 // the session was already closed, so bail out now
2248 return;
2249 }
2250 }
2251 if (mResponse != null) {
2252 // stop listening for response deaths
2253 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2254
2255 // clear this so that we don't accidentally send any further results
2256 mResponse = null;
2257 }
2258 cancelTimeout();
2259 unbind();
2260 }
2261
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002262 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002263 public void binderDied() {
2264 mResponse = null;
2265 close();
2266 }
2267
2268 protected String toDebugString() {
2269 return toDebugString(SystemClock.elapsedRealtime());
2270 }
2271
2272 protected String toDebugString(long now) {
2273 return "Session: expectLaunch " + mExpectActivityLaunch
2274 + ", connected " + (mAuthenticator != null)
2275 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2276 + "/" + mNumErrors + ")"
2277 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2278 }
2279
Fred Quintana60307342009-03-24 22:48:12 -07002280 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002281 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2282 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2283 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002284 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002285 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002286 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002287 }
2288 }
2289
2290 private void unbind() {
2291 if (mAuthenticator != null) {
2292 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002293 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002294 }
2295 }
2296
2297 public void scheduleTimeout() {
2298 mMessageHandler.sendMessageDelayed(
2299 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2300 }
2301
2302 public void cancelTimeout() {
2303 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2304 }
2305
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002306 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002307 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002308 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002309 try {
2310 run();
2311 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002312 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002313 "remote exception");
2314 }
Fred Quintana60307342009-03-24 22:48:12 -07002315 }
2316
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002317 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002318 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002319 mAuthenticator = null;
2320 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002321 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002322 try {
2323 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2324 "disconnected");
2325 } catch (RemoteException e) {
2326 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2327 Log.v(TAG, "Session.onServiceDisconnected: "
2328 + "caught RemoteException while responding", e);
2329 }
2330 }
Fred Quintana60307342009-03-24 22:48:12 -07002331 }
2332 }
2333
Fred Quintanab839afc2009-10-14 15:57:28 -07002334 public abstract void run() throws RemoteException;
2335
Fred Quintana60307342009-03-24 22:48:12 -07002336 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002337 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002338 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002339 try {
2340 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2341 "timeout");
2342 } catch (RemoteException e) {
2343 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2344 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2345 e);
2346 }
2347 }
Fred Quintana60307342009-03-24 22:48:12 -07002348 }
2349 }
2350
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002351 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002352 public void onResult(Bundle result) {
2353 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002354 Intent intent = null;
2355 if (result != null
2356 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2357 /*
2358 * The Authenticator API allows third party authenticators to
2359 * supply arbitrary intents to other apps that they can run,
2360 * this can be very bad when those apps are in the system like
2361 * the System Settings.
2362 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002363 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07002364 long bid = Binder.clearCallingIdentity();
2365 try {
2366 PackageManager pm = mContext.getPackageManager();
2367 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2368 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2369 if (PackageManager.SIGNATURE_MATCH !=
2370 pm.checkSignatures(authenticatorUid, targetUid)) {
2371 throw new SecurityException(
2372 "Activity to be started with KEY_INTENT must " +
2373 "share Authenticator's signatures");
2374 }
2375 } finally {
2376 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002377 }
2378 }
2379 if (result != null
2380 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002381 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2382 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002383 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2384 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002385 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2386 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002387 }
Fred Quintana60307342009-03-24 22:48:12 -07002388 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002389 IAccountManagerResponse response;
2390 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002391 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002392 response = mResponse;
2393 } else {
2394 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002395 }
Fred Quintana60307342009-03-24 22:48:12 -07002396 if (response != null) {
2397 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002398 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002399 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2400 Log.v(TAG, getClass().getSimpleName()
2401 + " calling onError() on response " + response);
2402 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002403 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002404 "null bundle returned");
2405 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002406 if (mStripAuthTokenFromResult) {
2407 result.remove(AccountManager.KEY_AUTHTOKEN);
2408 }
Fred Quintana56285a62010-12-02 14:20:51 -08002409 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2410 Log.v(TAG, getClass().getSimpleName()
2411 + " calling onResult() on response " + response);
2412 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002413 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
2414 (intent == null)) {
2415 // All AccountManager error codes are greater than 0
2416 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
2417 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2418 } else {
2419 response.onResult(result);
2420 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002421 }
Fred Quintana60307342009-03-24 22:48:12 -07002422 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002423 // if the caller is dead then there is no one to care about remote exceptions
2424 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2425 Log.v(TAG, "failure while notifying response", e);
2426 }
Fred Quintana60307342009-03-24 22:48:12 -07002427 }
2428 }
2429 }
Fred Quintana60307342009-03-24 22:48:12 -07002430
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002431 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002432 public void onRequestContinued() {
2433 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002434 }
2435
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002436 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002437 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002438 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002439 IAccountManagerResponse response = getResponseAndClose();
2440 if (response != null) {
2441 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002442 Log.v(TAG, getClass().getSimpleName()
2443 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002444 }
2445 try {
2446 response.onError(errorCode, errorMessage);
2447 } catch (RemoteException e) {
2448 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2449 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2450 }
2451 }
2452 } else {
2453 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2454 Log.v(TAG, "Session.onError: already closed");
2455 }
Fred Quintana60307342009-03-24 22:48:12 -07002456 }
2457 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002458
2459 /**
2460 * find the component name for the authenticator and initiate a bind
2461 * if no authenticator or the bind fails then return false, otherwise return true
2462 */
2463 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002464 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2465 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2466 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002467 if (authenticatorInfo == null) {
2468 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2469 Log.v(TAG, "there is no authenticator for " + authenticatorType
2470 + ", bailing out");
2471 }
2472 return false;
2473 }
2474
2475 Intent intent = new Intent();
2476 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2477 intent.setComponent(authenticatorInfo.componentName);
2478 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2479 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2480 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002481 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2482 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002483 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2484 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2485 }
2486 return false;
2487 }
2488
2489
2490 return true;
2491 }
Fred Quintana60307342009-03-24 22:48:12 -07002492 }
2493
2494 private class MessageHandler extends Handler {
2495 MessageHandler(Looper looper) {
2496 super(looper);
2497 }
Costin Manolache3348f142009-09-29 18:58:36 -07002498
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002499 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002500 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002501 switch (msg.what) {
2502 case MESSAGE_TIMED_OUT:
2503 Session session = (Session)msg.obj;
2504 session.onTimedOut();
2505 break;
2506
Amith Yamasani5be347b2013-03-31 17:44:31 -07002507 case MESSAGE_COPY_SHARED_ACCOUNT:
2508 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2509 break;
2510
Fred Quintana60307342009-03-24 22:48:12 -07002511 default:
2512 throw new IllegalStateException("unhandled message: " + msg.what);
2513 }
2514 }
2515 }
2516
Amith Yamasani04e0d262012-02-14 11:50:53 -08002517 private static String getDatabaseName(int userId) {
2518 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002519 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002520 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002521 // Migrate old file, if it exists, to the new location.
2522 // Make sure the new file doesn't already exist. A dummy file could have been
2523 // accidentally created in the old location, causing the new one to become corrupted
2524 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002525 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002526 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002527 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002528 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002529 if (!userDir.exists()) {
2530 if (!userDir.mkdirs()) {
2531 throw new IllegalStateException("User dir cannot be created: " + userDir);
2532 }
2533 }
2534 if (!oldFile.renameTo(databaseFile)) {
2535 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2536 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002537 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002538 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002539 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002540 }
2541
Amith Yamasani04e0d262012-02-14 11:50:53 -08002542 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002543
Amith Yamasani04e0d262012-02-14 11:50:53 -08002544 public DatabaseHelper(Context context, int userId) {
2545 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002546 }
2547
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002548 /**
2549 * This call needs to be made while the mCacheLock is held. The way to
2550 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2551 * @param db The database.
2552 */
Fred Quintana60307342009-03-24 22:48:12 -07002553 @Override
2554 public void onCreate(SQLiteDatabase db) {
2555 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2556 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2557 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2558 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2559 + ACCOUNTS_PASSWORD + " TEXT, "
2560 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2561
2562 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2563 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2564 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2565 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2566 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2567 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2568
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002569 createGrantsTable(db);
2570
Fred Quintana60307342009-03-24 22:48:12 -07002571 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2572 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2573 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2574 + EXTRAS_KEY + " TEXT NOT NULL, "
2575 + EXTRAS_VALUE + " TEXT, "
2576 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2577
2578 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2579 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2580 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002581
Amith Yamasani67df64b2012-12-14 12:09:36 -08002582 createSharedAccountsTable(db);
2583
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002584 createAccountsDeletionTrigger(db);
2585 }
2586
Amith Yamasani67df64b2012-12-14 12:09:36 -08002587 private void createSharedAccountsTable(SQLiteDatabase db) {
2588 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2589 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2590 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2591 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2592 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2593 }
2594
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002595 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002596 db.execSQL(""
2597 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2598 + " BEGIN"
2599 + " DELETE FROM " + TABLE_AUTHTOKENS
2600 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2601 + " DELETE FROM " + TABLE_EXTRAS
2602 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002603 + " DELETE FROM " + TABLE_GRANTS
2604 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002605 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002606 }
2607
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002608 private void createGrantsTable(SQLiteDatabase db) {
2609 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2610 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2611 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2612 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2613 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2614 + "," + GRANTS_GRANTEE_UID + "))");
2615 }
2616
Fred Quintana60307342009-03-24 22:48:12 -07002617 @Override
2618 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002619 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002620
Fred Quintanaa698f422009-04-08 19:14:54 -07002621 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002622 // no longer need to do anything since the work is done
2623 // when upgrading from version 2
2624 oldVersion++;
2625 }
2626
2627 if (oldVersion == 2) {
2628 createGrantsTable(db);
2629 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2630 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002631 oldVersion++;
2632 }
Costin Manolache3348f142009-09-29 18:58:36 -07002633
2634 if (oldVersion == 3) {
2635 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2636 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2637 oldVersion++;
2638 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002639
2640 if (oldVersion == 4) {
2641 createSharedAccountsTable(db);
2642 oldVersion++;
2643 }
2644
2645 if (oldVersion != newVersion) {
2646 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2647 }
Fred Quintana60307342009-03-24 22:48:12 -07002648 }
2649
2650 @Override
2651 public void onOpen(SQLiteDatabase db) {
2652 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2653 }
2654 }
2655
Fred Quintana60307342009-03-24 22:48:12 -07002656 public IBinder onBind(Intent intent) {
2657 return asBinder();
2658 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002659
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002660 /**
2661 * Searches array of arguments for the specified string
2662 * @param args array of argument strings
2663 * @param value value to search for
2664 * @return true if the value is contained in the array
2665 */
2666 private static boolean scanArgs(String[] args, String value) {
2667 if (args != null) {
2668 for (String arg : args) {
2669 if (value.equals(arg)) {
2670 return true;
2671 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002672 }
2673 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002674 return false;
2675 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002676
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002677 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002678 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002679 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2680 != PackageManager.PERMISSION_GRANTED) {
2681 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2682 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2683 + " without permission " + android.Manifest.permission.DUMP);
2684 return;
2685 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002686 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002687 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002688
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002689 final List<UserInfo> users = getUserManager().getUsers();
2690 for (UserInfo user : users) {
2691 ipw.println("User " + user + ":");
2692 ipw.increaseIndent();
2693 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2694 ipw.println();
2695 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002696 }
2697 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002698
Amith Yamasani04e0d262012-02-14 11:50:53 -08002699 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2700 String[] args, boolean isCheckinRequest) {
2701 synchronized (userAccounts.cacheLock) {
2702 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002703
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002704 if (isCheckinRequest) {
2705 // This is a checkin request. *Only* upload the account types and the count of each.
2706 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2707 null, null, ACCOUNTS_TYPE, null, null);
2708 try {
2709 while (cursor.moveToNext()) {
2710 // print type,count
2711 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2712 }
2713 } finally {
2714 if (cursor != null) {
2715 cursor.close();
2716 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002717 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002718 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002719 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002720 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002721 fout.println("Accounts: " + accounts.length);
2722 for (Account account : accounts) {
2723 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002724 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002725
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002726 fout.println();
2727 synchronized (mSessions) {
2728 final long now = SystemClock.elapsedRealtime();
2729 fout.println("Active Sessions: " + mSessions.size());
2730 for (Session session : mSessions.values()) {
2731 fout.println(" " + session.toDebugString(now));
2732 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002733 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002734
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002735 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002736 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002737 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002738 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002739 }
2740
Amith Yamasani04e0d262012-02-14 11:50:53 -08002741 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002742 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002743 long identityToken = clearCallingIdentity();
2744 try {
2745 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2746 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2747 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002748
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002749 if (intent.getComponent() != null &&
2750 GrantCredentialsPermissionActivity.class.getName().equals(
2751 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002752 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002753 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002754 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002755 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002756 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2757 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002758 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002759 final String notificationTitleFormat =
2760 mContext.getText(R.string.notification_title).toString();
2761 n.setLatestEventInfo(mContext,
2762 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002763 message, PendingIntent.getActivityAsUser(
2764 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002765 null, user));
2766 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002767 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002768 } finally {
2769 restoreCallingIdentity(identityToken);
2770 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002771 }
2772
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002773 protected void installNotification(final int notificationId, final Notification n,
2774 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002775 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002776 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002777 }
2778
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002779 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002780 long identityToken = clearCallingIdentity();
2781 try {
2782 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002783 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002784 } finally {
2785 restoreCallingIdentity(identityToken);
2786 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002787 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002788
Fred Quintanab38eb142010-02-24 13:40:54 -08002789 /** Succeeds if any of the specified permissions are granted. */
2790 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002791 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002792
2793 for (String perm : permissions) {
2794 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2795 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002796 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002797 }
2798 return;
2799 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002800 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002801
2802 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002803 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002804 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002805 }
2806
Amith Yamasani67df64b2012-12-14 12:09:36 -08002807 private int handleIncomingUser(int userId) {
2808 try {
2809 return ActivityManagerNative.getDefault().handleIncomingUser(
2810 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2811 } catch (RemoteException re) {
2812 // Shouldn't happen, local.
2813 }
2814 return userId;
2815 }
2816
Christopher Tateccbf84f2013-05-08 15:25:41 -07002817 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002818 final int callingUserId = UserHandle.getUserId(callingUid);
2819
2820 final PackageManager userPackageManager;
2821 try {
2822 userPackageManager = mContext.createPackageContextAsUser(
2823 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2824 } catch (NameNotFoundException e) {
2825 return false;
2826 }
2827
2828 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002829 for (String name : packages) {
2830 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002831 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002832 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07002833 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002834 return true;
2835 }
2836 } catch (PackageManager.NameNotFoundException e) {
2837 return false;
2838 }
2839 }
2840 return false;
2841 }
2842
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002843 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07002844 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002845 final boolean fromAuthenticator = account != null
2846 && hasAuthenticatorUid(account.type, callerUid);
2847 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002848 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002849 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2850 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002851 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002852 + ": is authenticator? " + fromAuthenticator
2853 + ", has explicit permission? " + hasExplicitGrants);
2854 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07002855 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002856 }
2857
Fred Quintana1a231912009-10-15 11:31:30 -07002858 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002859 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002860 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002861 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002862 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002863 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002864 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002865 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002866 }
2867 }
2868 return false;
2869 }
2870
Amith Yamasani04e0d262012-02-14 11:50:53 -08002871 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2872 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002873 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002874 return true;
2875 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002876 UserAccounts accounts = getUserAccountsForCaller();
2877 synchronized (accounts.cacheLock) {
2878 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2879 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002880 account.name, account.type};
2881 final boolean permissionGranted =
2882 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2883 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2884 // TODO: Skip this check when running automated tests. Replace this
2885 // with a more general solution.
2886 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002887 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002888 + " but ignoring since device is in test harness.");
2889 return true;
2890 }
2891 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002892 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002893 }
2894
2895 private void checkCallingUidAgainstAuthenticator(Account account) {
2896 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002897 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002898 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2899 Log.w(TAG, msg);
2900 throw new SecurityException(msg);
2901 }
2902 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2903 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2904 }
2905 }
2906
2907 private void checkAuthenticateAccountsPermission(Account account) {
2908 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2909 checkCallingUidAgainstAuthenticator(account);
2910 }
2911
2912 private void checkReadAccountsPermission() {
2913 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2914 }
2915
2916 private void checkManageAccountsPermission() {
2917 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2918 }
2919
Fred Quintanab38eb142010-02-24 13:40:54 -08002920 private void checkManageAccountsOrUseCredentialsPermissions() {
2921 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2922 Manifest.permission.USE_CREDENTIALS);
2923 }
2924
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002925 private boolean canUserModifyAccounts(int userId) {
2926 if (getUserManager().getUserRestrictions(new UserHandle(userId))
2927 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
2928 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002929 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002930 return true;
2931 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01002932
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002933 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01002934 DevicePolicyManager dpm = (DevicePolicyManager) mContext
2935 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002936 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Sander Alewijnseda1350f2014-05-08 16:59:42 +01002937 for (String forbiddenType : typesArray) {
2938 if (forbiddenType.equals(accountType)) {
2939 return false;
2940 }
2941 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002942 return true;
2943 }
2944
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002945 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002946 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2947 throws RemoteException {
2948 final int callingUid = getCallingUid();
2949
Amith Yamasani27db4682013-03-30 17:07:47 -07002950 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002951 throw new SecurityException();
2952 }
2953
2954 if (value) {
2955 grantAppPermission(account, authTokenType, uid);
2956 } else {
2957 revokeAppPermission(account, authTokenType, uid);
2958 }
2959 }
2960
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002961 /**
2962 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2963 * <p>
2964 * Although this is public it can only be accessed via the AccountManagerService object
2965 * which is in the system. This means we don't need to protect it with permissions.
2966 * @hide
2967 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002968 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002969 if (account == null || authTokenType == null) {
2970 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002971 return;
2972 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002973 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002974 synchronized (accounts.cacheLock) {
2975 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002976 db.beginTransaction();
2977 try {
2978 long accountId = getAccountIdLocked(db, account);
2979 if (accountId >= 0) {
2980 ContentValues values = new ContentValues();
2981 values.put(GRANTS_ACCOUNTS_ID, accountId);
2982 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2983 values.put(GRANTS_GRANTEE_UID, uid);
2984 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2985 db.setTransactionSuccessful();
2986 }
2987 } finally {
2988 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002989 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002990 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2991 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002992 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002993 }
2994
2995 /**
2996 * Don't allow callers with the given uid permission to get credentials for
2997 * account/authTokenType.
2998 * <p>
2999 * Although this is public it can only be accessed via the AccountManagerService object
3000 * which is in the system. This means we don't need to protect it with permissions.
3001 * @hide
3002 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003003 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003004 if (account == null || authTokenType == null) {
3005 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003006 return;
3007 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003008 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003009 synchronized (accounts.cacheLock) {
3010 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003011 db.beginTransaction();
3012 try {
3013 long accountId = getAccountIdLocked(db, account);
3014 if (accountId >= 0) {
3015 db.delete(TABLE_GRANTS,
3016 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
3017 + GRANTS_GRANTEE_UID + "=?",
3018 new String[]{String.valueOf(accountId), authTokenType,
3019 String.valueOf(uid)});
3020 db.setTransactionSuccessful();
3021 }
3022 } finally {
3023 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003024 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003025 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3026 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003027 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003028 }
Fred Quintana56285a62010-12-02 14:20:51 -08003029
3030 static final private String stringArrayToString(String[] value) {
3031 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
3032 }
3033
Amith Yamasani04e0d262012-02-14 11:50:53 -08003034 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
3035 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003036 if (oldAccountsForType != null) {
3037 ArrayList<Account> newAccountsList = new ArrayList<Account>();
3038 for (Account curAccount : oldAccountsForType) {
3039 if (!curAccount.equals(account)) {
3040 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003041 }
3042 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003043 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003044 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003045 } else {
3046 Account[] newAccountsForType = new Account[newAccountsList.size()];
3047 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003048 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003049 }
Fred Quintana56285a62010-12-02 14:20:51 -08003050 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003051 accounts.userDataCache.remove(account);
3052 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003053 }
3054
3055 /**
3056 * This assumes that the caller has already checked that the account is not already present.
3057 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08003058 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
3059 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003060 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
3061 Account[] newAccountsForType = new Account[oldLength + 1];
3062 if (accountsForType != null) {
3063 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08003064 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003065 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003066 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08003067 }
3068
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003069 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07003070 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003071 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07003072 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003073 return unfiltered;
3074 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003075 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
3076 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003077 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003078 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003079 // otherwise return non-shared accounts only.
3080 // This might be a temporary way to specify a whitelist
3081 String whiteList = mContext.getResources().getString(
3082 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
3083 for (String packageName : packages) {
3084 if (whiteList.contains(";" + packageName + ";")) {
3085 return unfiltered;
3086 }
3087 }
3088 ArrayList<Account> allowed = new ArrayList<Account>();
3089 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
3090 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003091 String requiredAccountType = "";
3092 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07003093 // If there's an explicit callingPackage specified, check if that package
3094 // opted in to see restricted accounts.
3095 if (callingPackage != null) {
3096 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003097 if (pi != null && pi.restrictedAccountType != null) {
3098 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07003099 }
3100 } else {
3101 // Otherwise check if the callingUid has a package that has opted in
3102 for (String packageName : packages) {
3103 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
3104 if (pi != null && pi.restrictedAccountType != null) {
3105 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07003106 break;
3107 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003108 }
3109 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003110 } catch (NameNotFoundException nnfe) {
3111 }
3112 for (Account account : unfiltered) {
3113 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003114 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003115 } else {
3116 boolean found = false;
3117 for (Account shared : sharedAccounts) {
3118 if (shared.equals(account)) {
3119 found = true;
3120 break;
3121 }
3122 }
3123 if (!found) {
3124 allowed.add(account);
3125 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003126 }
3127 }
3128 Account[] filtered = new Account[allowed.size()];
3129 allowed.toArray(filtered);
3130 return filtered;
3131 } else {
3132 return unfiltered;
3133 }
3134 }
3135
Amith Yamasani27db4682013-03-30 17:07:47 -07003136 /*
3137 * packageName can be null. If not null, it should be used to filter out restricted accounts
3138 * that the package is not allowed to access.
3139 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003140 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07003141 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003142 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003143 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003144 if (accounts == null) {
3145 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08003146 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003147 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07003148 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003149 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003150 } else {
3151 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003152 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003153 totalLength += accounts.length;
3154 }
3155 if (totalLength == 0) {
3156 return EMPTY_ACCOUNT_ARRAY;
3157 }
3158 Account[] accounts = new Account[totalLength];
3159 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003160 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003161 System.arraycopy(accountsOfType, 0, accounts, totalLength,
3162 accountsOfType.length);
3163 totalLength += accountsOfType.length;
3164 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003165 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003166 }
3167 }
3168
Amith Yamasani04e0d262012-02-14 11:50:53 -08003169 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3170 Account account, String key, String value) {
3171 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003172 if (userDataForAccount == null) {
3173 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003174 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003175 }
3176 if (value == null) {
3177 userDataForAccount.remove(key);
3178 } else {
3179 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003180 }
3181 }
3182
Amith Yamasani04e0d262012-02-14 11:50:53 -08003183 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3184 Account account, String key, String value) {
3185 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003186 if (authTokensForAccount == null) {
3187 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003188 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003189 }
3190 if (value == null) {
3191 authTokensForAccount.remove(key);
3192 } else {
3193 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003194 }
3195 }
3196
Amith Yamasani04e0d262012-02-14 11:50:53 -08003197 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
3198 String authTokenType) {
3199 synchronized (accounts.cacheLock) {
3200 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003201 if (authTokensForAccount == null) {
3202 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003203 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003204 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003205 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003206 }
3207 return authTokensForAccount.get(authTokenType);
3208 }
3209 }
3210
Amith Yamasani04e0d262012-02-14 11:50:53 -08003211 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
3212 synchronized (accounts.cacheLock) {
3213 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003214 if (userDataForAccount == null) {
3215 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003216 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003217 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003218 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003219 }
3220 return userDataForAccount.get(key);
3221 }
3222 }
3223
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003224 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3225 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003226 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003227 Cursor cursor = db.query(TABLE_EXTRAS,
3228 COLUMNS_EXTRAS_KEY_AND_VALUE,
3229 SELECTION_USERDATA_BY_ACCOUNT,
3230 new String[]{account.name, account.type},
3231 null, null, null);
3232 try {
3233 while (cursor.moveToNext()) {
3234 final String tmpkey = cursor.getString(0);
3235 final String value = cursor.getString(1);
3236 userDataForAccount.put(tmpkey, value);
3237 }
3238 } finally {
3239 cursor.close();
3240 }
3241 return userDataForAccount;
3242 }
3243
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003244 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3245 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003246 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003247 Cursor cursor = db.query(TABLE_AUTHTOKENS,
3248 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3249 SELECTION_AUTHTOKENS_BY_ACCOUNT,
3250 new String[]{account.name, account.type},
3251 null, null, null);
3252 try {
3253 while (cursor.moveToNext()) {
3254 final String type = cursor.getString(0);
3255 final String authToken = cursor.getString(1);
3256 authTokensForAccount.put(type, authToken);
3257 }
3258 } finally {
3259 cursor.close();
3260 }
3261 return authTokensForAccount;
3262 }
Fred Quintana60307342009-03-24 22:48:12 -07003263}