blob: 85eed859f6acfc0da0d761dcaf76a180da9e36fc [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";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700112 private static final int DATABASE_VERSION = 6;
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";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700133 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Fred Quintana60307342009-03-24 22:48:12 -0700134
135 private static final String TABLE_AUTHTOKENS = "authtokens";
136 private static final String AUTHTOKENS_ID = "_id";
137 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
138 private static final String AUTHTOKENS_TYPE = "type";
139 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
140
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700141 private static final String TABLE_GRANTS = "grants";
142 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
143 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
144 private static final String GRANTS_GRANTEE_UID = "uid";
145
Fred Quintana60307342009-03-24 22:48:12 -0700146 private static final String TABLE_EXTRAS = "extras";
147 private static final String EXTRAS_ID = "_id";
148 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
149 private static final String EXTRAS_KEY = "key";
150 private static final String EXTRAS_VALUE = "value";
151
152 private static final String TABLE_META = "meta";
153 private static final String META_KEY = "key";
154 private static final String META_VALUE = "value";
155
Amith Yamasani67df64b2012-12-14 12:09:36 -0800156 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
157
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700158 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
159 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700160 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700161
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700162 private static final String COUNT_OF_MATCHING_GRANTS = ""
163 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
164 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
165 + " AND " + GRANTS_GRANTEE_UID + "=?"
166 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
167 + " AND " + ACCOUNTS_NAME + "=?"
168 + " AND " + ACCOUNTS_TYPE + "=?";
169
Fred Quintana56285a62010-12-02 14:20:51 -0800170 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
171 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
172 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
173 AUTHTOKENS_AUTHTOKEN};
174
175 private static final String SELECTION_USERDATA_BY_ACCOUNT =
176 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
177 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
178
Fred Quintanaa698f422009-04-08 19:14:54 -0700179 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700180 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
181
Amith Yamasani04e0d262012-02-14 11:50:53 -0800182 static class UserAccounts {
183 private final int userId;
184 private final DatabaseHelper openHelper;
185 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
186 credentialsPermissionNotificationIds =
187 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
188 private final HashMap<Account, Integer> signinRequiredNotificationIds =
189 new HashMap<Account, Integer>();
190 private final Object cacheLock = new Object();
191 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700192 private final HashMap<String, Account[]> accountCache =
193 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800194 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800195 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800196 new HashMap<Account, HashMap<String, String>>();
197 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800198 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800199 new HashMap<Account, HashMap<String, String>>();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700200 /**
201 * protected by the {@link #cacheLock}
202 *
203 * Caches the previous names associated with an account. Previous names
204 * should be cached because we expect that when an Account is renamed,
205 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
206 * want to know if the accounts they care about have been renamed.
207 *
208 * The previous names are wrapped in an {@link AtomicReference} so that
209 * we can distinguish between those accounts with no previous names and
210 * those whose previous names haven't been cached (yet).
211 */
212 private final HashMap<Account, AtomicReference<String>> previousNameCache =
213 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800214
215 UserAccounts(Context context, int userId) {
216 this.userId = userId;
217 synchronized (cacheLock) {
218 openHelper = new DatabaseHelper(context, userId);
219 }
220 }
221 }
222
223 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
224
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700225 private static AtomicReference<AccountManagerService> sThis =
226 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700227 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700228
229 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700230 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700231 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
232 }
233
Fred Quintana56285a62010-12-02 14:20:51 -0800234
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700235 /**
236 * This should only be called by system code. One should only call this after the service
237 * has started.
238 * @return a reference to the AccountManagerService instance
239 * @hide
240 */
241 public static AccountManagerService getSingleton() {
242 return sThis.get();
243 }
Fred Quintana60307342009-03-24 22:48:12 -0700244
Fred Quintana56285a62010-12-02 14:20:51 -0800245 public AccountManagerService(Context context) {
246 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700247 }
248
Fred Quintana56285a62010-12-02 14:20:51 -0800249 public AccountManagerService(Context context, PackageManager packageManager,
250 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700251 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800252 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700253
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700254 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700255
Fred Quintana56285a62010-12-02 14:20:51 -0800256 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800257 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700258
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700259 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800260
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800261 IntentFilter intentFilter = new IntentFilter();
262 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
263 intentFilter.addDataScheme("package");
264 mContext.registerReceiver(new BroadcastReceiver() {
265 @Override
266 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700267 // Don't delete accounts when updating a authenticator's
268 // package.
269 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
270 purgeOldGrantsAll();
271 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800272 }
273 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800274
Amith Yamasani13593602012-03-22 16:16:17 -0700275 IntentFilter userFilter = new IntentFilter();
276 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800277 userFilter.addAction(Intent.ACTION_USER_STARTED);
278 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700279 @Override
280 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800281 String action = intent.getAction();
282 if (Intent.ACTION_USER_REMOVED.equals(action)) {
283 onUserRemoved(intent);
284 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
285 onUserStarted(intent);
286 }
Amith Yamasani13593602012-03-22 16:16:17 -0700287 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800288 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800289 }
290
Dianne Hackborn164371f2013-10-01 19:10:13 -0700291 @Override
292 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
293 throws RemoteException {
294 try {
295 return super.onTransact(code, data, reply, flags);
296 } catch (RuntimeException e) {
297 // The account manager only throws security exceptions, so let's
298 // log all others.
299 if (!(e instanceof SecurityException)) {
300 Slog.wtf(TAG, "Account Manager Crash", e);
301 }
302 throw e;
303 }
304 }
305
Kenny Root26ff6622012-07-30 12:58:03 -0700306 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700307 }
308
Amith Yamasani258848d2012-08-10 17:06:33 -0700309 private UserManager getUserManager() {
310 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700311 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700312 }
313 return mUserManager;
314 }
315
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700316 /* Caller should lock mUsers */
317 private UserAccounts initUserLocked(int userId) {
318 UserAccounts accounts = mUsers.get(userId);
319 if (accounts == null) {
320 accounts = new UserAccounts(mContext, userId);
321 mUsers.append(userId, accounts);
322 purgeOldGrants(accounts);
323 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800324 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700325 return accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800326 }
327
328 private void purgeOldGrantsAll() {
329 synchronized (mUsers) {
330 for (int i = 0; i < mUsers.size(); i++) {
331 purgeOldGrants(mUsers.valueAt(i));
332 }
333 }
334 }
335
336 private void purgeOldGrants(UserAccounts accounts) {
337 synchronized (accounts.cacheLock) {
338 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800339 final Cursor cursor = db.query(TABLE_GRANTS,
340 new String[]{GRANTS_GRANTEE_UID},
341 null, null, GRANTS_GRANTEE_UID, null, null);
342 try {
343 while (cursor.moveToNext()) {
344 final int uid = cursor.getInt(0);
345 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
346 if (packageExists) {
347 continue;
348 }
349 Log.d(TAG, "deleting grants for UID " + uid
350 + " because its package is no longer installed");
351 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
352 new String[]{Integer.toString(uid)});
353 }
354 } finally {
355 cursor.close();
356 }
357 }
358 }
359
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700360 /**
361 * Validate internal set of accounts against installed authenticators for
362 * given user. Clears cached authenticators before validating.
363 */
364 public void validateAccounts(int userId) {
365 final UserAccounts accounts = getUserAccounts(userId);
366
367 // Invalidate user-specific cache to make sure we catch any
368 // removed authenticators.
369 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
370 }
371
372 /**
373 * Validate internal set of accounts against installed authenticators for
374 * given user. Clear cached authenticators before validating when requested.
375 */
376 private void validateAccountsInternal(
377 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
378 if (invalidateAuthenticatorCache) {
379 mAuthenticatorCache.invalidateCache(accounts.userId);
380 }
381
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700382 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
383 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
384 mAuthenticatorCache.getAllServices(accounts.userId)) {
385 knownAuth.add(service.type);
386 }
387
Amith Yamasani04e0d262012-02-14 11:50:53 -0800388 synchronized (accounts.cacheLock) {
389 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800390 boolean accountDeleted = false;
391 Cursor cursor = db.query(TABLE_ACCOUNTS,
392 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
393 null, null, null, null, null);
394 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800395 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800396 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700397 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800398 while (cursor.moveToNext()) {
399 final long accountId = cursor.getLong(0);
400 final String accountType = cursor.getString(1);
401 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700402
403 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700404 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800405 + accountType + " no longer has a registered authenticator");
406 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
407 accountDeleted = true;
408 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800409 accounts.userDataCache.remove(account);
410 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800411 } else {
412 ArrayList<String> accountNames = accountNamesByType.get(accountType);
413 if (accountNames == null) {
414 accountNames = new ArrayList<String>();
415 accountNamesByType.put(accountType, accountNames);
416 }
417 accountNames.add(accountName);
418 }
419 }
Andy McFadden2f362292012-01-20 14:43:38 -0800420 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800421 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800422 final String accountType = cur.getKey();
423 final ArrayList<String> accountNames = cur.getValue();
424 final Account[] accountsForType = new Account[accountNames.size()];
425 int i = 0;
426 for (String accountName : accountNames) {
427 accountsForType[i] = new Account(accountName, accountType);
428 ++i;
429 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800430 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800431 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800432 } finally {
433 cursor.close();
434 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800435 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800436 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800437 }
438 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700439 }
440
Amith Yamasani04e0d262012-02-14 11:50:53 -0800441 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700442 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800443 }
444
445 protected UserAccounts getUserAccounts(int userId) {
446 synchronized (mUsers) {
447 UserAccounts accounts = mUsers.get(userId);
448 if (accounts == null) {
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700449 accounts = initUserLocked(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800450 mUsers.append(userId, accounts);
451 }
452 return accounts;
453 }
454 }
455
Amith Yamasani13593602012-03-22 16:16:17 -0700456 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700457 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700458 if (userId < 1) return;
459
460 UserAccounts accounts;
461 synchronized (mUsers) {
462 accounts = mUsers.get(userId);
463 mUsers.remove(userId);
464 }
465 if (accounts == null) {
466 File dbFile = new File(getDatabaseName(userId));
467 dbFile.delete();
468 return;
469 }
470
471 synchronized (accounts.cacheLock) {
472 accounts.openHelper.close();
473 File dbFile = new File(getDatabaseName(userId));
474 dbFile.delete();
475 }
476 }
477
Amith Yamasani67df64b2012-12-14 12:09:36 -0800478 private void onUserStarted(Intent intent) {
479 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
480 if (userId < 1) return;
481
482 // Check if there's a shared account that needs to be created as an account
483 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
484 if (sharedAccounts == null || sharedAccounts.length == 0) return;
485 Account[] accounts = getAccountsAsUser(null, userId);
486 for (Account sa : sharedAccounts) {
487 if (ArrayUtils.contains(accounts, sa)) continue;
488 // Account doesn't exist. Copy it now.
489 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
490 }
491 }
492
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700493 @Override
494 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700495 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700496 }
497
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800498 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700499 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800500 if (Log.isLoggable(TAG, Log.VERBOSE)) {
501 Log.v(TAG, "getPassword: " + account
502 + ", caller's uid " + Binder.getCallingUid()
503 + ", pid " + Binder.getCallingPid());
504 }
Fred Quintana382601f2010-03-25 12:25:10 -0700505 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700506 checkAuthenticateAccountsPermission(account);
507
Amith Yamasani04e0d262012-02-14 11:50:53 -0800508 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700509 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700510 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800511 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700512 } finally {
513 restoreCallingIdentity(identityToken);
514 }
515 }
516
Amith Yamasani04e0d262012-02-14 11:50:53 -0800517 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700518 if (account == null) {
519 return null;
520 }
521
Amith Yamasani04e0d262012-02-14 11:50:53 -0800522 synchronized (accounts.cacheLock) {
523 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800524 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
525 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
526 new String[]{account.name, account.type}, null, null, null);
527 try {
528 if (cursor.moveToNext()) {
529 return cursor.getString(0);
530 }
531 return null;
532 } finally {
533 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700534 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700535 }
536 }
537
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800538 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700539 public String getPreviousName(Account account) {
540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
541 Log.v(TAG, "getPreviousName: " + account
542 + ", caller's uid " + Binder.getCallingUid()
543 + ", pid " + Binder.getCallingPid());
544 }
545 if (account == null) throw new IllegalArgumentException("account is null");
546 UserAccounts accounts = getUserAccountsForCaller();
547 long identityToken = clearCallingIdentity();
548 try {
549 return readPreviousNameInternal(accounts, account);
550 } finally {
551 restoreCallingIdentity(identityToken);
552 }
553 }
554
555 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
556 if (account == null) {
557 return null;
558 }
559 synchronized (accounts.cacheLock) {
560 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
561 if (previousNameRef == null) {
562 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
563 Cursor cursor = db.query(
564 TABLE_ACCOUNTS,
565 new String[]{ ACCOUNTS_PREVIOUS_NAME },
566 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
567 new String[] { account.name, account.type },
568 null,
569 null,
570 null);
571 try {
572 if (cursor.moveToNext()) {
573 String previousName = cursor.getString(0);
574 previousNameRef = new AtomicReference<String>(previousName);
575 accounts.previousNameCache.put(account, previousNameRef);
576 return previousName;
577 } else {
578 return null;
579 }
580 } finally {
581 cursor.close();
582 }
583 } else {
584 return previousNameRef.get();
585 }
586 }
587 }
588
589 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700590 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800591 if (Log.isLoggable(TAG, Log.VERBOSE)) {
592 Log.v(TAG, "getUserData: " + account
593 + ", key " + key
594 + ", caller's uid " + Binder.getCallingUid()
595 + ", pid " + Binder.getCallingPid());
596 }
Fred Quintana382601f2010-03-25 12:25:10 -0700597 if (account == null) throw new IllegalArgumentException("account is null");
598 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700599 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800600 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700601 long identityToken = clearCallingIdentity();
602 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800603 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700604 } finally {
605 restoreCallingIdentity(identityToken);
606 }
607 }
608
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800609 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100610 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800611 if (Log.isLoggable(TAG, Log.VERBOSE)) {
612 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100613 + "for user id " + userId
Fred Quintana56285a62010-12-02 14:20:51 -0800614 + "caller's uid " + Binder.getCallingUid()
615 + ", pid " + Binder.getCallingPid());
616 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100617 // Only allow the system process to read accounts of other users
618 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
619 + " trying get authenticator types for " + userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700620 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700621 try {
Fred Quintana97889762009-06-15 12:29:24 -0700622 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700623 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700624 AuthenticatorDescription[] types =
625 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700626 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700627 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700628 : authenticatorCollection) {
629 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700630 i++;
631 }
632 return types;
633 } finally {
634 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700635 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700636 }
637
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100638 private void enforceCrossUserPermission(int userId, String errorMessage) {
639 if (userId != UserHandle.getCallingUserId()
640 && Binder.getCallingUid() != Process.myUid()
641 && mContext.checkCallingOrSelfPermission(
642 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
643 != PackageManager.PERMISSION_GRANTED) {
644 throw new SecurityException(errorMessage);
645 }
646 }
647
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700648 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700649 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800650 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700651 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800652 + ", caller's uid " + Binder.getCallingUid()
653 + ", pid " + Binder.getCallingPid());
654 }
Fred Quintana382601f2010-03-25 12:25:10 -0700655 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700656 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700657 /*
658 * Child users are not allowed to add accounts. Only the accounts that are
659 * shared by the parent profile can be added to child profile.
660 *
661 * TODO: Only allow accounts that were shared to be added by
662 * a limited user.
663 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700664
Amith Yamasani04e0d262012-02-14 11:50:53 -0800665 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700666 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700667 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700668 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800669 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700670 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700671 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700672 }
673 }
674
Amith Yamasani67df64b2012-12-14 12:09:36 -0800675 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
676 final UserAccounts fromAccounts = getUserAccounts(userFrom);
677 final UserAccounts toAccounts = getUserAccounts(userTo);
678 if (fromAccounts == null || toAccounts == null) {
679 return false;
680 }
681
682 long identityToken = clearCallingIdentity();
683 try {
684 new Session(fromAccounts, null, account.type, false,
685 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700686 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800687 protected String toDebugString(long now) {
688 return super.toDebugString(now) + ", getAccountCredentialsForClone"
689 + ", " + account.type;
690 }
691
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700692 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800693 public void run() throws RemoteException {
694 mAuthenticator.getAccountCredentialsForCloning(this, account);
695 }
696
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700697 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800698 public void onResult(Bundle result) {
699 if (result != null) {
700 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
701 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800702 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800703 }
704 return;
705 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800706 super.onResult(result);
707 }
708 }
709 }.bind();
710 } finally {
711 restoreCallingIdentity(identityToken);
712 }
713 return true;
714 }
715
Amith Yamasani67df64b2012-12-14 12:09:36 -0800716 void completeCloningAccount(final Bundle result, final Account account,
717 final UserAccounts targetUser) {
718 long id = clearCallingIdentity();
719 try {
720 new Session(targetUser, null, account.type, false,
721 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700722 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800723 protected String toDebugString(long now) {
724 return super.toDebugString(now) + ", getAccountCredentialsForClone"
725 + ", " + account.type;
726 }
727
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700728 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800729 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700730 // Confirm that the owner's account still exists before this step.
731 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
732 synchronized (owner.cacheLock) {
733 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
734 for (Account acc : ownerAccounts) {
735 if (acc.equals(account)) {
736 mAuthenticator.addAccountFromCredentials(this, account, result);
737 break;
738 }
739 }
740 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800741 }
742
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700743 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800744 public void onResult(Bundle result) {
745 if (result != null) {
746 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
747 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800748 } else {
749 // TODO: Show error notification
750 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800751 }
752 return;
753 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800754 super.onResult(result);
755 }
756 }
757
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700758 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800759 public void onError(int errorCode, String errorMessage) {
760 super.onError(errorCode, errorMessage);
761 // TODO: Show error notification to user
762 // TODO: Should we remove the shadow account so that it doesn't keep trying?
763 }
764
765 }.bind();
766 } finally {
767 restoreCallingIdentity(id);
768 }
769 }
770
Amith Yamasani04e0d262012-02-14 11:50:53 -0800771 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800772 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700773 if (account == null) {
774 return false;
775 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800776 synchronized (accounts.cacheLock) {
777 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800778 db.beginTransaction();
779 try {
780 long numMatches = DatabaseUtils.longForQuery(db,
781 "select count(*) from " + TABLE_ACCOUNTS
782 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
783 new String[]{account.name, account.type});
784 if (numMatches > 0) {
785 Log.w(TAG, "insertAccountIntoDatabase: " + account
786 + ", skipping since the account already exists");
787 return false;
788 }
789 ContentValues values = new ContentValues();
790 values.put(ACCOUNTS_NAME, account.name);
791 values.put(ACCOUNTS_TYPE, account.type);
792 values.put(ACCOUNTS_PASSWORD, password);
793 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
794 if (accountId < 0) {
795 Log.w(TAG, "insertAccountIntoDatabase: " + account
796 + ", skipping the DB insert failed");
797 return false;
798 }
799 if (extras != null) {
800 for (String key : extras.keySet()) {
801 final String value = extras.getString(key);
802 if (insertExtraLocked(db, accountId, key, value) < 0) {
803 Log.w(TAG, "insertAccountIntoDatabase: " + account
804 + ", skipping since insertExtra failed for key " + key);
805 return false;
806 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700807 }
808 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800809 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800810 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800811 } finally {
812 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700813 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800814 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700815 }
816 if (accounts.userId == UserHandle.USER_OWNER) {
817 addAccountToLimitedUsers(account);
818 }
819 return true;
820 }
821
822 /**
823 * Adds the account to all limited users as shared accounts. If the user is currently
824 * running, then clone the account too.
825 * @param account the account to share with limited users
826 */
827 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700828 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700829 for (UserInfo user : users) {
830 if (user.isRestricted()) {
831 addSharedAccountAsUser(account, user.id);
832 try {
833 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
834 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
835 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
836 account));
837 }
838 } catch (RemoteException re) {
839 // Shouldn't happen
840 }
841 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700842 }
843 }
844
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800845 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700846 ContentValues values = new ContentValues();
847 values.put(EXTRAS_KEY, key);
848 values.put(EXTRAS_ACCOUNTS_ID, accountId);
849 values.put(EXTRAS_VALUE, value);
850 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
851 }
852
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800853 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -0800854 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800855 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800856 if (Log.isLoggable(TAG, Log.VERBOSE)) {
857 Log.v(TAG, "hasFeatures: " + account
858 + ", response " + response
859 + ", features " + stringArrayToString(features)
860 + ", caller's uid " + Binder.getCallingUid()
861 + ", pid " + Binder.getCallingPid());
862 }
Fred Quintana382601f2010-03-25 12:25:10 -0700863 if (response == null) throw new IllegalArgumentException("response is null");
864 if (account == null) throw new IllegalArgumentException("account is null");
865 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800866 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800867 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800868 long identityToken = clearCallingIdentity();
869 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800870 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800871 } finally {
872 restoreCallingIdentity(identityToken);
873 }
874 }
875
876 private class TestFeaturesSession extends Session {
877 private final String[] mFeatures;
878 private final Account mAccount;
879
Amith Yamasani04e0d262012-02-14 11:50:53 -0800880 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800881 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800882 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800883 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800884 mFeatures = features;
885 mAccount = account;
886 }
887
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700888 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800889 public void run() throws RemoteException {
890 try {
891 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
892 } catch (RemoteException e) {
893 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
894 }
895 }
896
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700897 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800898 public void onResult(Bundle result) {
899 IAccountManagerResponse response = getResponseAndClose();
900 if (response != null) {
901 try {
902 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700903 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800904 return;
905 }
Fred Quintana56285a62010-12-02 14:20:51 -0800906 if (Log.isLoggable(TAG, Log.VERBOSE)) {
907 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
908 + response);
909 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800910 final Bundle newResult = new Bundle();
911 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
912 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
913 response.onResult(newResult);
914 } catch (RemoteException e) {
915 // if the caller is dead then there is no one to care about remote exceptions
916 if (Log.isLoggable(TAG, Log.VERBOSE)) {
917 Log.v(TAG, "failure while notifying response", e);
918 }
919 }
920 }
921 }
922
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700923 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800924 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800925 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800926 + ", " + mAccount
927 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
928 }
929 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800930
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800931 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700932 public void renameAccount(
933 IAccountManagerResponse response, Account accountToRename, String newName) {
934 if (Log.isLoggable(TAG, Log.VERBOSE)) {
935 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
936 + ", caller's uid " + Binder.getCallingUid()
937 + ", pid " + Binder.getCallingPid());
938 }
939 if (accountToRename == null) throw new IllegalArgumentException("account is null");
940 checkAuthenticateAccountsPermission(accountToRename);
941 UserAccounts accounts = getUserAccountsForCaller();
942 long identityToken = clearCallingIdentity();
943 try {
944 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
945 Bundle result = new Bundle();
946 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
947 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
948 try {
949 response.onResult(result);
950 } catch (RemoteException e) {
951 Log.w(TAG, e.getMessage());
952 }
953 } finally {
954 restoreCallingIdentity(identityToken);
955 }
956 }
957
958 private Account renameAccountInternal(
959 UserAccounts accounts, Account accountToRename, String newName) {
960 Account resultAccount = null;
961 /*
962 * Cancel existing notifications. Let authenticators
963 * re-post notifications as required. But we don't know if
964 * the authenticators have bound their notifications to
965 * now stale account name data.
966 *
967 * With a rename api, we might not need to do this anymore but it
968 * shouldn't hurt.
969 */
970 cancelNotification(
971 getSigninRequiredNotificationId(accounts, accountToRename),
972 new UserHandle(accounts.userId));
973 synchronized(accounts.credentialsPermissionNotificationIds) {
974 for (Pair<Pair<Account, String>, Integer> pair:
975 accounts.credentialsPermissionNotificationIds.keySet()) {
976 if (accountToRename.equals(pair.first.first)) {
977 int id = accounts.credentialsPermissionNotificationIds.get(pair);
978 cancelNotification(id, new UserHandle(accounts.userId));
979 }
980 }
981 }
982 synchronized (accounts.cacheLock) {
983 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
984 db.beginTransaction();
985 boolean isSuccessful = false;
986 Account renamedAccount = new Account(newName, accountToRename.type);
987 try {
988 final ContentValues values = new ContentValues();
989 values.put(ACCOUNTS_NAME, newName);
990 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
991 final long accountId = getAccountIdLocked(db, accountToRename);
992 if (accountId >= 0) {
993 final String[] argsAccountId = { String.valueOf(accountId) };
994 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
995 db.setTransactionSuccessful();
996 isSuccessful = true;
997 }
998 } finally {
999 db.endTransaction();
1000 if (isSuccessful) {
1001 /*
1002 * Database transaction was successful. Clean up cached
1003 * data associated with the account in the user profile.
1004 */
1005 insertAccountIntoCacheLocked(accounts, renamedAccount);
1006 /*
1007 * Extract the data and token caches before removing the
1008 * old account to preserve the user data associated with
1009 * the account.
1010 */
1011 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1012 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1013 removeAccountFromCacheLocked(accounts, accountToRename);
1014 /*
1015 * Update the cached data associated with the renamed
1016 * account.
1017 */
1018 accounts.userDataCache.put(renamedAccount, tmpData);
1019 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1020 accounts.previousNameCache.put(
1021 renamedAccount,
1022 new AtomicReference<String>(accountToRename.name));
1023 resultAccount = renamedAccount;
1024
1025 if (accounts.userId == UserHandle.USER_OWNER) {
1026 /*
1027 * Owner's account was renamed, rename the account for
1028 * those users with which the account was shared.
1029 */
1030 List<UserInfo> users = mUserManager.getUsers(true);
1031 for (UserInfo user : users) {
1032 if (!user.isPrimary() && user.isRestricted()) {
1033 renameSharedAccountAsUser(accountToRename, newName, user.id);
1034 }
1035 }
1036 }
1037 sendAccountsChangedBroadcast(accounts.userId);
1038 }
1039 }
1040 }
1041 return resultAccount;
1042 }
1043
1044 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001045 public void removeAccount(IAccountManagerResponse response, Account account,
1046 boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001047 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1048 Log.v(TAG, "removeAccount: " + account
1049 + ", response " + response
1050 + ", caller's uid " + Binder.getCallingUid()
1051 + ", pid " + Binder.getCallingPid());
1052 }
Fred Quintana382601f2010-03-25 12:25:10 -07001053 if (response == null) throw new IllegalArgumentException("response is null");
1054 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001055 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001056 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001057 UserAccounts accounts = getUserAccountsForCaller();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001058 int userId = Binder.getCallingUserHandle().getIdentifier();
1059 if (!canUserModifyAccounts(userId)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001060 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001061 // TODO: This should be ERROR_CODE_USER_RESTRICTED instead. See http://b/16322768
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001062 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
1063 "User cannot modify accounts");
1064 } catch (RemoteException re) {
1065 }
Amith Yamasani5934dbc2014-02-20 15:23:36 -08001066 return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001067 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001068 if (!canUserModifyAccountsForType(userId, account.type)) {
1069 try {
1070 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1071 "User cannot modify accounts of this type (policy).");
1072 } catch (RemoteException re) {
1073 }
1074 return;
1075 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001076
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001077 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001078
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001079 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001080 synchronized (accounts.credentialsPermissionNotificationIds) {
1081 for (Pair<Pair<Account, String>, Integer> pair:
1082 accounts.credentialsPermissionNotificationIds.keySet()) {
1083 if (account.equals(pair.first.first)) {
1084 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1085 cancelNotification(id, user);
1086 }
1087 }
1088 }
1089
1090 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001091 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001092 } finally {
1093 restoreCallingIdentity(identityToken);
1094 }
1095 }
1096
1097 @Override
1098 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001099 boolean expectActivityLaunch, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001100 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1101 Log.v(TAG, "removeAccount: " + account
1102 + ", response " + response
1103 + ", caller's uid " + Binder.getCallingUid()
1104 + ", pid " + Binder.getCallingPid()
1105 + ", for user id " + userId);
1106 }
1107 if (response == null) throw new IllegalArgumentException("response is null");
1108 if (account == null) throw new IllegalArgumentException("account is null");
1109
1110 // Only allow the system process to modify accounts of other users
1111 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1112 + " trying to remove account for " + userId);
1113 checkManageAccountsPermission();
1114
1115 UserAccounts accounts = getUserAccounts(userId);
1116 if (!canUserModifyAccounts(userId)) {
1117 try {
1118 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1119 "User cannot modify accounts");
1120 } catch (RemoteException re) {
1121 }
1122 return;
1123 }
1124 if (!canUserModifyAccountsForType(userId, account.type)) {
1125 try {
1126 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1127 "User cannot modify accounts of this type (policy).");
1128 } catch (RemoteException re) {
1129 }
1130 return;
1131 }
1132
1133 UserHandle user = new UserHandle(userId);
1134 long identityToken = clearCallingIdentity();
1135
1136 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001137 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001138 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001139 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001140 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001141 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001142 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001143 }
1144 }
1145 }
1146
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001147 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001148 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1149 } finally {
1150 restoreCallingIdentity(identityToken);
1151 }
1152 }
1153
1154 @Override
1155 public boolean removeAccountExplicitly(Account account) {
1156 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1157 Log.v(TAG, "removeAccountExplicitly: " + account
1158 + ", caller's uid " + Binder.getCallingUid()
1159 + ", pid " + Binder.getCallingPid());
1160 }
1161 if (account == null) throw new IllegalArgumentException("account is null");
1162 checkAuthenticateAccountsPermission(account);
1163
1164 UserAccounts accounts = getUserAccountsForCaller();
1165 int userId = Binder.getCallingUserHandle().getIdentifier();
1166 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
1167 return false;
1168 }
1169 long identityToken = clearCallingIdentity();
1170 try {
1171 return removeAccountInternal(accounts, account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001172 } finally {
1173 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001174 }
Fred Quintana60307342009-03-24 22:48:12 -07001175 }
1176
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001177 private class RemoveAccountSession extends Session {
1178 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001179 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001180 Account account, boolean expectActivityLaunch) {
1181 super(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001182 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001183 mAccount = account;
1184 }
1185
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001186 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001187 protected String toDebugString(long now) {
1188 return super.toDebugString(now) + ", removeAccount"
1189 + ", account " + mAccount;
1190 }
1191
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001192 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001193 public void run() throws RemoteException {
1194 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1195 }
1196
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001197 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001198 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001199 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1200 && !result.containsKey(AccountManager.KEY_INTENT)) {
1201 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001202 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001203 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001204 }
1205 IAccountManagerResponse response = getResponseAndClose();
1206 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001207 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1208 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1209 + response);
1210 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001211 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001212 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001213 try {
1214 response.onResult(result2);
1215 } catch (RemoteException e) {
1216 // ignore
1217 }
1218 }
1219 }
1220 super.onResult(result);
1221 }
1222 }
1223
Amith Yamasani04e0d262012-02-14 11:50:53 -08001224 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001225 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001226 removeAccountInternal(getUserAccountsForCaller(), account);
1227 }
1228
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001229 private boolean removeAccountInternal(UserAccounts accounts, Account account) {
1230 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001231 synchronized (accounts.cacheLock) {
1232 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001233 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1234 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001235 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001236 removeAccountFromCacheLocked(accounts, account);
1237 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001238 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001239 if (accounts.userId == UserHandle.USER_OWNER) {
1240 // Owner's account was removed, remove from any users that are sharing
1241 // this account.
1242 long id = Binder.clearCallingIdentity();
1243 try {
1244 List<UserInfo> users = mUserManager.getUsers(true);
1245 for (UserInfo user : users) {
1246 if (!user.isPrimary() && user.isRestricted()) {
1247 removeSharedAccountAsUser(account, user.id);
1248 }
1249 }
1250 } finally {
1251 Binder.restoreCallingIdentity(id);
1252 }
1253 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001254 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001255 }
1256
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001257 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001258 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001259 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1260 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
1261 + ", caller's uid " + Binder.getCallingUid()
1262 + ", pid " + Binder.getCallingPid());
1263 }
Fred Quintana382601f2010-03-25 12:25:10 -07001264 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1265 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -08001266 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001267 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001268 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001269 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001270 synchronized (accounts.cacheLock) {
1271 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001272 db.beginTransaction();
1273 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001274 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001275 db.setTransactionSuccessful();
1276 } finally {
1277 db.endTransaction();
1278 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001279 }
Fred Quintana60307342009-03-24 22:48:12 -07001280 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001281 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001282 }
1283 }
1284
Amith Yamasani04e0d262012-02-14 11:50:53 -08001285 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1286 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001287 if (authToken == null || accountType == null) {
1288 return;
1289 }
Fred Quintana33269202009-04-20 16:05:10 -07001290 Cursor cursor = db.rawQuery(
1291 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1292 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1293 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1294 + " FROM " + TABLE_ACCOUNTS
1295 + " JOIN " + TABLE_AUTHTOKENS
1296 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1297 + " = " + AUTHTOKENS_ACCOUNTS_ID
1298 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1299 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1300 new String[]{authToken, accountType});
1301 try {
1302 while (cursor.moveToNext()) {
1303 long authTokenId = cursor.getLong(0);
1304 String accountName = cursor.getString(1);
1305 String authTokenType = cursor.getString(2);
1306 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001307 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001308 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -07001309 }
Fred Quintana33269202009-04-20 16:05:10 -07001310 } finally {
1311 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001312 }
1313 }
1314
Amith Yamasani04e0d262012-02-14 11:50:53 -08001315 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1316 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001317 if (account == null || type == null) {
1318 return false;
1319 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001320 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1321 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001322 synchronized (accounts.cacheLock) {
1323 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001324 db.beginTransaction();
1325 try {
1326 long accountId = getAccountIdLocked(db, account);
1327 if (accountId < 0) {
1328 return false;
1329 }
1330 db.delete(TABLE_AUTHTOKENS,
1331 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1332 new String[]{type});
1333 ContentValues values = new ContentValues();
1334 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1335 values.put(AUTHTOKENS_TYPE, type);
1336 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1337 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1338 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001339 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001340 return true;
1341 }
Fred Quintana33269202009-04-20 16:05:10 -07001342 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001343 } finally {
1344 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001345 }
Fred Quintana60307342009-03-24 22:48:12 -07001346 }
1347 }
1348
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001349 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001350 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001351 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1352 Log.v(TAG, "peekAuthToken: " + account
1353 + ", authTokenType " + authTokenType
1354 + ", caller's uid " + Binder.getCallingUid()
1355 + ", pid " + Binder.getCallingPid());
1356 }
Fred Quintana382601f2010-03-25 12:25:10 -07001357 if (account == null) throw new IllegalArgumentException("account is null");
1358 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001359 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001360 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001361 long identityToken = clearCallingIdentity();
1362 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001363 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001364 } finally {
1365 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001366 }
Fred Quintana60307342009-03-24 22:48:12 -07001367 }
1368
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001369 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001370 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001371 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1372 Log.v(TAG, "setAuthToken: " + account
1373 + ", authTokenType " + authTokenType
1374 + ", caller's uid " + Binder.getCallingUid()
1375 + ", pid " + Binder.getCallingPid());
1376 }
Fred Quintana382601f2010-03-25 12:25:10 -07001377 if (account == null) throw new IllegalArgumentException("account is null");
1378 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001379 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001380 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001381 long identityToken = clearCallingIdentity();
1382 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001383 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001384 } finally {
1385 restoreCallingIdentity(identityToken);
1386 }
Fred Quintana60307342009-03-24 22:48:12 -07001387 }
1388
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001389 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001390 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001391 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1392 Log.v(TAG, "setAuthToken: " + account
1393 + ", caller's uid " + Binder.getCallingUid()
1394 + ", pid " + Binder.getCallingPid());
1395 }
Fred Quintana382601f2010-03-25 12:25:10 -07001396 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001397 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001398 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001399 long identityToken = clearCallingIdentity();
1400 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001401 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001402 } finally {
1403 restoreCallingIdentity(identityToken);
1404 }
Fred Quintana60307342009-03-24 22:48:12 -07001405 }
1406
Amith Yamasani04e0d262012-02-14 11:50:53 -08001407 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001408 if (account == null) {
1409 return;
1410 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001411 synchronized (accounts.cacheLock) {
1412 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001413 db.beginTransaction();
1414 try {
1415 final ContentValues values = new ContentValues();
1416 values.put(ACCOUNTS_PASSWORD, password);
1417 final long accountId = getAccountIdLocked(db, account);
1418 if (accountId >= 0) {
1419 final String[] argsAccountId = {String.valueOf(accountId)};
1420 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1421 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001422 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001423 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001424 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001425 } finally {
1426 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001427 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001428 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001429 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001430 }
1431
Amith Yamasani04e0d262012-02-14 11:50:53 -08001432 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001433 Log.i(TAG, "the accounts changed, sending broadcast of "
1434 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001435 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001436 }
1437
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001438 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001439 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001440 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1441 Log.v(TAG, "clearPassword: " + account
1442 + ", caller's uid " + Binder.getCallingUid()
1443 + ", pid " + Binder.getCallingPid());
1444 }
Fred Quintana382601f2010-03-25 12:25:10 -07001445 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001446 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001447 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001448 long identityToken = clearCallingIdentity();
1449 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001450 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001451 } finally {
1452 restoreCallingIdentity(identityToken);
1453 }
Fred Quintana60307342009-03-24 22:48:12 -07001454 }
1455
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001456 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001457 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001458 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1459 Log.v(TAG, "setUserData: " + account
1460 + ", key " + key
1461 + ", caller's uid " + Binder.getCallingUid()
1462 + ", pid " + Binder.getCallingPid());
1463 }
Fred Quintana382601f2010-03-25 12:25:10 -07001464 if (key == null) throw new IllegalArgumentException("key is null");
1465 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001466 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001467 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001468 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001469 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001470 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001471 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001472 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001473 }
1474 }
1475
Amith Yamasani04e0d262012-02-14 11:50:53 -08001476 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1477 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001478 if (account == null || key == null) {
1479 return;
1480 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001481 synchronized (accounts.cacheLock) {
1482 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001483 db.beginTransaction();
1484 try {
1485 long accountId = getAccountIdLocked(db, account);
1486 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001487 return;
1488 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001489 long extrasId = getExtrasIdLocked(db, accountId, key);
1490 if (extrasId < 0 ) {
1491 extrasId = insertExtraLocked(db, accountId, key, value);
1492 if (extrasId < 0) {
1493 return;
1494 }
1495 } else {
1496 ContentValues values = new ContentValues();
1497 values.put(EXTRAS_VALUE, value);
1498 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1499 return;
1500 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001501
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001502 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001503 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001504 db.setTransactionSuccessful();
1505 } finally {
1506 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001507 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001508 }
1509 }
1510
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001511 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001512 if (result == null) {
1513 Log.e(TAG, "the result is unexpectedly null", new Exception());
1514 }
1515 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1516 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1517 + response);
1518 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001519 try {
1520 response.onResult(result);
1521 } catch (RemoteException e) {
1522 // if the caller is dead then there is no one to care about remote
1523 // exceptions
1524 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1525 Log.v(TAG, "failure while notifying response", e);
1526 }
1527 }
1528 }
1529
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001530 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001531 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1532 final String authTokenType)
1533 throws RemoteException {
1534 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001535 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1536
Fred Quintanad9640ec2012-05-23 12:37:00 -07001537 final int callingUid = getCallingUid();
1538 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001539 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001540 throw new SecurityException("can only call from system");
1541 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001542 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001543 long identityToken = clearCallingIdentity();
1544 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001545 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001546 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001547 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001548 protected String toDebugString(long now) {
1549 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001550 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001551 + ", authTokenType " + authTokenType;
1552 }
1553
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001554 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001555 public void run() throws RemoteException {
1556 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1557 }
1558
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001559 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001560 public void onResult(Bundle result) {
1561 if (result != null) {
1562 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1563 Bundle bundle = new Bundle();
1564 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1565 super.onResult(bundle);
1566 return;
1567 } else {
1568 super.onResult(result);
1569 }
1570 }
1571 }.bind();
1572 } finally {
1573 restoreCallingIdentity(identityToken);
1574 }
1575 }
1576
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001577 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001578 public void getAuthToken(IAccountManagerResponse response, final Account account,
1579 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001580 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001581 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1582 Log.v(TAG, "getAuthToken: " + account
1583 + ", response " + response
1584 + ", authTokenType " + authTokenType
1585 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1586 + ", expectActivityLaunch " + expectActivityLaunch
1587 + ", caller's uid " + Binder.getCallingUid()
1588 + ", pid " + Binder.getCallingPid());
1589 }
Fred Quintana382601f2010-03-25 12:25:10 -07001590 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001591 try {
1592 if (account == null) {
1593 Slog.w(TAG, "getAuthToken called with null account");
1594 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1595 return;
1596 }
1597 if (authTokenType == null) {
1598 Slog.w(TAG, "getAuthToken called with null authTokenType");
1599 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1600 return;
1601 }
1602 } catch (RemoteException e) {
1603 Slog.w(TAG, "Failed to report error back to the client." + e);
1604 return;
1605 }
1606
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001607 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001608 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001609 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1610 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1611 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001612 final boolean customTokens =
1613 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1614
1615 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001616 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001617 final boolean permissionGranted = customTokens ||
1618 permissionIsGranted(account, authTokenType, callerUid);
1619
Costin Manolachec6684f92011-01-14 11:25:39 -08001620 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1621 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001622 // let authenticator know the identity of the caller
1623 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1624 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1625 if (notifyOnAuthFailure) {
1626 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001627 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001628
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001629 long identityToken = clearCallingIdentity();
1630 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001631 // if the caller has permission, do the peek. otherwise go the more expensive
1632 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001633 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001634 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001635 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001636 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001637 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1638 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1639 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001640 onResult(response, result);
1641 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001642 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001643 }
1644
Amith Yamasani04e0d262012-02-14 11:50:53 -08001645 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001646 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001647 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001648 protected String toDebugString(long now) {
1649 if (loginOptions != null) loginOptions.keySet();
1650 return super.toDebugString(now) + ", getAuthToken"
1651 + ", " + account
1652 + ", authTokenType " + authTokenType
1653 + ", loginOptions " + loginOptions
1654 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1655 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001656
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001657 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001658 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001659 // If the caller doesn't have permission then create and return the
1660 // "grant permission" intent instead of the "getAuthToken" intent.
1661 if (!permissionGranted) {
1662 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1663 } else {
1664 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1665 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001666 }
1667
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001668 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001669 public void onResult(Bundle result) {
1670 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001671 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001672 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1673 new AccountAuthenticatorResponse(this),
1674 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001675 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001676 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001677 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001678 onResult(bundle);
1679 return;
1680 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001681 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001682 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001683 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1684 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001685 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001686 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001687 "the type and name should not be empty");
1688 return;
1689 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001690 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001691 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001692 authTokenType, authToken);
1693 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001694 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001695
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001696 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001697 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001698 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001699 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001700 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001701 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001702 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001703 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001704 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001705 }.bind();
1706 } finally {
1707 restoreCallingIdentity(identityToken);
1708 }
Fred Quintana60307342009-03-24 22:48:12 -07001709 }
1710
Dianne Hackborn41203752012-08-31 14:05:51 -07001711 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1712 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001713 int uid = intent.getIntExtra(
1714 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1715 String authTokenType = intent.getStringExtra(
1716 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1717 String authTokenLabel = intent.getStringExtra(
1718 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1719
1720 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1721 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001722 final String titleAndSubtitle =
1723 mContext.getString(R.string.permission_request_notification_with_subtitle,
1724 account.name);
1725 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001726 String title = titleAndSubtitle;
1727 String subtitle = "";
1728 if (index > 0) {
1729 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001730 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001731 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001732 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01001733 Context contextForUser = getContextForUser(user);
1734 n.color = contextForUser.getResources().getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001735 com.android.internal.R.color.system_notification_accent_color);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01001736 n.setLatestEventInfo(contextForUser, title, subtitle,
Dianne Hackborn41203752012-08-31 14:05:51 -07001737 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001738 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1739 installNotification(getCredentialPermissionNotificationId(
1740 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001741 }
1742
Costin Manolache5f383ad92010-12-02 16:44:46 -08001743 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1744 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001745
1746 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001747 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001748 // Since it was set in Eclair+ we can't change it without breaking apps using
1749 // the intent from a non-Activity context.
1750 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001751 intent.addCategory(
1752 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001753
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001754 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001755 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1756 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001757 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001758
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001759 return intent;
1760 }
1761
1762 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1763 int uid) {
1764 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001765 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001766 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001767 final Pair<Pair<Account, String>, Integer> key =
1768 new Pair<Pair<Account, String>, Integer>(
1769 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001770 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001771 if (id == null) {
1772 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001773 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001774 }
1775 }
1776 return id;
1777 }
1778
Amith Yamasani04e0d262012-02-14 11:50:53 -08001779 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001780 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001781 synchronized (accounts.signinRequiredNotificationIds) {
1782 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001783 if (id == null) {
1784 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001785 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001786 }
1787 }
1788 return id;
1789 }
1790
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001791 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001792 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001793 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001794 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001795 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1796 Log.v(TAG, "addAccount: accountType " + accountType
1797 + ", response " + response
1798 + ", authTokenType " + authTokenType
1799 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1800 + ", expectActivityLaunch " + expectActivityLaunch
1801 + ", caller's uid " + Binder.getCallingUid()
1802 + ", pid " + Binder.getCallingPid());
1803 }
Fred Quintana382601f2010-03-25 12:25:10 -07001804 if (response == null) throw new IllegalArgumentException("response is null");
1805 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001806 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001807
Amith Yamasani71e6c692013-03-24 17:39:28 -07001808 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001809 int userId = Binder.getCallingUserHandle().getIdentifier();
1810 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001811 try {
1812 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1813 "User is not allowed to add an account!");
1814 } catch (RemoteException re) {
1815 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07001816 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001817 return;
1818 }
1819 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07001820 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001821 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1822 "User cannot modify accounts of this type (policy).");
1823 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07001824 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07001825 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1826 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001827 return;
1828 }
1829
Amith Yamasani04e0d262012-02-14 11:50:53 -08001830 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001831 final int pid = Binder.getCallingPid();
1832 final int uid = Binder.getCallingUid();
1833 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1834 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1835 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1836
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001837 long identityToken = clearCallingIdentity();
1838 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001839 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001840 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001841 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001842 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001843 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001844 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001845 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001846
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001847 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001848 protected String toDebugString(long now) {
1849 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001850 + ", accountType " + accountType
1851 + ", requiredFeatures "
1852 + (requiredFeatures != null
1853 ? TextUtils.join(",", requiredFeatures)
1854 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001855 }
1856 }.bind();
1857 } finally {
1858 restoreCallingIdentity(identityToken);
1859 }
Fred Quintana60307342009-03-24 22:48:12 -07001860 }
1861
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001862 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001863 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
1864 final String authTokenType, final String[] requiredFeatures,
1865 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
1866 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1867 Log.v(TAG, "addAccount: accountType " + accountType
1868 + ", response " + response
1869 + ", authTokenType " + authTokenType
1870 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1871 + ", expectActivityLaunch " + expectActivityLaunch
1872 + ", caller's uid " + Binder.getCallingUid()
1873 + ", pid " + Binder.getCallingPid()
1874 + ", for user id " + userId);
1875 }
1876 if (response == null) throw new IllegalArgumentException("response is null");
1877 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1878 checkManageAccountsPermission();
1879
1880 // Only allow the system process to add accounts of other users
1881 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1882 + " trying to add account for " + userId);
1883
1884 // Is user disallowed from modifying accounts?
1885 if (!canUserModifyAccounts(userId)) {
1886 try {
1887 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1888 "User is not allowed to add an account!");
1889 } catch (RemoteException re) {
1890 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07001891 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001892 return;
1893 }
1894 if (!canUserModifyAccountsForType(userId, accountType)) {
1895 try {
1896 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1897 "User cannot modify accounts of this type (policy).");
1898 } catch (RemoteException re) {
1899 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07001900 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1901 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001902 return;
1903 }
1904
1905 UserAccounts accounts = getUserAccounts(userId);
1906 final int pid = Binder.getCallingPid();
1907 final int uid = Binder.getCallingUid();
1908 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1909 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1910 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1911
1912 long identityToken = clearCallingIdentity();
1913 try {
1914 new Session(accounts, response, accountType, expectActivityLaunch,
1915 true /* stripAuthTokenFromResult */) {
1916 @Override
1917 public void run() throws RemoteException {
1918 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
1919 options);
1920 }
1921
1922 @Override
1923 protected String toDebugString(long now) {
1924 return super.toDebugString(now) + ", addAccount"
1925 + ", accountType " + accountType
1926 + ", requiredFeatures "
1927 + (requiredFeatures != null
1928 ? TextUtils.join(",", requiredFeatures)
1929 : null);
1930 }
1931 }.bind();
1932 } finally {
1933 restoreCallingIdentity(identityToken);
1934 }
1935 }
1936
Amith Yamasaniae7034a2014-09-22 12:42:12 -07001937 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001938 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1939 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
1940 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1941 long identityToken = clearCallingIdentity();
1942 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07001943 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001944 } finally {
1945 restoreCallingIdentity(identityToken);
1946 }
1947 }
1948
1949 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001950 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1951 final Account account, final Bundle options, final boolean expectActivityLaunch,
1952 int userId) {
1953 // Only allow the system process to read accounts of other users
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001954 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001955 + " trying to confirm account credentials for " + userId);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001956
Fred Quintana56285a62010-12-02 14:20:51 -08001957 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1958 Log.v(TAG, "confirmCredentials: " + account
1959 + ", response " + response
1960 + ", expectActivityLaunch " + expectActivityLaunch
1961 + ", caller's uid " + Binder.getCallingUid()
1962 + ", pid " + Binder.getCallingPid());
1963 }
Fred Quintana382601f2010-03-25 12:25:10 -07001964 if (response == null) throw new IllegalArgumentException("response is null");
1965 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001966 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001967 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001968 long identityToken = clearCallingIdentity();
1969 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001970 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001971 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001972 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001973 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001974 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001975 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001976 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001977 protected String toDebugString(long now) {
1978 return super.toDebugString(now) + ", confirmCredentials"
1979 + ", " + account;
1980 }
1981 }.bind();
1982 } finally {
1983 restoreCallingIdentity(identityToken);
1984 }
Fred Quintana60307342009-03-24 22:48:12 -07001985 }
1986
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001987 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001988 public void updateCredentials(IAccountManagerResponse response, final Account account,
1989 final String authTokenType, final boolean expectActivityLaunch,
1990 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001991 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1992 Log.v(TAG, "updateCredentials: " + account
1993 + ", response " + response
1994 + ", authTokenType " + authTokenType
1995 + ", expectActivityLaunch " + expectActivityLaunch
1996 + ", caller's uid " + Binder.getCallingUid()
1997 + ", pid " + Binder.getCallingPid());
1998 }
Fred Quintana382601f2010-03-25 12:25:10 -07001999 if (response == null) throw new IllegalArgumentException("response is null");
2000 if (account == null) throw new IllegalArgumentException("account is null");
2001 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002002 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002003 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002004 long identityToken = clearCallingIdentity();
2005 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002006 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08002007 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002008 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002009 public void run() throws RemoteException {
2010 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2011 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002012 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002013 protected String toDebugString(long now) {
2014 if (loginOptions != null) loginOptions.keySet();
2015 return super.toDebugString(now) + ", updateCredentials"
2016 + ", " + account
2017 + ", authTokenType " + authTokenType
2018 + ", loginOptions " + loginOptions;
2019 }
2020 }.bind();
2021 } finally {
2022 restoreCallingIdentity(identityToken);
2023 }
Fred Quintana60307342009-03-24 22:48:12 -07002024 }
2025
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002026 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002027 public void editProperties(IAccountManagerResponse response, final String accountType,
2028 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08002029 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2030 Log.v(TAG, "editProperties: accountType " + accountType
2031 + ", response " + response
2032 + ", expectActivityLaunch " + expectActivityLaunch
2033 + ", caller's uid " + Binder.getCallingUid()
2034 + ", pid " + Binder.getCallingPid());
2035 }
Fred Quintana382601f2010-03-25 12:25:10 -07002036 if (response == null) throw new IllegalArgumentException("response is null");
2037 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002038 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002039 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002040 long identityToken = clearCallingIdentity();
2041 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002042 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08002043 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002044 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002045 public void run() throws RemoteException {
2046 mAuthenticator.editProperties(this, mAccountType);
2047 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002048 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002049 protected String toDebugString(long now) {
2050 return super.toDebugString(now) + ", editProperties"
2051 + ", accountType " + accountType;
2052 }
2053 }.bind();
2054 } finally {
2055 restoreCallingIdentity(identityToken);
2056 }
Fred Quintana60307342009-03-24 22:48:12 -07002057 }
2058
Fred Quintana33269202009-04-20 16:05:10 -07002059 private class GetAccountsByTypeAndFeatureSession extends Session {
2060 private final String[] mFeatures;
2061 private volatile Account[] mAccountsOfType = null;
2062 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2063 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002064 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002065
Amith Yamasani04e0d262012-02-14 11:50:53 -08002066 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002067 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002068 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08002069 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002070 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002071 mFeatures = features;
2072 }
2073
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002074 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002075 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002076 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002077 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2078 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002079 }
Fred Quintana33269202009-04-20 16:05:10 -07002080 // check whether each account matches the requested features
2081 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2082 mCurrentAccount = 0;
2083
2084 checkAccount();
2085 }
2086
2087 public void checkAccount() {
2088 if (mCurrentAccount >= mAccountsOfType.length) {
2089 sendResult();
2090 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002091 }
Fred Quintana33269202009-04-20 16:05:10 -07002092
Fred Quintana29e94b82010-03-10 12:11:51 -08002093 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2094 if (accountAuthenticator == null) {
2095 // It is possible that the authenticator has died, which is indicated by
2096 // mAuthenticator being set to null. If this happens then just abort.
2097 // There is no need to send back a result or error in this case since
2098 // that already happened when mAuthenticator was cleared.
2099 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2100 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2101 + " connected to the authenticator, " + toDebugString());
2102 }
2103 return;
2104 }
Fred Quintana33269202009-04-20 16:05:10 -07002105 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002106 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002107 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002108 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002109 }
2110 }
2111
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002112 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002113 public void onResult(Bundle result) {
2114 mNumResults++;
2115 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002116 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002117 return;
2118 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002119 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002120 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2121 }
2122 mCurrentAccount++;
2123 checkAccount();
2124 }
2125
2126 public void sendResult() {
2127 IAccountManagerResponse response = getResponseAndClose();
2128 if (response != null) {
2129 try {
2130 Account[] accounts = new Account[mAccountsWithFeatures.size()];
2131 for (int i = 0; i < accounts.length; i++) {
2132 accounts[i] = mAccountsWithFeatures.get(i);
2133 }
Fred Quintana56285a62010-12-02 14:20:51 -08002134 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2135 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2136 + response);
2137 }
Fred Quintana33269202009-04-20 16:05:10 -07002138 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002139 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07002140 response.onResult(result);
2141 } catch (RemoteException e) {
2142 // if the caller is dead then there is no one to care about remote exceptions
2143 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2144 Log.v(TAG, "failure while notifying response", e);
2145 }
2146 }
2147 }
2148 }
2149
2150
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002151 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002152 protected String toDebugString(long now) {
2153 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2154 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2155 }
2156 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002157
Amith Yamasani04e0d262012-02-14 11:50:53 -08002158 /**
2159 * Returns the accounts for a specific user
2160 * @hide
2161 */
2162 public Account[] getAccounts(int userId) {
2163 checkReadAccountsPermission();
2164 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002165 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002166 long identityToken = clearCallingIdentity();
2167 try {
2168 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002169 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002170 }
2171 } finally {
2172 restoreCallingIdentity(identityToken);
2173 }
2174 }
2175
Amith Yamasanif29f2362012-04-05 18:29:52 -07002176 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002177 * Returns accounts for all running users.
2178 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07002179 * @hide
2180 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002181 public AccountAndUser[] getRunningAccounts() {
2182 final int[] runningUserIds;
2183 try {
2184 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2185 } catch (RemoteException e) {
2186 // Running in system_server; should never happen
2187 throw new RuntimeException(e);
2188 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002189 return getAccounts(runningUserIds);
2190 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07002191
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002192 /** {@hide} */
2193 public AccountAndUser[] getAllAccounts() {
2194 final List<UserInfo> users = getUserManager().getUsers();
2195 final int[] userIds = new int[users.size()];
2196 for (int i = 0; i < userIds.length; i++) {
2197 userIds[i] = users.get(i).id;
2198 }
2199 return getAccounts(userIds);
2200 }
2201
2202 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002203 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002204 for (int userId : userIds) {
2205 UserAccounts userAccounts = getUserAccounts(userId);
2206 if (userAccounts == null) continue;
2207 synchronized (userAccounts.cacheLock) {
2208 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2209 Binder.getCallingUid(), null);
2210 for (int a = 0; a < accounts.length; a++) {
2211 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07002212 }
2213 }
2214 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002215
2216 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2217 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002218 }
2219
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002220 @Override
2221 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002222 return getAccountsAsUser(type, userId, null, -1);
2223 }
2224
2225 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
2226 int packageUid) {
2227 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002228 // Only allow the system process to read accounts of other users
2229 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002230 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002231 && mContext.checkCallingOrSelfPermission(
2232 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2233 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002234 throw new SecurityException("User " + UserHandle.getCallingUserId()
2235 + " trying to get account for " + userId);
2236 }
2237
Fred Quintana56285a62010-12-02 14:20:51 -08002238 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2239 Log.v(TAG, "getAccounts: accountType " + type
2240 + ", caller's uid " + Binder.getCallingUid()
2241 + ", pid " + Binder.getCallingPid());
2242 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002243 // If the original calling app was using the framework account chooser activity, we'll
2244 // be passed in the original caller's uid here, which is what should be used for filtering.
2245 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2246 callingUid = packageUid;
2247 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002248 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002249 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002250 long identityToken = clearCallingIdentity();
2251 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002252 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002253 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002254 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002255 } finally {
2256 restoreCallingIdentity(identityToken);
2257 }
2258 }
2259
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002260 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002261 public boolean addSharedAccountAsUser(Account account, int userId) {
2262 userId = handleIncomingUser(userId);
2263 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
2264 ContentValues values = new ContentValues();
2265 values.put(ACCOUNTS_NAME, account.name);
2266 values.put(ACCOUNTS_TYPE, account.type);
2267 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2268 new String[] {account.name, account.type});
2269 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2270 if (accountId < 0) {
2271 Log.w(TAG, "insertAccountIntoDatabase: " + account
2272 + ", skipping the DB insert failed");
2273 return false;
2274 }
2275 return true;
2276 }
2277
2278 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002279 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
2280 userId = handleIncomingUser(userId);
2281 UserAccounts accounts = getUserAccounts(userId);
2282 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2283 final ContentValues values = new ContentValues();
2284 values.put(ACCOUNTS_NAME, newName);
2285 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
2286 int r = db.update(
2287 TABLE_SHARED_ACCOUNTS,
2288 values,
2289 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2290 new String[] { account.name, account.type });
2291 if (r > 0) {
2292 // Recursively rename the account.
2293 renameAccountInternal(accounts, account, newName);
2294 }
2295 return r > 0;
2296 }
2297
2298 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002299 public boolean removeSharedAccountAsUser(Account account, int userId) {
2300 userId = handleIncomingUser(userId);
2301 UserAccounts accounts = getUserAccounts(userId);
2302 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2303 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2304 new String[] {account.name, account.type});
2305 if (r > 0) {
2306 removeAccountInternal(accounts, account);
2307 }
2308 return r > 0;
2309 }
2310
2311 @Override
2312 public Account[] getSharedAccountsAsUser(int userId) {
2313 userId = handleIncomingUser(userId);
2314 UserAccounts accounts = getUserAccounts(userId);
2315 ArrayList<Account> accountList = new ArrayList<Account>();
2316 Cursor cursor = null;
2317 try {
2318 cursor = accounts.openHelper.getReadableDatabase()
2319 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2320 null, null, null, null, null);
2321 if (cursor != null && cursor.moveToFirst()) {
2322 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2323 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2324 do {
2325 accountList.add(new Account(cursor.getString(nameIndex),
2326 cursor.getString(typeIndex)));
2327 } while (cursor.moveToNext());
2328 }
2329 } finally {
2330 if (cursor != null) {
2331 cursor.close();
2332 }
2333 }
2334 Account[] accountArray = new Account[accountList.size()];
2335 accountList.toArray(accountArray);
2336 return accountArray;
2337 }
2338
2339 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002340 public Account[] getAccounts(String type) {
2341 return getAccountsAsUser(type, UserHandle.getCallingUserId());
2342 }
2343
Amith Yamasani27db4682013-03-30 17:07:47 -07002344 @Override
2345 public Account[] getAccountsForPackage(String packageName, int uid) {
2346 int callingUid = Binder.getCallingUid();
2347 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2348 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2349 + callingUid + " with uid=" + uid);
2350 }
2351 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
2352 }
2353
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002354 @Override
2355 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
2356 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
2357 int packageUid = -1;
2358 try {
2359 packageUid = AppGlobals.getPackageManager().getPackageUid(
2360 packageName, UserHandle.getCallingUserId());
2361 } catch (RemoteException re) {
2362 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2363 return new Account[0];
2364 }
2365 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
2366 }
2367
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002368 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002369 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07002370 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08002371 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2372 Log.v(TAG, "getAccounts: accountType " + type
2373 + ", response " + response
2374 + ", features " + stringArrayToString(features)
2375 + ", caller's uid " + Binder.getCallingUid()
2376 + ", pid " + Binder.getCallingPid());
2377 }
Fred Quintana382601f2010-03-25 12:25:10 -07002378 if (response == null) throw new IllegalArgumentException("response is null");
2379 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002380 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002381 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002382 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07002383 long identityToken = clearCallingIdentity();
2384 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002385 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002386 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002387 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002388 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002389 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002390 Bundle result = new Bundle();
2391 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2392 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002393 return;
2394 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002395 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
2396 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002397 } finally {
2398 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002399 }
2400 }
2401
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002402 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002403 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002404 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002405 try {
2406 if (cursor.moveToNext()) {
2407 return cursor.getLong(0);
2408 }
2409 return -1;
2410 } finally {
2411 cursor.close();
2412 }
2413 }
2414
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002415 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002416 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2417 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2418 new String[]{key}, null, null, null);
2419 try {
2420 if (cursor.moveToNext()) {
2421 return cursor.getLong(0);
2422 }
2423 return -1;
2424 } finally {
2425 cursor.close();
2426 }
2427 }
2428
Fred Quintanaa698f422009-04-08 19:14:54 -07002429 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002430 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002431 IAccountManagerResponse mResponse;
2432 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002433 final boolean mExpectActivityLaunch;
2434 final long mCreationTime;
2435
Fred Quintana33269202009-04-20 16:05:10 -07002436 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002437 private int mNumRequestContinued = 0;
2438 private int mNumErrors = 0;
2439
Fred Quintana60307342009-03-24 22:48:12 -07002440 IAccountAuthenticator mAuthenticator = null;
2441
Fred Quintana8570f742010-02-18 10:32:54 -08002442 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002443 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002444
Amith Yamasani04e0d262012-02-14 11:50:53 -08002445 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08002446 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07002447 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002448 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002449 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002450 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002451 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002452 mResponse = response;
2453 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002454 mExpectActivityLaunch = expectActivityLaunch;
2455 mCreationTime = SystemClock.elapsedRealtime();
2456 synchronized (mSessions) {
2457 mSessions.put(toString(), this);
2458 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002459 if (response != null) {
2460 try {
2461 response.asBinder().linkToDeath(this, 0 /* flags */);
2462 } catch (RemoteException e) {
2463 mResponse = null;
2464 binderDied();
2465 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002466 }
Fred Quintana60307342009-03-24 22:48:12 -07002467 }
2468
Fred Quintanaa698f422009-04-08 19:14:54 -07002469 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002470 if (mResponse == null) {
2471 // this session has already been closed
2472 return null;
2473 }
Fred Quintana60307342009-03-24 22:48:12 -07002474 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002475 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002476 return response;
2477 }
2478
Fred Quintanaa698f422009-04-08 19:14:54 -07002479 private void close() {
2480 synchronized (mSessions) {
2481 if (mSessions.remove(toString()) == null) {
2482 // the session was already closed, so bail out now
2483 return;
2484 }
2485 }
2486 if (mResponse != null) {
2487 // stop listening for response deaths
2488 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2489
2490 // clear this so that we don't accidentally send any further results
2491 mResponse = null;
2492 }
2493 cancelTimeout();
2494 unbind();
2495 }
2496
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002497 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002498 public void binderDied() {
2499 mResponse = null;
2500 close();
2501 }
2502
2503 protected String toDebugString() {
2504 return toDebugString(SystemClock.elapsedRealtime());
2505 }
2506
2507 protected String toDebugString(long now) {
2508 return "Session: expectLaunch " + mExpectActivityLaunch
2509 + ", connected " + (mAuthenticator != null)
2510 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2511 + "/" + mNumErrors + ")"
2512 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2513 }
2514
Fred Quintana60307342009-03-24 22:48:12 -07002515 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002516 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2517 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2518 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002519 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002520 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002521 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002522 }
2523 }
2524
2525 private void unbind() {
2526 if (mAuthenticator != null) {
2527 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002528 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002529 }
2530 }
2531
2532 public void scheduleTimeout() {
2533 mMessageHandler.sendMessageDelayed(
2534 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2535 }
2536
2537 public void cancelTimeout() {
2538 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2539 }
2540
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002541 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002542 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002543 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002544 try {
2545 run();
2546 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002547 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002548 "remote exception");
2549 }
Fred Quintana60307342009-03-24 22:48:12 -07002550 }
2551
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002552 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002553 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002554 mAuthenticator = null;
2555 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002556 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002557 try {
2558 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2559 "disconnected");
2560 } catch (RemoteException e) {
2561 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2562 Log.v(TAG, "Session.onServiceDisconnected: "
2563 + "caught RemoteException while responding", e);
2564 }
2565 }
Fred Quintana60307342009-03-24 22:48:12 -07002566 }
2567 }
2568
Fred Quintanab839afc2009-10-14 15:57:28 -07002569 public abstract void run() throws RemoteException;
2570
Fred Quintana60307342009-03-24 22:48:12 -07002571 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002572 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002573 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002574 try {
2575 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2576 "timeout");
2577 } catch (RemoteException e) {
2578 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2579 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2580 e);
2581 }
2582 }
Fred Quintana60307342009-03-24 22:48:12 -07002583 }
2584 }
2585
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002586 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002587 public void onResult(Bundle result) {
2588 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002589 Intent intent = null;
2590 if (result != null
2591 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2592 /*
2593 * The Authenticator API allows third party authenticators to
2594 * supply arbitrary intents to other apps that they can run,
2595 * this can be very bad when those apps are in the system like
2596 * the System Settings.
2597 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002598 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07002599 long bid = Binder.clearCallingIdentity();
2600 try {
2601 PackageManager pm = mContext.getPackageManager();
2602 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2603 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2604 if (PackageManager.SIGNATURE_MATCH !=
2605 pm.checkSignatures(authenticatorUid, targetUid)) {
2606 throw new SecurityException(
2607 "Activity to be started with KEY_INTENT must " +
2608 "share Authenticator's signatures");
2609 }
2610 } finally {
2611 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002612 }
2613 }
2614 if (result != null
2615 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002616 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2617 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002618 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2619 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002620 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2621 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002622 }
Fred Quintana60307342009-03-24 22:48:12 -07002623 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002624 IAccountManagerResponse response;
2625 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002626 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002627 response = mResponse;
2628 } else {
2629 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002630 }
Fred Quintana60307342009-03-24 22:48:12 -07002631 if (response != null) {
2632 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002633 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002634 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2635 Log.v(TAG, getClass().getSimpleName()
2636 + " calling onError() on response " + response);
2637 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002638 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002639 "null bundle returned");
2640 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002641 if (mStripAuthTokenFromResult) {
2642 result.remove(AccountManager.KEY_AUTHTOKEN);
2643 }
Fred Quintana56285a62010-12-02 14:20:51 -08002644 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2645 Log.v(TAG, getClass().getSimpleName()
2646 + " calling onResult() on response " + response);
2647 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002648 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
2649 (intent == null)) {
2650 // All AccountManager error codes are greater than 0
2651 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
2652 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2653 } else {
2654 response.onResult(result);
2655 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002656 }
Fred Quintana60307342009-03-24 22:48:12 -07002657 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002658 // if the caller is dead then there is no one to care about remote exceptions
2659 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2660 Log.v(TAG, "failure while notifying response", e);
2661 }
Fred Quintana60307342009-03-24 22:48:12 -07002662 }
2663 }
2664 }
Fred Quintana60307342009-03-24 22:48:12 -07002665
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002666 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002667 public void onRequestContinued() {
2668 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002669 }
2670
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002671 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002672 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002673 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002674 IAccountManagerResponse response = getResponseAndClose();
2675 if (response != null) {
2676 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002677 Log.v(TAG, getClass().getSimpleName()
2678 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002679 }
2680 try {
2681 response.onError(errorCode, errorMessage);
2682 } catch (RemoteException e) {
2683 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2684 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2685 }
2686 }
2687 } else {
2688 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2689 Log.v(TAG, "Session.onError: already closed");
2690 }
Fred Quintana60307342009-03-24 22:48:12 -07002691 }
2692 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002693
2694 /**
2695 * find the component name for the authenticator and initiate a bind
2696 * if no authenticator or the bind fails then return false, otherwise return true
2697 */
2698 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002699 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2700 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2701 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002702 if (authenticatorInfo == null) {
2703 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2704 Log.v(TAG, "there is no authenticator for " + authenticatorType
2705 + ", bailing out");
2706 }
2707 return false;
2708 }
2709
2710 Intent intent = new Intent();
2711 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2712 intent.setComponent(authenticatorInfo.componentName);
2713 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2714 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2715 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002716 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2717 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002718 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2719 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2720 }
2721 return false;
2722 }
2723
2724
2725 return true;
2726 }
Fred Quintana60307342009-03-24 22:48:12 -07002727 }
2728
2729 private class MessageHandler extends Handler {
2730 MessageHandler(Looper looper) {
2731 super(looper);
2732 }
Costin Manolache3348f142009-09-29 18:58:36 -07002733
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002734 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002735 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002736 switch (msg.what) {
2737 case MESSAGE_TIMED_OUT:
2738 Session session = (Session)msg.obj;
2739 session.onTimedOut();
2740 break;
2741
Amith Yamasani5be347b2013-03-31 17:44:31 -07002742 case MESSAGE_COPY_SHARED_ACCOUNT:
2743 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2744 break;
2745
Fred Quintana60307342009-03-24 22:48:12 -07002746 default:
2747 throw new IllegalStateException("unhandled message: " + msg.what);
2748 }
2749 }
2750 }
2751
Amith Yamasani04e0d262012-02-14 11:50:53 -08002752 private static String getDatabaseName(int userId) {
2753 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002754 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002755 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002756 // Migrate old file, if it exists, to the new location.
2757 // Make sure the new file doesn't already exist. A dummy file could have been
2758 // accidentally created in the old location, causing the new one to become corrupted
2759 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002760 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002761 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002762 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002763 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002764 if (!userDir.exists()) {
2765 if (!userDir.mkdirs()) {
2766 throw new IllegalStateException("User dir cannot be created: " + userDir);
2767 }
2768 }
2769 if (!oldFile.renameTo(databaseFile)) {
2770 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2771 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002772 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002773 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002774 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002775 }
2776
Amith Yamasani04e0d262012-02-14 11:50:53 -08002777 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002778
Amith Yamasani04e0d262012-02-14 11:50:53 -08002779 public DatabaseHelper(Context context, int userId) {
2780 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002781 }
2782
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002783 /**
2784 * This call needs to be made while the mCacheLock is held. The way to
2785 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2786 * @param db The database.
2787 */
Fred Quintana60307342009-03-24 22:48:12 -07002788 @Override
2789 public void onCreate(SQLiteDatabase db) {
2790 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2791 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2792 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2793 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2794 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002795 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Fred Quintana60307342009-03-24 22:48:12 -07002796 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2797
2798 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2799 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2800 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2801 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2802 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2803 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2804
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002805 createGrantsTable(db);
2806
Fred Quintana60307342009-03-24 22:48:12 -07002807 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2808 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2809 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2810 + EXTRAS_KEY + " TEXT NOT NULL, "
2811 + EXTRAS_VALUE + " TEXT, "
2812 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2813
2814 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2815 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2816 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002817
Amith Yamasani67df64b2012-12-14 12:09:36 -08002818 createSharedAccountsTable(db);
2819
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002820 createAccountsDeletionTrigger(db);
2821 }
2822
Amith Yamasani67df64b2012-12-14 12:09:36 -08002823 private void createSharedAccountsTable(SQLiteDatabase db) {
2824 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2825 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2826 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2827 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2828 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2829 }
2830
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002831 private void addOldAccountNameColumn(SQLiteDatabase db) {
2832 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
2833 }
2834
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002835 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002836 db.execSQL(""
2837 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2838 + " BEGIN"
2839 + " DELETE FROM " + TABLE_AUTHTOKENS
2840 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2841 + " DELETE FROM " + TABLE_EXTRAS
2842 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002843 + " DELETE FROM " + TABLE_GRANTS
2844 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002845 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002846 }
2847
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002848 private void createGrantsTable(SQLiteDatabase db) {
2849 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2850 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2851 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2852 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2853 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2854 + "," + GRANTS_GRANTEE_UID + "))");
2855 }
2856
Fred Quintana60307342009-03-24 22:48:12 -07002857 @Override
2858 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002859 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002860
Fred Quintanaa698f422009-04-08 19:14:54 -07002861 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002862 // no longer need to do anything since the work is done
2863 // when upgrading from version 2
2864 oldVersion++;
2865 }
2866
2867 if (oldVersion == 2) {
2868 createGrantsTable(db);
2869 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2870 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002871 oldVersion++;
2872 }
Costin Manolache3348f142009-09-29 18:58:36 -07002873
2874 if (oldVersion == 3) {
2875 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2876 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2877 oldVersion++;
2878 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002879
2880 if (oldVersion == 4) {
2881 createSharedAccountsTable(db);
2882 oldVersion++;
2883 }
2884
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002885 if (oldVersion == 5) {
2886 addOldAccountNameColumn(db);
2887 oldVersion++;
2888 }
2889
Amith Yamasani67df64b2012-12-14 12:09:36 -08002890 if (oldVersion != newVersion) {
2891 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2892 }
Fred Quintana60307342009-03-24 22:48:12 -07002893 }
2894
2895 @Override
2896 public void onOpen(SQLiteDatabase db) {
2897 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2898 }
2899 }
2900
Fred Quintana60307342009-03-24 22:48:12 -07002901 public IBinder onBind(Intent intent) {
2902 return asBinder();
2903 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002904
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002905 /**
2906 * Searches array of arguments for the specified string
2907 * @param args array of argument strings
2908 * @param value value to search for
2909 * @return true if the value is contained in the array
2910 */
2911 private static boolean scanArgs(String[] args, String value) {
2912 if (args != null) {
2913 for (String arg : args) {
2914 if (value.equals(arg)) {
2915 return true;
2916 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002917 }
2918 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002919 return false;
2920 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002921
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002922 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002923 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002924 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2925 != PackageManager.PERMISSION_GRANTED) {
2926 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2927 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2928 + " without permission " + android.Manifest.permission.DUMP);
2929 return;
2930 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002931 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002932 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002933
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002934 final List<UserInfo> users = getUserManager().getUsers();
2935 for (UserInfo user : users) {
2936 ipw.println("User " + user + ":");
2937 ipw.increaseIndent();
2938 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2939 ipw.println();
2940 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002941 }
2942 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002943
Amith Yamasani04e0d262012-02-14 11:50:53 -08002944 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2945 String[] args, boolean isCheckinRequest) {
2946 synchronized (userAccounts.cacheLock) {
2947 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002948
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002949 if (isCheckinRequest) {
2950 // This is a checkin request. *Only* upload the account types and the count of each.
2951 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2952 null, null, ACCOUNTS_TYPE, null, null);
2953 try {
2954 while (cursor.moveToNext()) {
2955 // print type,count
2956 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2957 }
2958 } finally {
2959 if (cursor != null) {
2960 cursor.close();
2961 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002962 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002963 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002964 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002965 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002966 fout.println("Accounts: " + accounts.length);
2967 for (Account account : accounts) {
2968 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002969 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002970
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002971 fout.println();
2972 synchronized (mSessions) {
2973 final long now = SystemClock.elapsedRealtime();
2974 fout.println("Active Sessions: " + mSessions.size());
2975 for (Session session : mSessions.values()) {
2976 fout.println(" " + session.toDebugString(now));
2977 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002978 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002979
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002980 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002981 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002982 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002983 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002984 }
2985
Amith Yamasani04e0d262012-02-14 11:50:53 -08002986 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002987 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002988 long identityToken = clearCallingIdentity();
2989 try {
2990 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2991 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2992 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002993
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002994 if (intent.getComponent() != null &&
2995 GrantCredentialsPermissionActivity.class.getName().equals(
2996 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002997 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002998 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002999 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07003000 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003001 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
3002 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003003 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003004 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07003005 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003006 contextForUser.getText(R.string.notification_title).toString();
3007 n.color = contextForUser.getResources().getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003008 com.android.internal.R.color.system_notification_accent_color);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003009 n.setLatestEventInfo(contextForUser,
Fred Quintana33f889a2009-09-14 17:31:26 -07003010 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07003011 message, PendingIntent.getActivityAsUser(
3012 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003013 null, user));
3014 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003015 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003016 } finally {
3017 restoreCallingIdentity(identityToken);
3018 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003019 }
3020
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003021 protected void installNotification(final int notificationId, final Notification n,
3022 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08003023 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003024 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08003025 }
3026
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003027 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003028 long identityToken = clearCallingIdentity();
3029 try {
3030 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003031 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003032 } finally {
3033 restoreCallingIdentity(identityToken);
3034 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003035 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003036
Fred Quintanab38eb142010-02-24 13:40:54 -08003037 /** Succeeds if any of the specified permissions are granted. */
3038 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003039 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08003040
3041 for (String perm : permissions) {
3042 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
3043 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003044 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08003045 }
3046 return;
3047 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003048 }
Fred Quintanab38eb142010-02-24 13:40:54 -08003049
3050 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08003051 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08003052 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003053 }
3054
Amith Yamasani67df64b2012-12-14 12:09:36 -08003055 private int handleIncomingUser(int userId) {
3056 try {
3057 return ActivityManagerNative.getDefault().handleIncomingUser(
3058 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
3059 } catch (RemoteException re) {
3060 // Shouldn't happen, local.
3061 }
3062 return userId;
3063 }
3064
Christopher Tateccbf84f2013-05-08 15:25:41 -07003065 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003066 final int callingUserId = UserHandle.getUserId(callingUid);
3067
3068 final PackageManager userPackageManager;
3069 try {
3070 userPackageManager = mContext.createPackageContextAsUser(
3071 "android", 0, new UserHandle(callingUserId)).getPackageManager();
3072 } catch (NameNotFoundException e) {
3073 return false;
3074 }
3075
3076 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07003077 for (String name : packages) {
3078 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003079 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08003080 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07003081 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07003082 return true;
3083 }
3084 } catch (PackageManager.NameNotFoundException e) {
3085 return false;
3086 }
3087 }
3088 return false;
3089 }
3090
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003091 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07003092 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07003093 final boolean fromAuthenticator = account != null
3094 && hasAuthenticatorUid(account.type, callerUid);
3095 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08003096 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003097 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3098 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08003099 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003100 + ": is authenticator? " + fromAuthenticator
3101 + ", has explicit permission? " + hasExplicitGrants);
3102 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07003103 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003104 }
3105
Fred Quintana1a231912009-10-15 11:31:30 -07003106 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003107 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003108 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003109 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003110 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003111 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08003112 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003113 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003114 }
3115 }
3116 return false;
3117 }
3118
Amith Yamasani04e0d262012-02-14 11:50:53 -08003119 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
3120 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003121 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003122 return true;
3123 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003124 UserAccounts accounts = getUserAccountsForCaller();
3125 synchronized (accounts.cacheLock) {
3126 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3127 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003128 account.name, account.type};
3129 final boolean permissionGranted =
3130 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
3131 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
3132 // TODO: Skip this check when running automated tests. Replace this
3133 // with a more general solution.
3134 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08003135 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003136 + " but ignoring since device is in test harness.");
3137 return true;
3138 }
3139 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003140 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003141 }
3142
3143 private void checkCallingUidAgainstAuthenticator(Account account) {
3144 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07003145 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003146 String msg = "caller uid " + uid + " is different than the authenticator's uid";
3147 Log.w(TAG, msg);
3148 throw new SecurityException(msg);
3149 }
3150 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3151 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
3152 }
3153 }
3154
3155 private void checkAuthenticateAccountsPermission(Account account) {
3156 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
3157 checkCallingUidAgainstAuthenticator(account);
3158 }
3159
3160 private void checkReadAccountsPermission() {
3161 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
3162 }
3163
3164 private void checkManageAccountsPermission() {
3165 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
3166 }
3167
Fred Quintanab38eb142010-02-24 13:40:54 -08003168 private void checkManageAccountsOrUseCredentialsPermissions() {
3169 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
3170 Manifest.permission.USE_CREDENTIALS);
3171 }
3172
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003173 private boolean canUserModifyAccounts(int userId) {
3174 if (getUserManager().getUserRestrictions(new UserHandle(userId))
3175 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
3176 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003177 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003178 return true;
3179 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003180
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003181 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003182 DevicePolicyManager dpm = (DevicePolicyManager) mContext
3183 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003184 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02003185 if (typesArray == null) {
3186 return true;
3187 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003188 for (String forbiddenType : typesArray) {
3189 if (forbiddenType.equals(accountType)) {
3190 return false;
3191 }
3192 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003193 return true;
3194 }
3195
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003196 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07003197 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
3198 throws RemoteException {
3199 final int callingUid = getCallingUid();
3200
Amith Yamasani27db4682013-03-30 17:07:47 -07003201 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07003202 throw new SecurityException();
3203 }
3204
3205 if (value) {
3206 grantAppPermission(account, authTokenType, uid);
3207 } else {
3208 revokeAppPermission(account, authTokenType, uid);
3209 }
3210 }
3211
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003212 /**
3213 * Allow callers with the given uid permission to get credentials for account/authTokenType.
3214 * <p>
3215 * Although this is public it can only be accessed via the AccountManagerService object
3216 * which is in the system. This means we don't need to protect it with permissions.
3217 * @hide
3218 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003219 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003220 if (account == null || authTokenType == null) {
3221 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003222 return;
3223 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003224 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003225 synchronized (accounts.cacheLock) {
3226 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003227 db.beginTransaction();
3228 try {
3229 long accountId = getAccountIdLocked(db, account);
3230 if (accountId >= 0) {
3231 ContentValues values = new ContentValues();
3232 values.put(GRANTS_ACCOUNTS_ID, accountId);
3233 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
3234 values.put(GRANTS_GRANTEE_UID, uid);
3235 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
3236 db.setTransactionSuccessful();
3237 }
3238 } finally {
3239 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003240 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003241 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3242 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003243 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003244 }
3245
3246 /**
3247 * Don't allow callers with the given uid permission to get credentials for
3248 * account/authTokenType.
3249 * <p>
3250 * Although this is public it can only be accessed via the AccountManagerService object
3251 * which is in the system. This means we don't need to protect it with permissions.
3252 * @hide
3253 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003254 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003255 if (account == null || authTokenType == null) {
3256 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003257 return;
3258 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003259 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003260 synchronized (accounts.cacheLock) {
3261 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003262 db.beginTransaction();
3263 try {
3264 long accountId = getAccountIdLocked(db, account);
3265 if (accountId >= 0) {
3266 db.delete(TABLE_GRANTS,
3267 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
3268 + GRANTS_GRANTEE_UID + "=?",
3269 new String[]{String.valueOf(accountId), authTokenType,
3270 String.valueOf(uid)});
3271 db.setTransactionSuccessful();
3272 }
3273 } finally {
3274 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003275 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003276 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3277 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003278 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003279 }
Fred Quintana56285a62010-12-02 14:20:51 -08003280
3281 static final private String stringArrayToString(String[] value) {
3282 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
3283 }
3284
Amith Yamasani04e0d262012-02-14 11:50:53 -08003285 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
3286 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003287 if (oldAccountsForType != null) {
3288 ArrayList<Account> newAccountsList = new ArrayList<Account>();
3289 for (Account curAccount : oldAccountsForType) {
3290 if (!curAccount.equals(account)) {
3291 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003292 }
3293 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003294 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003295 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003296 } else {
3297 Account[] newAccountsForType = new Account[newAccountsList.size()];
3298 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003299 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003300 }
Fred Quintana56285a62010-12-02 14:20:51 -08003301 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003302 accounts.userDataCache.remove(account);
3303 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003304 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003305 }
3306
3307 /**
3308 * This assumes that the caller has already checked that the account is not already present.
3309 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08003310 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
3311 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003312 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
3313 Account[] newAccountsForType = new Account[oldLength + 1];
3314 if (accountsForType != null) {
3315 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08003316 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003317 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003318 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08003319 }
3320
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003321 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07003322 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003323 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07003324 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003325 return unfiltered;
3326 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003327 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
3328 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003329 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003330 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003331 // otherwise return non-shared accounts only.
3332 // This might be a temporary way to specify a whitelist
3333 String whiteList = mContext.getResources().getString(
3334 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
3335 for (String packageName : packages) {
3336 if (whiteList.contains(";" + packageName + ";")) {
3337 return unfiltered;
3338 }
3339 }
3340 ArrayList<Account> allowed = new ArrayList<Account>();
3341 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
3342 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003343 String requiredAccountType = "";
3344 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07003345 // If there's an explicit callingPackage specified, check if that package
3346 // opted in to see restricted accounts.
3347 if (callingPackage != null) {
3348 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003349 if (pi != null && pi.restrictedAccountType != null) {
3350 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07003351 }
3352 } else {
3353 // Otherwise check if the callingUid has a package that has opted in
3354 for (String packageName : packages) {
3355 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
3356 if (pi != null && pi.restrictedAccountType != null) {
3357 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07003358 break;
3359 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003360 }
3361 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003362 } catch (NameNotFoundException nnfe) {
3363 }
3364 for (Account account : unfiltered) {
3365 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003366 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003367 } else {
3368 boolean found = false;
3369 for (Account shared : sharedAccounts) {
3370 if (shared.equals(account)) {
3371 found = true;
3372 break;
3373 }
3374 }
3375 if (!found) {
3376 allowed.add(account);
3377 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003378 }
3379 }
3380 Account[] filtered = new Account[allowed.size()];
3381 allowed.toArray(filtered);
3382 return filtered;
3383 } else {
3384 return unfiltered;
3385 }
3386 }
3387
Amith Yamasani27db4682013-03-30 17:07:47 -07003388 /*
3389 * packageName can be null. If not null, it should be used to filter out restricted accounts
3390 * that the package is not allowed to access.
3391 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003392 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07003393 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003394 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003395 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003396 if (accounts == null) {
3397 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08003398 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003399 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07003400 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003401 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003402 } else {
3403 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003404 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003405 totalLength += accounts.length;
3406 }
3407 if (totalLength == 0) {
3408 return EMPTY_ACCOUNT_ARRAY;
3409 }
3410 Account[] accounts = new Account[totalLength];
3411 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003412 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003413 System.arraycopy(accountsOfType, 0, accounts, totalLength,
3414 accountsOfType.length);
3415 totalLength += accountsOfType.length;
3416 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003417 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003418 }
3419 }
3420
Amith Yamasani04e0d262012-02-14 11:50:53 -08003421 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3422 Account account, String key, String value) {
3423 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003424 if (userDataForAccount == null) {
3425 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003426 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003427 }
3428 if (value == null) {
3429 userDataForAccount.remove(key);
3430 } else {
3431 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003432 }
3433 }
3434
Amith Yamasani04e0d262012-02-14 11:50:53 -08003435 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3436 Account account, String key, String value) {
3437 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003438 if (authTokensForAccount == null) {
3439 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003440 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003441 }
3442 if (value == null) {
3443 authTokensForAccount.remove(key);
3444 } else {
3445 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003446 }
3447 }
3448
Amith Yamasani04e0d262012-02-14 11:50:53 -08003449 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
3450 String authTokenType) {
3451 synchronized (accounts.cacheLock) {
3452 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003453 if (authTokensForAccount == null) {
3454 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003455 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003456 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003457 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003458 }
3459 return authTokensForAccount.get(authTokenType);
3460 }
3461 }
3462
Amith Yamasani04e0d262012-02-14 11:50:53 -08003463 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
3464 synchronized (accounts.cacheLock) {
3465 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003466 if (userDataForAccount == null) {
3467 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003468 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003469 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003470 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003471 }
3472 return userDataForAccount.get(key);
3473 }
3474 }
3475
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003476 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3477 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003478 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003479 Cursor cursor = db.query(TABLE_EXTRAS,
3480 COLUMNS_EXTRAS_KEY_AND_VALUE,
3481 SELECTION_USERDATA_BY_ACCOUNT,
3482 new String[]{account.name, account.type},
3483 null, null, null);
3484 try {
3485 while (cursor.moveToNext()) {
3486 final String tmpkey = cursor.getString(0);
3487 final String value = cursor.getString(1);
3488 userDataForAccount.put(tmpkey, value);
3489 }
3490 } finally {
3491 cursor.close();
3492 }
3493 return userDataForAccount;
3494 }
3495
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003496 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3497 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003498 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003499 Cursor cursor = db.query(TABLE_AUTHTOKENS,
3500 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3501 SELECTION_AUTHTOKENS_BY_ACCOUNT,
3502 new String[]{account.name, account.type},
3503 null, null, null);
3504 try {
3505 while (cursor.moveToNext()) {
3506 final String type = cursor.getString(0);
3507 final String authToken = cursor.getString(1);
3508 authTokensForAccount.put(type, authToken);
3509 }
3510 } finally {
3511 cursor.close();
3512 }
3513 return authTokensForAccount;
3514 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003515
3516 private Context getContextForUser(UserHandle user) {
3517 try {
3518 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
3519 } catch (NameNotFoundException e) {
3520 // Default to mContext, not finding the package system is running as is unlikely.
3521 return mContext;
3522 }
3523 }
Fred Quintana60307342009-03-24 22:48:12 -07003524}