blob: 0fbde37a20c5148ccd856962b546e9bd29e83051 [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;
Fred Quintanaa698f422009-04-08 19:14:54 -070037import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070038import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070039import android.content.ContentValues;
40import android.content.Context;
41import android.content.Intent;
42import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070043import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070044import android.content.pm.ApplicationInfo;
45import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070046import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070047import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070048import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070049import android.content.pm.RegisteredServicesCacheListener;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070050import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070051import android.database.Cursor;
52import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070053import android.database.sqlite.SQLiteDatabase;
54import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070055import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070056import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080057import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070058import android.os.Handler;
59import android.os.HandlerThread;
60import android.os.IBinder;
61import android.os.Looper;
62import android.os.Message;
Amith Yamasani27db4682013-03-30 17:07:47 -070063import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070064import android.os.RemoteException;
65import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070067import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070068import android.text.TextUtils;
69import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070070import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070071import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080072import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070073
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070074import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080075import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080076import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070077import com.google.android.collect.Lists;
78import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070079
Oscar Montemayora8529f62009-11-18 10:14:20 -080080import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070081import java.io.FileDescriptor;
82import java.io.PrintWriter;
83import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080084import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070085import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070086import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070087import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080088import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070089import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080090import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070091import java.util.concurrent.atomic.AtomicInteger;
92import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070093
Fred Quintana60307342009-03-24 22:48:12 -070094/**
95 * A system service that provides account, password, and authtoken management for all
96 * accounts on the device. Some of these calls are implemented with the help of the corresponding
97 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
98 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070099 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700100 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700101 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700102public class AccountManagerService
103 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800104 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700105 private static final String TAG = "AccountManagerService";
106
107 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
108 private static final String DATABASE_NAME = "accounts.db";
Amith Yamasani67df64b2012-12-14 12:09:36 -0800109 private static final int DATABASE_VERSION = 5;
Fred Quintana60307342009-03-24 22:48:12 -0700110
111 private final Context mContext;
112
Fred Quintana56285a62010-12-02 14:20:51 -0800113 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700114 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800115
Fred Quintana60307342009-03-24 22:48:12 -0700116 private HandlerThread mMessageThread;
117 private final MessageHandler mMessageHandler;
118
119 // Messages that can be sent on mHandler
120 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700121 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700122
Fred Quintana56285a62010-12-02 14:20:51 -0800123 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700124
125 private static final String TABLE_ACCOUNTS = "accounts";
126 private static final String ACCOUNTS_ID = "_id";
127 private static final String ACCOUNTS_NAME = "name";
128 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700129 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700130 private static final String ACCOUNTS_PASSWORD = "password";
131
132 private static final String TABLE_AUTHTOKENS = "authtokens";
133 private static final String AUTHTOKENS_ID = "_id";
134 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
135 private static final String AUTHTOKENS_TYPE = "type";
136 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
137
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700138 private static final String TABLE_GRANTS = "grants";
139 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
140 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
141 private static final String GRANTS_GRANTEE_UID = "uid";
142
Fred Quintana60307342009-03-24 22:48:12 -0700143 private static final String TABLE_EXTRAS = "extras";
144 private static final String EXTRAS_ID = "_id";
145 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
146 private static final String EXTRAS_KEY = "key";
147 private static final String EXTRAS_VALUE = "value";
148
149 private static final String TABLE_META = "meta";
150 private static final String META_KEY = "key";
151 private static final String META_VALUE = "value";
152
Amith Yamasani67df64b2012-12-14 12:09:36 -0800153 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
154
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700155 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
156 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700157 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700158
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700159 private static final String COUNT_OF_MATCHING_GRANTS = ""
160 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
161 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
162 + " AND " + GRANTS_GRANTEE_UID + "=?"
163 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
164 + " AND " + ACCOUNTS_NAME + "=?"
165 + " AND " + ACCOUNTS_TYPE + "=?";
166
Fred Quintana56285a62010-12-02 14:20:51 -0800167 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
168 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
169 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
170 AUTHTOKENS_AUTHTOKEN};
171
172 private static final String SELECTION_USERDATA_BY_ACCOUNT =
173 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
174 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
175
Fred Quintanaa698f422009-04-08 19:14:54 -0700176 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700177 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
178
Amith Yamasani04e0d262012-02-14 11:50:53 -0800179 static class UserAccounts {
180 private final int userId;
181 private final DatabaseHelper openHelper;
182 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
183 credentialsPermissionNotificationIds =
184 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
185 private final HashMap<Account, Integer> signinRequiredNotificationIds =
186 new HashMap<Account, Integer>();
187 private final Object cacheLock = new Object();
188 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700189 private final HashMap<String, Account[]> accountCache =
190 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800191 /** protected by the {@link #cacheLock} */
192 private HashMap<Account, HashMap<String, String>> userDataCache =
193 new HashMap<Account, HashMap<String, String>>();
194 /** protected by the {@link #cacheLock} */
195 private HashMap<Account, HashMap<String, String>> authTokenCache =
196 new HashMap<Account, HashMap<String, String>>();
197
198 UserAccounts(Context context, int userId) {
199 this.userId = userId;
200 synchronized (cacheLock) {
201 openHelper = new DatabaseHelper(context, userId);
202 }
203 }
204 }
205
206 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
207
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700208 private static AtomicReference<AccountManagerService> sThis =
209 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700210 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700211
212 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700213 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700214 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
215 }
216
Fred Quintana56285a62010-12-02 14:20:51 -0800217
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700218 /**
219 * This should only be called by system code. One should only call this after the service
220 * has started.
221 * @return a reference to the AccountManagerService instance
222 * @hide
223 */
224 public static AccountManagerService getSingleton() {
225 return sThis.get();
226 }
Fred Quintana60307342009-03-24 22:48:12 -0700227
Fred Quintana56285a62010-12-02 14:20:51 -0800228 public AccountManagerService(Context context) {
229 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700230 }
231
Fred Quintana56285a62010-12-02 14:20:51 -0800232 public AccountManagerService(Context context, PackageManager packageManager,
233 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700234 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800235 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700236
Fred Quintana60307342009-03-24 22:48:12 -0700237 mMessageThread = new HandlerThread("AccountManagerService");
238 mMessageThread.start();
239 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
240
Fred Quintana56285a62010-12-02 14:20:51 -0800241 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800242 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700243
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700244 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800245
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800246 IntentFilter intentFilter = new IntentFilter();
247 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
248 intentFilter.addDataScheme("package");
249 mContext.registerReceiver(new BroadcastReceiver() {
250 @Override
251 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800252 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800253 }
254 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800255
Amith Yamasani13593602012-03-22 16:16:17 -0700256 IntentFilter userFilter = new IntentFilter();
257 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800258 userFilter.addAction(Intent.ACTION_USER_STARTED);
259 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700260 @Override
261 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800262 String action = intent.getAction();
263 if (Intent.ACTION_USER_REMOVED.equals(action)) {
264 onUserRemoved(intent);
265 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
266 onUserStarted(intent);
267 }
Amith Yamasani13593602012-03-22 16:16:17 -0700268 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800269 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800270 }
271
Kenny Root26ff6622012-07-30 12:58:03 -0700272 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700273 }
274
Amith Yamasani258848d2012-08-10 17:06:33 -0700275 private UserManager getUserManager() {
276 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700277 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700278 }
279 return mUserManager;
280 }
281
Amith Yamasani04e0d262012-02-14 11:50:53 -0800282 private UserAccounts initUser(int userId) {
283 synchronized (mUsers) {
284 UserAccounts accounts = mUsers.get(userId);
285 if (accounts == null) {
286 accounts = new UserAccounts(mContext, userId);
287 mUsers.append(userId, accounts);
288 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700289 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800290 }
291 return accounts;
292 }
293 }
294
295 private void purgeOldGrantsAll() {
296 synchronized (mUsers) {
297 for (int i = 0; i < mUsers.size(); i++) {
298 purgeOldGrants(mUsers.valueAt(i));
299 }
300 }
301 }
302
303 private void purgeOldGrants(UserAccounts accounts) {
304 synchronized (accounts.cacheLock) {
305 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800306 final Cursor cursor = db.query(TABLE_GRANTS,
307 new String[]{GRANTS_GRANTEE_UID},
308 null, null, GRANTS_GRANTEE_UID, null, null);
309 try {
310 while (cursor.moveToNext()) {
311 final int uid = cursor.getInt(0);
312 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
313 if (packageExists) {
314 continue;
315 }
316 Log.d(TAG, "deleting grants for UID " + uid
317 + " because its package is no longer installed");
318 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
319 new String[]{Integer.toString(uid)});
320 }
321 } finally {
322 cursor.close();
323 }
324 }
325 }
326
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700327 /**
328 * Validate internal set of accounts against installed authenticators for
329 * given user. Clears cached authenticators before validating.
330 */
331 public void validateAccounts(int userId) {
332 final UserAccounts accounts = getUserAccounts(userId);
333
334 // Invalidate user-specific cache to make sure we catch any
335 // removed authenticators.
336 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
337 }
338
339 /**
340 * Validate internal set of accounts against installed authenticators for
341 * given user. Clear cached authenticators before validating when requested.
342 */
343 private void validateAccountsInternal(
344 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
345 if (invalidateAuthenticatorCache) {
346 mAuthenticatorCache.invalidateCache(accounts.userId);
347 }
348
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700349 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
350 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
351 mAuthenticatorCache.getAllServices(accounts.userId)) {
352 knownAuth.add(service.type);
353 }
354
Amith Yamasani04e0d262012-02-14 11:50:53 -0800355 synchronized (accounts.cacheLock) {
356 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800357 boolean accountDeleted = false;
358 Cursor cursor = db.query(TABLE_ACCOUNTS,
359 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
360 null, null, null, null, null);
361 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800362 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800363 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700364 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800365 while (cursor.moveToNext()) {
366 final long accountId = cursor.getLong(0);
367 final String accountType = cursor.getString(1);
368 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700369
370 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700371 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800372 + accountType + " no longer has a registered authenticator");
373 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
374 accountDeleted = true;
375 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800376 accounts.userDataCache.remove(account);
377 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800378 } else {
379 ArrayList<String> accountNames = accountNamesByType.get(accountType);
380 if (accountNames == null) {
381 accountNames = new ArrayList<String>();
382 accountNamesByType.put(accountType, accountNames);
383 }
384 accountNames.add(accountName);
385 }
386 }
Andy McFadden2f362292012-01-20 14:43:38 -0800387 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800388 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800389 final String accountType = cur.getKey();
390 final ArrayList<String> accountNames = cur.getValue();
391 final Account[] accountsForType = new Account[accountNames.size()];
392 int i = 0;
393 for (String accountName : accountNames) {
394 accountsForType[i] = new Account(accountName, accountType);
395 ++i;
396 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800397 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800398 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800399 } finally {
400 cursor.close();
401 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800402 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800403 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800404 }
405 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700406 }
407
Amith Yamasani04e0d262012-02-14 11:50:53 -0800408 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700409 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800410 }
411
412 protected UserAccounts getUserAccounts(int userId) {
413 synchronized (mUsers) {
414 UserAccounts accounts = mUsers.get(userId);
415 if (accounts == null) {
416 accounts = initUser(userId);
417 mUsers.append(userId, accounts);
418 }
419 return accounts;
420 }
421 }
422
Amith Yamasani13593602012-03-22 16:16:17 -0700423 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700424 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700425 if (userId < 1) return;
426
427 UserAccounts accounts;
428 synchronized (mUsers) {
429 accounts = mUsers.get(userId);
430 mUsers.remove(userId);
431 }
432 if (accounts == null) {
433 File dbFile = new File(getDatabaseName(userId));
434 dbFile.delete();
435 return;
436 }
437
438 synchronized (accounts.cacheLock) {
439 accounts.openHelper.close();
440 File dbFile = new File(getDatabaseName(userId));
441 dbFile.delete();
442 }
443 }
444
Amith Yamasani67df64b2012-12-14 12:09:36 -0800445 private void onUserStarted(Intent intent) {
446 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
447 if (userId < 1) return;
448
449 // Check if there's a shared account that needs to be created as an account
450 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
451 if (sharedAccounts == null || sharedAccounts.length == 0) return;
452 Account[] accounts = getAccountsAsUser(null, userId);
453 for (Account sa : sharedAccounts) {
454 if (ArrayUtils.contains(accounts, sa)) continue;
455 // Account doesn't exist. Copy it now.
456 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
457 }
458 }
459
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700460 @Override
461 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700462 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700463 }
464
Fred Quintanaa698f422009-04-08 19:14:54 -0700465 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800466 if (Log.isLoggable(TAG, Log.VERBOSE)) {
467 Log.v(TAG, "getPassword: " + account
468 + ", caller's uid " + Binder.getCallingUid()
469 + ", pid " + Binder.getCallingPid());
470 }
Fred Quintana382601f2010-03-25 12:25:10 -0700471 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700472 checkAuthenticateAccountsPermission(account);
473
Amith Yamasani04e0d262012-02-14 11:50:53 -0800474 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700475 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700476 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800477 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700478 } finally {
479 restoreCallingIdentity(identityToken);
480 }
481 }
482
Amith Yamasani04e0d262012-02-14 11:50:53 -0800483 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700484 if (account == null) {
485 return null;
486 }
487
Amith Yamasani04e0d262012-02-14 11:50:53 -0800488 synchronized (accounts.cacheLock) {
489 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800490 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
491 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
492 new String[]{account.name, account.type}, null, null, null);
493 try {
494 if (cursor.moveToNext()) {
495 return cursor.getString(0);
496 }
497 return null;
498 } finally {
499 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700500 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700501 }
502 }
503
504 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800505 if (Log.isLoggable(TAG, Log.VERBOSE)) {
506 Log.v(TAG, "getUserData: " + account
507 + ", key " + key
508 + ", caller's uid " + Binder.getCallingUid()
509 + ", pid " + Binder.getCallingPid());
510 }
Fred Quintana382601f2010-03-25 12:25:10 -0700511 if (account == null) throw new IllegalArgumentException("account is null");
512 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700513 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800514 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 long identityToken = clearCallingIdentity();
516 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800517 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700518 } finally {
519 restoreCallingIdentity(identityToken);
520 }
521 }
522
Fred Quintana97889762009-06-15 12:29:24 -0700523 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800524 if (Log.isLoggable(TAG, Log.VERBOSE)) {
525 Log.v(TAG, "getAuthenticatorTypes: "
526 + "caller's uid " + Binder.getCallingUid()
527 + ", pid " + Binder.getCallingPid());
528 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700529 final int userId = UserHandle.getCallingUserId();
530 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700531 try {
Fred Quintana97889762009-06-15 12:29:24 -0700532 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700533 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700534 AuthenticatorDescription[] types =
535 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700536 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700537 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700538 : authenticatorCollection) {
539 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700540 i++;
541 }
542 return types;
543 } finally {
544 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700545 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700546 }
547
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700548 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700549 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800550 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700551 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800552 + ", caller's uid " + Binder.getCallingUid()
553 + ", pid " + Binder.getCallingPid());
554 }
Fred Quintana382601f2010-03-25 12:25:10 -0700555 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700556 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700557 /*
558 * Child users are not allowed to add accounts. Only the accounts that are
559 * shared by the parent profile can be added to child profile.
560 *
561 * TODO: Only allow accounts that were shared to be added by
562 * a limited user.
563 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700564
Amith Yamasani04e0d262012-02-14 11:50:53 -0800565 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700566 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700567 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700568 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800569 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700570 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700571 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700572 }
573 }
574
Amith Yamasani67df64b2012-12-14 12:09:36 -0800575 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
576 final UserAccounts fromAccounts = getUserAccounts(userFrom);
577 final UserAccounts toAccounts = getUserAccounts(userTo);
578 if (fromAccounts == null || toAccounts == null) {
579 return false;
580 }
581
582 long identityToken = clearCallingIdentity();
583 try {
584 new Session(fromAccounts, null, account.type, false,
585 false /* stripAuthTokenFromResult */) {
586 protected String toDebugString(long now) {
587 return super.toDebugString(now) + ", getAccountCredentialsForClone"
588 + ", " + account.type;
589 }
590
591 public void run() throws RemoteException {
592 mAuthenticator.getAccountCredentialsForCloning(this, account);
593 }
594
595 public void onResult(Bundle result) {
596 if (result != null) {
597 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
598 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800599 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800600 }
601 return;
602 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800603 super.onResult(result);
604 }
605 }
606 }.bind();
607 } finally {
608 restoreCallingIdentity(identityToken);
609 }
610 return true;
611 }
612
Amith Yamasani67df64b2012-12-14 12:09:36 -0800613 void completeCloningAccount(final Bundle result, final Account account,
614 final UserAccounts targetUser) {
615 long id = clearCallingIdentity();
616 try {
617 new Session(targetUser, null, account.type, false,
618 false /* stripAuthTokenFromResult */) {
619 protected String toDebugString(long now) {
620 return super.toDebugString(now) + ", getAccountCredentialsForClone"
621 + ", " + account.type;
622 }
623
624 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700625 // Confirm that the owner's account still exists before this step.
626 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
627 synchronized (owner.cacheLock) {
628 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
629 for (Account acc : ownerAccounts) {
630 if (acc.equals(account)) {
631 mAuthenticator.addAccountFromCredentials(this, account, result);
632 break;
633 }
634 }
635 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800636 }
637
638 public void onResult(Bundle result) {
639 if (result != null) {
640 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
641 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800642 } else {
643 // TODO: Show error notification
644 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800645 }
646 return;
647 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800648 super.onResult(result);
649 }
650 }
651
652 public void onError(int errorCode, String errorMessage) {
653 super.onError(errorCode, errorMessage);
654 // TODO: Show error notification to user
655 // TODO: Should we remove the shadow account so that it doesn't keep trying?
656 }
657
658 }.bind();
659 } finally {
660 restoreCallingIdentity(id);
661 }
662 }
663
Amith Yamasani04e0d262012-02-14 11:50:53 -0800664 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800665 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700666 if (account == null) {
667 return false;
668 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800669 synchronized (accounts.cacheLock) {
670 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800671 db.beginTransaction();
672 try {
673 long numMatches = DatabaseUtils.longForQuery(db,
674 "select count(*) from " + TABLE_ACCOUNTS
675 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
676 new String[]{account.name, account.type});
677 if (numMatches > 0) {
678 Log.w(TAG, "insertAccountIntoDatabase: " + account
679 + ", skipping since the account already exists");
680 return false;
681 }
682 ContentValues values = new ContentValues();
683 values.put(ACCOUNTS_NAME, account.name);
684 values.put(ACCOUNTS_TYPE, account.type);
685 values.put(ACCOUNTS_PASSWORD, password);
686 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
687 if (accountId < 0) {
688 Log.w(TAG, "insertAccountIntoDatabase: " + account
689 + ", skipping the DB insert failed");
690 return false;
691 }
692 if (extras != null) {
693 for (String key : extras.keySet()) {
694 final String value = extras.getString(key);
695 if (insertExtraLocked(db, accountId, key, value) < 0) {
696 Log.w(TAG, "insertAccountIntoDatabase: " + account
697 + ", skipping since insertExtra failed for key " + key);
698 return false;
699 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700700 }
701 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800702 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800703 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800704 } finally {
705 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700706 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800707 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700708 }
709 if (accounts.userId == UserHandle.USER_OWNER) {
710 addAccountToLimitedUsers(account);
711 }
712 return true;
713 }
714
715 /**
716 * Adds the account to all limited users as shared accounts. If the user is currently
717 * running, then clone the account too.
718 * @param account the account to share with limited users
719 */
720 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700721 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700722 for (UserInfo user : users) {
723 if (user.isRestricted()) {
724 addSharedAccountAsUser(account, user.id);
725 try {
726 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
727 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
728 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
729 account));
730 }
731 } catch (RemoteException re) {
732 // Shouldn't happen
733 }
734 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700735 }
736 }
737
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800738 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700739 ContentValues values = new ContentValues();
740 values.put(EXTRAS_KEY, key);
741 values.put(EXTRAS_ACCOUNTS_ID, accountId);
742 values.put(EXTRAS_VALUE, value);
743 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
744 }
745
Fred Quintana3084a6f2010-01-14 18:02:03 -0800746 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800747 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800748 if (Log.isLoggable(TAG, Log.VERBOSE)) {
749 Log.v(TAG, "hasFeatures: " + account
750 + ", response " + response
751 + ", features " + stringArrayToString(features)
752 + ", caller's uid " + Binder.getCallingUid()
753 + ", pid " + Binder.getCallingPid());
754 }
Fred Quintana382601f2010-03-25 12:25:10 -0700755 if (response == null) throw new IllegalArgumentException("response is null");
756 if (account == null) throw new IllegalArgumentException("account is null");
757 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800758 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800759 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800760 long identityToken = clearCallingIdentity();
761 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800762 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800763 } finally {
764 restoreCallingIdentity(identityToken);
765 }
766 }
767
768 private class TestFeaturesSession extends Session {
769 private final String[] mFeatures;
770 private final Account mAccount;
771
Amith Yamasani04e0d262012-02-14 11:50:53 -0800772 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800773 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800774 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800775 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800776 mFeatures = features;
777 mAccount = account;
778 }
779
780 public void run() throws RemoteException {
781 try {
782 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
783 } catch (RemoteException e) {
784 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
785 }
786 }
787
788 public void onResult(Bundle result) {
789 IAccountManagerResponse response = getResponseAndClose();
790 if (response != null) {
791 try {
792 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700793 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800794 return;
795 }
Fred Quintana56285a62010-12-02 14:20:51 -0800796 if (Log.isLoggable(TAG, Log.VERBOSE)) {
797 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
798 + response);
799 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800800 final Bundle newResult = new Bundle();
801 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
802 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
803 response.onResult(newResult);
804 } catch (RemoteException e) {
805 // if the caller is dead then there is no one to care about remote exceptions
806 if (Log.isLoggable(TAG, Log.VERBOSE)) {
807 Log.v(TAG, "failure while notifying response", e);
808 }
809 }
810 }
811 }
812
813 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800814 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800815 + ", " + mAccount
816 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
817 }
818 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800819
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700820 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800821 if (Log.isLoggable(TAG, Log.VERBOSE)) {
822 Log.v(TAG, "removeAccount: " + account
823 + ", response " + response
824 + ", caller's uid " + Binder.getCallingUid()
825 + ", pid " + Binder.getCallingPid());
826 }
Fred Quintana382601f2010-03-25 12:25:10 -0700827 if (response == null) throw new IllegalArgumentException("response is null");
828 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700829 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700830 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800831 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800832 if (!canUserModifyAccounts(Binder.getCallingUid())) {
833 try {
834 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
835 "User cannot modify accounts");
836 } catch (RemoteException re) {
837 }
838 }
839
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700840 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800841
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700842 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800843 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800844 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800845 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800846 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800847 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700848 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800849 }
850 }
851 }
852
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700853 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800854 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700855 } finally {
856 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700857 }
Fred Quintana60307342009-03-24 22:48:12 -0700858 }
859
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700860 private class RemoveAccountSession extends Session {
861 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800862 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
863 Account account) {
864 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800865 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700866 mAccount = account;
867 }
868
869 protected String toDebugString(long now) {
870 return super.toDebugString(now) + ", removeAccount"
871 + ", account " + mAccount;
872 }
873
874 public void run() throws RemoteException {
875 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
876 }
877
878 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700879 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
880 && !result.containsKey(AccountManager.KEY_INTENT)) {
881 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700882 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800883 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700884 }
885 IAccountManagerResponse response = getResponseAndClose();
886 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800887 if (Log.isLoggable(TAG, Log.VERBOSE)) {
888 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
889 + response);
890 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700891 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700892 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700893 try {
894 response.onResult(result2);
895 } catch (RemoteException e) {
896 // ignore
897 }
898 }
899 }
900 super.onResult(result);
901 }
902 }
903
Amith Yamasani04e0d262012-02-14 11:50:53 -0800904 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800905 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800906 removeAccountInternal(getUserAccountsForCaller(), account);
907 }
908
909 private void removeAccountInternal(UserAccounts accounts, Account account) {
910 synchronized (accounts.cacheLock) {
911 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800912 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
913 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800914 removeAccountFromCacheLocked(accounts, account);
915 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800916 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800917 if (accounts.userId == UserHandle.USER_OWNER) {
918 // Owner's account was removed, remove from any users that are sharing
919 // this account.
920 long id = Binder.clearCallingIdentity();
921 try {
922 List<UserInfo> users = mUserManager.getUsers(true);
923 for (UserInfo user : users) {
924 if (!user.isPrimary() && user.isRestricted()) {
925 removeSharedAccountAsUser(account, user.id);
926 }
927 }
928 } finally {
929 Binder.restoreCallingIdentity(id);
930 }
931 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700932 }
933
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400934 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700935 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800936 if (Log.isLoggable(TAG, Log.VERBOSE)) {
937 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
938 + ", caller's uid " + Binder.getCallingUid()
939 + ", pid " + Binder.getCallingPid());
940 }
Fred Quintana382601f2010-03-25 12:25:10 -0700941 if (accountType == null) throw new IllegalArgumentException("accountType is null");
942 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800943 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800944 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700945 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700946 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800947 synchronized (accounts.cacheLock) {
948 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800949 db.beginTransaction();
950 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800951 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800952 db.setTransactionSuccessful();
953 } finally {
954 db.endTransaction();
955 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700956 }
Fred Quintana60307342009-03-24 22:48:12 -0700957 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700958 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700959 }
960 }
961
Amith Yamasani04e0d262012-02-14 11:50:53 -0800962 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
963 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700964 if (authToken == null || accountType == null) {
965 return;
966 }
Fred Quintana33269202009-04-20 16:05:10 -0700967 Cursor cursor = db.rawQuery(
968 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
969 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
970 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
971 + " FROM " + TABLE_ACCOUNTS
972 + " JOIN " + TABLE_AUTHTOKENS
973 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
974 + " = " + AUTHTOKENS_ACCOUNTS_ID
975 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
976 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
977 new String[]{authToken, accountType});
978 try {
979 while (cursor.moveToNext()) {
980 long authTokenId = cursor.getLong(0);
981 String accountName = cursor.getString(1);
982 String authTokenType = cursor.getString(2);
983 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800984 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800985 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700986 }
Fred Quintana33269202009-04-20 16:05:10 -0700987 } finally {
988 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700989 }
990 }
991
Amith Yamasani04e0d262012-02-14 11:50:53 -0800992 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
993 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700994 if (account == null || type == null) {
995 return false;
996 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700997 cancelNotification(getSigninRequiredNotificationId(accounts, account),
998 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800999 synchronized (accounts.cacheLock) {
1000 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001001 db.beginTransaction();
1002 try {
1003 long accountId = getAccountIdLocked(db, account);
1004 if (accountId < 0) {
1005 return false;
1006 }
1007 db.delete(TABLE_AUTHTOKENS,
1008 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1009 new String[]{type});
1010 ContentValues values = new ContentValues();
1011 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1012 values.put(AUTHTOKENS_TYPE, type);
1013 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1014 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1015 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001016 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001017 return true;
1018 }
Fred Quintana33269202009-04-20 16:05:10 -07001019 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001020 } finally {
1021 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001022 }
Fred Quintana60307342009-03-24 22:48:12 -07001023 }
1024 }
1025
Fred Quintanaa698f422009-04-08 19:14:54 -07001026 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001027 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1028 Log.v(TAG, "peekAuthToken: " + account
1029 + ", authTokenType " + authTokenType
1030 + ", caller's uid " + Binder.getCallingUid()
1031 + ", pid " + Binder.getCallingPid());
1032 }
Fred Quintana382601f2010-03-25 12:25:10 -07001033 if (account == null) throw new IllegalArgumentException("account is null");
1034 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001035 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001036 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001037 long identityToken = clearCallingIdentity();
1038 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001039 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001040 } finally {
1041 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001042 }
Fred Quintana60307342009-03-24 22:48:12 -07001043 }
1044
Fred Quintanaa698f422009-04-08 19:14:54 -07001045 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001046 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1047 Log.v(TAG, "setAuthToken: " + account
1048 + ", authTokenType " + authTokenType
1049 + ", caller's uid " + Binder.getCallingUid()
1050 + ", pid " + Binder.getCallingPid());
1051 }
Fred Quintana382601f2010-03-25 12:25:10 -07001052 if (account == null) throw new IllegalArgumentException("account is null");
1053 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001054 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001055 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001056 long identityToken = clearCallingIdentity();
1057 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001058 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001059 } finally {
1060 restoreCallingIdentity(identityToken);
1061 }
Fred Quintana60307342009-03-24 22:48:12 -07001062 }
1063
Fred Quintanaa698f422009-04-08 19:14:54 -07001064 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001065 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1066 Log.v(TAG, "setAuthToken: " + account
1067 + ", caller's uid " + Binder.getCallingUid()
1068 + ", pid " + Binder.getCallingPid());
1069 }
Fred Quintana382601f2010-03-25 12:25:10 -07001070 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001071 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001072 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001073 long identityToken = clearCallingIdentity();
1074 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001075 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001076 } finally {
1077 restoreCallingIdentity(identityToken);
1078 }
Fred Quintana60307342009-03-24 22:48:12 -07001079 }
1080
Amith Yamasani04e0d262012-02-14 11:50:53 -08001081 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001082 if (account == null) {
1083 return;
1084 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001085 synchronized (accounts.cacheLock) {
1086 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001087 db.beginTransaction();
1088 try {
1089 final ContentValues values = new ContentValues();
1090 values.put(ACCOUNTS_PASSWORD, password);
1091 final long accountId = getAccountIdLocked(db, account);
1092 if (accountId >= 0) {
1093 final String[] argsAccountId = {String.valueOf(accountId)};
1094 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1095 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001096 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001097 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001098 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001099 } finally {
1100 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001101 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001102 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001103 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001104 }
1105
Amith Yamasani04e0d262012-02-14 11:50:53 -08001106 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001107 Log.i(TAG, "the accounts changed, sending broadcast of "
1108 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001109 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001110 }
1111
Fred Quintanaa698f422009-04-08 19:14:54 -07001112 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001113 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1114 Log.v(TAG, "clearPassword: " + account
1115 + ", caller's uid " + Binder.getCallingUid()
1116 + ", pid " + Binder.getCallingPid());
1117 }
Fred Quintana382601f2010-03-25 12:25:10 -07001118 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001119 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001120 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001121 long identityToken = clearCallingIdentity();
1122 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001123 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001124 } finally {
1125 restoreCallingIdentity(identityToken);
1126 }
Fred Quintana60307342009-03-24 22:48:12 -07001127 }
1128
Fred Quintanaa698f422009-04-08 19:14:54 -07001129 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001130 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1131 Log.v(TAG, "setUserData: " + account
1132 + ", key " + key
1133 + ", caller's uid " + Binder.getCallingUid()
1134 + ", pid " + Binder.getCallingPid());
1135 }
Fred Quintana382601f2010-03-25 12:25:10 -07001136 if (key == null) throw new IllegalArgumentException("key is null");
1137 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001138 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001139 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001140 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001141 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001142 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001143 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001144 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001145 }
1146 }
1147
Amith Yamasani04e0d262012-02-14 11:50:53 -08001148 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1149 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001150 if (account == null || key == null) {
1151 return;
1152 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001153 synchronized (accounts.cacheLock) {
1154 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001155 db.beginTransaction();
1156 try {
1157 long accountId = getAccountIdLocked(db, account);
1158 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001159 return;
1160 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001161 long extrasId = getExtrasIdLocked(db, accountId, key);
1162 if (extrasId < 0 ) {
1163 extrasId = insertExtraLocked(db, accountId, key, value);
1164 if (extrasId < 0) {
1165 return;
1166 }
1167 } else {
1168 ContentValues values = new ContentValues();
1169 values.put(EXTRAS_VALUE, value);
1170 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1171 return;
1172 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001173
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001174 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001175 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001176 db.setTransactionSuccessful();
1177 } finally {
1178 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001179 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001180 }
1181 }
1182
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001183 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001184 if (result == null) {
1185 Log.e(TAG, "the result is unexpectedly null", new Exception());
1186 }
1187 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1188 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1189 + response);
1190 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001191 try {
1192 response.onResult(result);
1193 } catch (RemoteException e) {
1194 // if the caller is dead then there is no one to care about remote
1195 // exceptions
1196 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1197 Log.v(TAG, "failure while notifying response", e);
1198 }
1199 }
1200 }
1201
Fred Quintanad9640ec2012-05-23 12:37:00 -07001202 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1203 final String authTokenType)
1204 throws RemoteException {
1205 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001206 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1207
Fred Quintanad9640ec2012-05-23 12:37:00 -07001208 final int callingUid = getCallingUid();
1209 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001210 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001211 throw new SecurityException("can only call from system");
1212 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001213 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001214 long identityToken = clearCallingIdentity();
1215 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001216 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001217 false /* stripAuthTokenFromResult */) {
1218 protected String toDebugString(long now) {
1219 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001220 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001221 + ", authTokenType " + authTokenType;
1222 }
1223
1224 public void run() throws RemoteException {
1225 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1226 }
1227
1228 public void onResult(Bundle result) {
1229 if (result != null) {
1230 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1231 Bundle bundle = new Bundle();
1232 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1233 super.onResult(bundle);
1234 return;
1235 } else {
1236 super.onResult(result);
1237 }
1238 }
1239 }.bind();
1240 } finally {
1241 restoreCallingIdentity(identityToken);
1242 }
1243 }
1244
Fred Quintanaa698f422009-04-08 19:14:54 -07001245 public void getAuthToken(IAccountManagerResponse response, final Account account,
1246 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001247 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001248 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1249 Log.v(TAG, "getAuthToken: " + account
1250 + ", response " + response
1251 + ", authTokenType " + authTokenType
1252 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1253 + ", expectActivityLaunch " + expectActivityLaunch
1254 + ", caller's uid " + Binder.getCallingUid()
1255 + ", pid " + Binder.getCallingPid());
1256 }
Fred Quintana382601f2010-03-25 12:25:10 -07001257 if (response == null) throw new IllegalArgumentException("response is null");
1258 if (account == null) throw new IllegalArgumentException("account is null");
1259 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001260 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001261 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001262 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1263 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1264 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001265 final boolean customTokens =
1266 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1267
Amith Yamasanid20ea2f2013-05-08 12:57:01 -07001268 // Check to see that the app is authorized to access the account, in case it's a
1269 // restricted account.
1270 if (!ArrayUtils.contains(getAccounts((String) null), account)) {
1271 throw new IllegalArgumentException("no such account");
1272 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001273 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001274 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001275 final boolean permissionGranted = customTokens ||
1276 permissionIsGranted(account, authTokenType, callerUid);
1277
Costin Manolachec6684f92011-01-14 11:25:39 -08001278 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1279 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001280 // let authenticator know the identity of the caller
1281 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1282 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1283 if (notifyOnAuthFailure) {
1284 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001285 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001286
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001287 long identityToken = clearCallingIdentity();
1288 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001289 // if the caller has permission, do the peek. otherwise go the more expensive
1290 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001291 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001292 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001293 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001294 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001295 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1296 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1297 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001298 onResult(response, result);
1299 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001300 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001301 }
1302
Amith Yamasani04e0d262012-02-14 11:50:53 -08001303 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001304 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001305 protected String toDebugString(long now) {
1306 if (loginOptions != null) loginOptions.keySet();
1307 return super.toDebugString(now) + ", getAuthToken"
1308 + ", " + account
1309 + ", authTokenType " + authTokenType
1310 + ", loginOptions " + loginOptions
1311 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1312 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001313
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001314 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001315 // If the caller doesn't have permission then create and return the
1316 // "grant permission" intent instead of the "getAuthToken" intent.
1317 if (!permissionGranted) {
1318 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1319 } else {
1320 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1321 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001322 }
1323
1324 public void onResult(Bundle result) {
1325 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001326 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001327 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1328 new AccountAuthenticatorResponse(this),
1329 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001330 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001331 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001332 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001333 onResult(bundle);
1334 return;
1335 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001336 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001337 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001338 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1339 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001340 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001341 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001342 "the type and name should not be empty");
1343 return;
1344 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001345 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001346 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001347 authTokenType, authToken);
1348 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001349 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001350
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001351 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001352 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001353 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001354 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001355 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001356 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001357 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001358 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001359 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001360 }.bind();
1361 } finally {
1362 restoreCallingIdentity(identityToken);
1363 }
Fred Quintana60307342009-03-24 22:48:12 -07001364 }
1365
Dianne Hackborn41203752012-08-31 14:05:51 -07001366 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1367 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001368 int uid = intent.getIntExtra(
1369 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1370 String authTokenType = intent.getStringExtra(
1371 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1372 String authTokenLabel = intent.getStringExtra(
1373 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1374
1375 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1376 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001377 final String titleAndSubtitle =
1378 mContext.getString(R.string.permission_request_notification_with_subtitle,
1379 account.name);
1380 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001381 String title = titleAndSubtitle;
1382 String subtitle = "";
1383 if (index > 0) {
1384 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001385 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001386 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001387 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001388 n.setLatestEventInfo(mContext, title, subtitle,
1389 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001390 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1391 installNotification(getCredentialPermissionNotificationId(
1392 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001393 }
1394
Costin Manolache5f383ad92010-12-02 16:44:46 -08001395 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1396 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001397
1398 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001399 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001400 // Since it was set in Eclair+ we can't change it without breaking apps using
1401 // the intent from a non-Activity context.
1402 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001403 intent.addCategory(
1404 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001405
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001406 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001407 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1408 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001409 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001410
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001411 return intent;
1412 }
1413
1414 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1415 int uid) {
1416 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001417 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001418 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001419 final Pair<Pair<Account, String>, Integer> key =
1420 new Pair<Pair<Account, String>, Integer>(
1421 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001422 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001423 if (id == null) {
1424 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001425 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001426 }
1427 }
1428 return id;
1429 }
1430
Amith Yamasani04e0d262012-02-14 11:50:53 -08001431 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001432 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001433 synchronized (accounts.signinRequiredNotificationIds) {
1434 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001435 if (id == null) {
1436 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001437 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001438 }
1439 }
1440 return id;
1441 }
1442
Amith Yamasani27db4682013-03-30 17:07:47 -07001443 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001444 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001445 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001446 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1447 Log.v(TAG, "addAccount: accountType " + accountType
1448 + ", response " + response
1449 + ", authTokenType " + authTokenType
1450 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1451 + ", expectActivityLaunch " + expectActivityLaunch
1452 + ", caller's uid " + Binder.getCallingUid()
1453 + ", pid " + Binder.getCallingPid());
1454 }
Fred Quintana382601f2010-03-25 12:25:10 -07001455 if (response == null) throw new IllegalArgumentException("response is null");
1456 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001457 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001458
Amith Yamasani71e6c692013-03-24 17:39:28 -07001459 // Is user disallowed from modifying accounts?
Amith Yamasani27db4682013-03-30 17:07:47 -07001460 if (!canUserModifyAccounts(Binder.getCallingUid())) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001461 try {
1462 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1463 "User is not allowed to add an account!");
1464 } catch (RemoteException re) {
1465 }
Amith Yamasani23c8b962013-04-10 13:37:18 -07001466 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1467 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1468 long identityToken = clearCallingIdentity();
1469 try {
1470 mContext.startActivityAsUser(cantAddAccount, UserHandle.CURRENT);
1471 } finally {
1472 restoreCallingIdentity(identityToken);
1473 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001474 return;
1475 }
1476
Amith Yamasani04e0d262012-02-14 11:50:53 -08001477 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001478 final int pid = Binder.getCallingPid();
1479 final int uid = Binder.getCallingUid();
1480 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1481 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1482 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1483
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001484 long identityToken = clearCallingIdentity();
1485 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001486 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001487 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001488 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001489 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001490 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001491 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001492
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001493 protected String toDebugString(long now) {
1494 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001495 + ", accountType " + accountType
1496 + ", requiredFeatures "
1497 + (requiredFeatures != null
1498 ? TextUtils.join(",", requiredFeatures)
1499 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001500 }
1501 }.bind();
1502 } finally {
1503 restoreCallingIdentity(identityToken);
1504 }
Fred Quintana60307342009-03-24 22:48:12 -07001505 }
1506
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001507 @Override
1508 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1509 final Account account, final Bundle options, final boolean expectActivityLaunch,
1510 int userId) {
1511 // Only allow the system process to read accounts of other users
1512 if (userId != UserHandle.getCallingUserId()
Amith Yamasani27db4682013-03-30 17:07:47 -07001513 && Binder.getCallingUid() != Process.myUid()) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001514 throw new SecurityException("User " + UserHandle.getCallingUserId()
1515 + " trying to confirm account credentials for " + userId);
1516 }
1517
Fred Quintana56285a62010-12-02 14:20:51 -08001518 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1519 Log.v(TAG, "confirmCredentials: " + account
1520 + ", response " + response
1521 + ", expectActivityLaunch " + expectActivityLaunch
1522 + ", caller's uid " + Binder.getCallingUid()
1523 + ", pid " + Binder.getCallingPid());
1524 }
Fred Quintana382601f2010-03-25 12:25:10 -07001525 if (response == null) throw new IllegalArgumentException("response is null");
1526 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001527 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001528 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001529 long identityToken = clearCallingIdentity();
1530 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001531 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001532 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001533 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001534 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001535 }
1536 protected String toDebugString(long now) {
1537 return super.toDebugString(now) + ", confirmCredentials"
1538 + ", " + account;
1539 }
1540 }.bind();
1541 } finally {
1542 restoreCallingIdentity(identityToken);
1543 }
Fred Quintana60307342009-03-24 22:48:12 -07001544 }
1545
Fred Quintanaa698f422009-04-08 19:14:54 -07001546 public void updateCredentials(IAccountManagerResponse response, final Account account,
1547 final String authTokenType, final boolean expectActivityLaunch,
1548 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001549 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1550 Log.v(TAG, "updateCredentials: " + account
1551 + ", response " + response
1552 + ", authTokenType " + authTokenType
1553 + ", expectActivityLaunch " + expectActivityLaunch
1554 + ", caller's uid " + Binder.getCallingUid()
1555 + ", pid " + Binder.getCallingPid());
1556 }
Fred Quintana382601f2010-03-25 12:25:10 -07001557 if (response == null) throw new IllegalArgumentException("response is null");
1558 if (account == null) throw new IllegalArgumentException("account is null");
1559 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001560 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001561 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001562 long identityToken = clearCallingIdentity();
1563 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001564 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001565 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001566 public void run() throws RemoteException {
1567 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1568 }
1569 protected String toDebugString(long now) {
1570 if (loginOptions != null) loginOptions.keySet();
1571 return super.toDebugString(now) + ", updateCredentials"
1572 + ", " + account
1573 + ", authTokenType " + authTokenType
1574 + ", loginOptions " + loginOptions;
1575 }
1576 }.bind();
1577 } finally {
1578 restoreCallingIdentity(identityToken);
1579 }
Fred Quintana60307342009-03-24 22:48:12 -07001580 }
1581
Fred Quintanaa698f422009-04-08 19:14:54 -07001582 public void editProperties(IAccountManagerResponse response, final String accountType,
1583 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001584 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1585 Log.v(TAG, "editProperties: accountType " + accountType
1586 + ", response " + response
1587 + ", expectActivityLaunch " + expectActivityLaunch
1588 + ", caller's uid " + Binder.getCallingUid()
1589 + ", pid " + Binder.getCallingPid());
1590 }
Fred Quintana382601f2010-03-25 12:25:10 -07001591 if (response == null) throw new IllegalArgumentException("response is null");
1592 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001593 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001594 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001595 long identityToken = clearCallingIdentity();
1596 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001597 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001598 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001599 public void run() throws RemoteException {
1600 mAuthenticator.editProperties(this, mAccountType);
1601 }
1602 protected String toDebugString(long now) {
1603 return super.toDebugString(now) + ", editProperties"
1604 + ", accountType " + accountType;
1605 }
1606 }.bind();
1607 } finally {
1608 restoreCallingIdentity(identityToken);
1609 }
Fred Quintana60307342009-03-24 22:48:12 -07001610 }
1611
Fred Quintana33269202009-04-20 16:05:10 -07001612 private class GetAccountsByTypeAndFeatureSession extends Session {
1613 private final String[] mFeatures;
1614 private volatile Account[] mAccountsOfType = null;
1615 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1616 private volatile int mCurrentAccount = 0;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001617 private int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001618
Amith Yamasani04e0d262012-02-14 11:50:53 -08001619 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001620 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001621 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001622 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001623 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001624 mFeatures = features;
1625 }
1626
1627 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001628 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001629 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1630 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001631 }
Fred Quintana33269202009-04-20 16:05:10 -07001632 // check whether each account matches the requested features
1633 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1634 mCurrentAccount = 0;
1635
1636 checkAccount();
1637 }
1638
1639 public void checkAccount() {
1640 if (mCurrentAccount >= mAccountsOfType.length) {
1641 sendResult();
1642 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001643 }
Fred Quintana33269202009-04-20 16:05:10 -07001644
Fred Quintana29e94b82010-03-10 12:11:51 -08001645 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1646 if (accountAuthenticator == null) {
1647 // It is possible that the authenticator has died, which is indicated by
1648 // mAuthenticator being set to null. If this happens then just abort.
1649 // There is no need to send back a result or error in this case since
1650 // that already happened when mAuthenticator was cleared.
1651 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1652 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1653 + " connected to the authenticator, " + toDebugString());
1654 }
1655 return;
1656 }
Fred Quintana33269202009-04-20 16:05:10 -07001657 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001658 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001659 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001660 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001661 }
1662 }
1663
1664 public void onResult(Bundle result) {
1665 mNumResults++;
1666 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001667 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001668 return;
1669 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001670 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001671 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1672 }
1673 mCurrentAccount++;
1674 checkAccount();
1675 }
1676
1677 public void sendResult() {
1678 IAccountManagerResponse response = getResponseAndClose();
1679 if (response != null) {
1680 try {
1681 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1682 for (int i = 0; i < accounts.length; i++) {
1683 accounts[i] = mAccountsWithFeatures.get(i);
1684 }
Fred Quintana56285a62010-12-02 14:20:51 -08001685 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1686 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1687 + response);
1688 }
Fred Quintana33269202009-04-20 16:05:10 -07001689 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001690 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001691 response.onResult(result);
1692 } catch (RemoteException e) {
1693 // if the caller is dead then there is no one to care about remote exceptions
1694 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1695 Log.v(TAG, "failure while notifying response", e);
1696 }
1697 }
1698 }
1699 }
1700
1701
1702 protected String toDebugString(long now) {
1703 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1704 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1705 }
1706 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001707
Amith Yamasani04e0d262012-02-14 11:50:53 -08001708 /**
1709 * Returns the accounts for a specific user
1710 * @hide
1711 */
1712 public Account[] getAccounts(int userId) {
1713 checkReadAccountsPermission();
1714 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001715 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001716 long identityToken = clearCallingIdentity();
1717 try {
1718 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001719 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001720 }
1721 } finally {
1722 restoreCallingIdentity(identityToken);
1723 }
1724 }
1725
Amith Yamasanif29f2362012-04-05 18:29:52 -07001726 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001727 * Returns accounts for all running users.
1728 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001729 * @hide
1730 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001731 public AccountAndUser[] getRunningAccounts() {
1732 final int[] runningUserIds;
1733 try {
1734 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1735 } catch (RemoteException e) {
1736 // Running in system_server; should never happen
1737 throw new RuntimeException(e);
1738 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001739 return getAccounts(runningUserIds);
1740 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001741
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001742 /** {@hide} */
1743 public AccountAndUser[] getAllAccounts() {
1744 final List<UserInfo> users = getUserManager().getUsers();
1745 final int[] userIds = new int[users.size()];
1746 for (int i = 0; i < userIds.length; i++) {
1747 userIds[i] = users.get(i).id;
1748 }
1749 return getAccounts(userIds);
1750 }
1751
1752 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001753 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1754 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001755 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001756 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001757 if (userAccounts == null) continue;
1758 synchronized (userAccounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001759 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
Amith Yamasani27db4682013-03-30 17:07:47 -07001760 Binder.getCallingUid(), null);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001761 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001762 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001763 }
1764 }
1765 }
1766 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001767
1768 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1769 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001770 }
1771
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001772 @Override
1773 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001774 return getAccountsAsUser(type, userId, null, -1);
1775 }
1776
1777 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
1778 int packageUid) {
1779 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001780 // Only allow the system process to read accounts of other users
1781 if (userId != UserHandle.getCallingUserId()
Amith Yamasani27db4682013-03-30 17:07:47 -07001782 && callingUid != Process.myUid()) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001783 throw new SecurityException("User " + UserHandle.getCallingUserId()
1784 + " trying to get account for " + userId);
1785 }
1786
Fred Quintana56285a62010-12-02 14:20:51 -08001787 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1788 Log.v(TAG, "getAccounts: accountType " + type
1789 + ", caller's uid " + Binder.getCallingUid()
1790 + ", pid " + Binder.getCallingPid());
1791 }
Amith Yamasani27db4682013-03-30 17:07:47 -07001792 // If the original calling app was using the framework account chooser activity, we'll
1793 // be passed in the original caller's uid here, which is what should be used for filtering.
1794 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
1795 callingUid = packageUid;
1796 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001797 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001798 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001799 long identityToken = clearCallingIdentity();
1800 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001801 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001802 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001803 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001804 } finally {
1805 restoreCallingIdentity(identityToken);
1806 }
1807 }
1808
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001809 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001810 public boolean addSharedAccountAsUser(Account account, int userId) {
1811 userId = handleIncomingUser(userId);
1812 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1813 ContentValues values = new ContentValues();
1814 values.put(ACCOUNTS_NAME, account.name);
1815 values.put(ACCOUNTS_TYPE, account.type);
1816 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1817 new String[] {account.name, account.type});
1818 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1819 if (accountId < 0) {
1820 Log.w(TAG, "insertAccountIntoDatabase: " + account
1821 + ", skipping the DB insert failed");
1822 return false;
1823 }
1824 return true;
1825 }
1826
1827 @Override
1828 public boolean removeSharedAccountAsUser(Account account, int userId) {
1829 userId = handleIncomingUser(userId);
1830 UserAccounts accounts = getUserAccounts(userId);
1831 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1832 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1833 new String[] {account.name, account.type});
1834 if (r > 0) {
1835 removeAccountInternal(accounts, account);
1836 }
1837 return r > 0;
1838 }
1839
1840 @Override
1841 public Account[] getSharedAccountsAsUser(int userId) {
1842 userId = handleIncomingUser(userId);
1843 UserAccounts accounts = getUserAccounts(userId);
1844 ArrayList<Account> accountList = new ArrayList<Account>();
1845 Cursor cursor = null;
1846 try {
1847 cursor = accounts.openHelper.getReadableDatabase()
1848 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1849 null, null, null, null, null);
1850 if (cursor != null && cursor.moveToFirst()) {
1851 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1852 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1853 do {
1854 accountList.add(new Account(cursor.getString(nameIndex),
1855 cursor.getString(typeIndex)));
1856 } while (cursor.moveToNext());
1857 }
1858 } finally {
1859 if (cursor != null) {
1860 cursor.close();
1861 }
1862 }
1863 Account[] accountArray = new Account[accountList.size()];
1864 accountList.toArray(accountArray);
1865 return accountArray;
1866 }
1867
1868 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001869 public Account[] getAccounts(String type) {
1870 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1871 }
1872
Amith Yamasani27db4682013-03-30 17:07:47 -07001873 @Override
1874 public Account[] getAccountsForPackage(String packageName, int uid) {
1875 int callingUid = Binder.getCallingUid();
1876 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
1877 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
1878 + callingUid + " with uid=" + uid);
1879 }
1880 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
1881 }
1882
Amith Yamasani3b458ad2013-04-18 18:40:07 -07001883 @Override
1884 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
1885 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
1886 int packageUid = -1;
1887 try {
1888 packageUid = AppGlobals.getPackageManager().getPackageUid(
1889 packageName, UserHandle.getCallingUserId());
1890 } catch (RemoteException re) {
1891 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
1892 return new Account[0];
1893 }
1894 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
1895 }
1896
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001897 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001898 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001899 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1900 Log.v(TAG, "getAccounts: accountType " + type
1901 + ", response " + response
1902 + ", features " + stringArrayToString(features)
1903 + ", caller's uid " + Binder.getCallingUid()
1904 + ", pid " + Binder.getCallingPid());
1905 }
Fred Quintana382601f2010-03-25 12:25:10 -07001906 if (response == null) throw new IllegalArgumentException("response is null");
1907 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001908 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001909 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001910 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001911 long identityToken = clearCallingIdentity();
1912 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001913 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001914 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001915 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001916 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001917 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001918 Bundle result = new Bundle();
1919 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1920 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001921 return;
1922 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001923 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
1924 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001925 } finally {
1926 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001927 }
1928 }
1929
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001930 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001931 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001932 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001933 try {
1934 if (cursor.moveToNext()) {
1935 return cursor.getLong(0);
1936 }
1937 return -1;
1938 } finally {
1939 cursor.close();
1940 }
1941 }
1942
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001943 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001944 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1945 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1946 new String[]{key}, null, null, null);
1947 try {
1948 if (cursor.moveToNext()) {
1949 return cursor.getLong(0);
1950 }
1951 return -1;
1952 } finally {
1953 cursor.close();
1954 }
1955 }
1956
Fred Quintanaa698f422009-04-08 19:14:54 -07001957 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001958 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001959 IAccountManagerResponse mResponse;
1960 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001961 final boolean mExpectActivityLaunch;
1962 final long mCreationTime;
1963
Fred Quintana33269202009-04-20 16:05:10 -07001964 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001965 private int mNumRequestContinued = 0;
1966 private int mNumErrors = 0;
1967
Fred Quintana60307342009-03-24 22:48:12 -07001968 IAccountAuthenticator mAuthenticator = null;
1969
Fred Quintana8570f742010-02-18 10:32:54 -08001970 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001971 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001972
Amith Yamasani04e0d262012-02-14 11:50:53 -08001973 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001974 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001975 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001976 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001977 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001978 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001979 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001980 mResponse = response;
1981 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001982 mExpectActivityLaunch = expectActivityLaunch;
1983 mCreationTime = SystemClock.elapsedRealtime();
1984 synchronized (mSessions) {
1985 mSessions.put(toString(), this);
1986 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001987 if (response != null) {
1988 try {
1989 response.asBinder().linkToDeath(this, 0 /* flags */);
1990 } catch (RemoteException e) {
1991 mResponse = null;
1992 binderDied();
1993 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001994 }
Fred Quintana60307342009-03-24 22:48:12 -07001995 }
1996
Fred Quintanaa698f422009-04-08 19:14:54 -07001997 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001998 if (mResponse == null) {
1999 // this session has already been closed
2000 return null;
2001 }
Fred Quintana60307342009-03-24 22:48:12 -07002002 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002003 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002004 return response;
2005 }
2006
Fred Quintanaa698f422009-04-08 19:14:54 -07002007 private void close() {
2008 synchronized (mSessions) {
2009 if (mSessions.remove(toString()) == null) {
2010 // the session was already closed, so bail out now
2011 return;
2012 }
2013 }
2014 if (mResponse != null) {
2015 // stop listening for response deaths
2016 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2017
2018 // clear this so that we don't accidentally send any further results
2019 mResponse = null;
2020 }
2021 cancelTimeout();
2022 unbind();
2023 }
2024
2025 public void binderDied() {
2026 mResponse = null;
2027 close();
2028 }
2029
2030 protected String toDebugString() {
2031 return toDebugString(SystemClock.elapsedRealtime());
2032 }
2033
2034 protected String toDebugString(long now) {
2035 return "Session: expectLaunch " + mExpectActivityLaunch
2036 + ", connected " + (mAuthenticator != null)
2037 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2038 + "/" + mNumErrors + ")"
2039 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2040 }
2041
Fred Quintana60307342009-03-24 22:48:12 -07002042 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002043 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2044 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2045 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002046 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002047 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002048 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002049 }
2050 }
2051
2052 private void unbind() {
2053 if (mAuthenticator != null) {
2054 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002055 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002056 }
2057 }
2058
2059 public void scheduleTimeout() {
2060 mMessageHandler.sendMessageDelayed(
2061 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2062 }
2063
2064 public void cancelTimeout() {
2065 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2066 }
2067
Fred Quintanab839afc2009-10-14 15:57:28 -07002068 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002069 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002070 try {
2071 run();
2072 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002073 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002074 "remote exception");
2075 }
Fred Quintana60307342009-03-24 22:48:12 -07002076 }
2077
Fred Quintanab839afc2009-10-14 15:57:28 -07002078 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002079 mAuthenticator = null;
2080 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002081 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002082 try {
2083 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2084 "disconnected");
2085 } catch (RemoteException e) {
2086 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2087 Log.v(TAG, "Session.onServiceDisconnected: "
2088 + "caught RemoteException while responding", e);
2089 }
2090 }
Fred Quintana60307342009-03-24 22:48:12 -07002091 }
2092 }
2093
Fred Quintanab839afc2009-10-14 15:57:28 -07002094 public abstract void run() throws RemoteException;
2095
Fred Quintana60307342009-03-24 22:48:12 -07002096 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002097 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002098 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002099 try {
2100 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2101 "timeout");
2102 } catch (RemoteException e) {
2103 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2104 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2105 e);
2106 }
2107 }
Fred Quintana60307342009-03-24 22:48:12 -07002108 }
2109 }
2110
Fred Quintanaa698f422009-04-08 19:14:54 -07002111 public void onResult(Bundle result) {
2112 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002113 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
2114 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2115 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002116 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2117 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002118 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2119 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002120 }
Fred Quintana60307342009-03-24 22:48:12 -07002121 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002122 IAccountManagerResponse response;
2123 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002124 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002125 response = mResponse;
2126 } else {
2127 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002128 }
Fred Quintana60307342009-03-24 22:48:12 -07002129 if (response != null) {
2130 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002131 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002132 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2133 Log.v(TAG, getClass().getSimpleName()
2134 + " calling onError() on response " + response);
2135 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002136 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002137 "null bundle returned");
2138 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002139 if (mStripAuthTokenFromResult) {
2140 result.remove(AccountManager.KEY_AUTHTOKEN);
2141 }
Fred Quintana56285a62010-12-02 14:20:51 -08002142 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2143 Log.v(TAG, getClass().getSimpleName()
2144 + " calling onResult() on response " + response);
2145 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002146 response.onResult(result);
2147 }
Fred Quintana60307342009-03-24 22:48:12 -07002148 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002149 // if the caller is dead then there is no one to care about remote exceptions
2150 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2151 Log.v(TAG, "failure while notifying response", e);
2152 }
Fred Quintana60307342009-03-24 22:48:12 -07002153 }
2154 }
2155 }
Fred Quintana60307342009-03-24 22:48:12 -07002156
Fred Quintanaa698f422009-04-08 19:14:54 -07002157 public void onRequestContinued() {
2158 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002159 }
2160
2161 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002162 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002163 IAccountManagerResponse response = getResponseAndClose();
2164 if (response != null) {
2165 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002166 Log.v(TAG, getClass().getSimpleName()
2167 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002168 }
2169 try {
2170 response.onError(errorCode, errorMessage);
2171 } catch (RemoteException e) {
2172 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2173 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2174 }
2175 }
2176 } else {
2177 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2178 Log.v(TAG, "Session.onError: already closed");
2179 }
Fred Quintana60307342009-03-24 22:48:12 -07002180 }
2181 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002182
2183 /**
2184 * find the component name for the authenticator and initiate a bind
2185 * if no authenticator or the bind fails then return false, otherwise return true
2186 */
2187 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002188 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2189 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2190 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002191 if (authenticatorInfo == null) {
2192 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2193 Log.v(TAG, "there is no authenticator for " + authenticatorType
2194 + ", bailing out");
2195 }
2196 return false;
2197 }
2198
2199 Intent intent = new Intent();
2200 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2201 intent.setComponent(authenticatorInfo.componentName);
2202 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2203 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2204 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002205 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2206 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002207 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2208 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2209 }
2210 return false;
2211 }
2212
2213
2214 return true;
2215 }
Fred Quintana60307342009-03-24 22:48:12 -07002216 }
2217
2218 private class MessageHandler extends Handler {
2219 MessageHandler(Looper looper) {
2220 super(looper);
2221 }
Costin Manolache3348f142009-09-29 18:58:36 -07002222
Fred Quintana60307342009-03-24 22:48:12 -07002223 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002224 switch (msg.what) {
2225 case MESSAGE_TIMED_OUT:
2226 Session session = (Session)msg.obj;
2227 session.onTimedOut();
2228 break;
2229
Amith Yamasani5be347b2013-03-31 17:44:31 -07002230 case MESSAGE_COPY_SHARED_ACCOUNT:
2231 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2232 break;
2233
Fred Quintana60307342009-03-24 22:48:12 -07002234 default:
2235 throw new IllegalStateException("unhandled message: " + msg.what);
2236 }
2237 }
2238 }
2239
Amith Yamasani04e0d262012-02-14 11:50:53 -08002240 private static String getDatabaseName(int userId) {
2241 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002242 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002243 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002244 // Migrate old file, if it exists, to the new location.
2245 // Make sure the new file doesn't already exist. A dummy file could have been
2246 // accidentally created in the old location, causing the new one to become corrupted
2247 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002248 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002249 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002250 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002251 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002252 if (!userDir.exists()) {
2253 if (!userDir.mkdirs()) {
2254 throw new IllegalStateException("User dir cannot be created: " + userDir);
2255 }
2256 }
2257 if (!oldFile.renameTo(databaseFile)) {
2258 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2259 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002260 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002261 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002262 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002263 }
2264
Amith Yamasani04e0d262012-02-14 11:50:53 -08002265 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002266
Amith Yamasani04e0d262012-02-14 11:50:53 -08002267 public DatabaseHelper(Context context, int userId) {
2268 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002269 }
2270
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002271 /**
2272 * This call needs to be made while the mCacheLock is held. The way to
2273 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2274 * @param db The database.
2275 */
Fred Quintana60307342009-03-24 22:48:12 -07002276 @Override
2277 public void onCreate(SQLiteDatabase db) {
2278 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2279 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2280 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2281 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2282 + ACCOUNTS_PASSWORD + " TEXT, "
2283 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2284
2285 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2286 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2287 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2288 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2289 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2290 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2291
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002292 createGrantsTable(db);
2293
Fred Quintana60307342009-03-24 22:48:12 -07002294 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2295 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2296 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2297 + EXTRAS_KEY + " TEXT NOT NULL, "
2298 + EXTRAS_VALUE + " TEXT, "
2299 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2300
2301 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2302 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2303 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002304
Amith Yamasani67df64b2012-12-14 12:09:36 -08002305 createSharedAccountsTable(db);
2306
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002307 createAccountsDeletionTrigger(db);
2308 }
2309
Amith Yamasani67df64b2012-12-14 12:09:36 -08002310 private void createSharedAccountsTable(SQLiteDatabase db) {
2311 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2312 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2313 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2314 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2315 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2316 }
2317
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002318 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002319 db.execSQL(""
2320 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2321 + " BEGIN"
2322 + " DELETE FROM " + TABLE_AUTHTOKENS
2323 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2324 + " DELETE FROM " + TABLE_EXTRAS
2325 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002326 + " DELETE FROM " + TABLE_GRANTS
2327 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002328 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002329 }
2330
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002331 private void createGrantsTable(SQLiteDatabase db) {
2332 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2333 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2334 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2335 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2336 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2337 + "," + GRANTS_GRANTEE_UID + "))");
2338 }
2339
Fred Quintana60307342009-03-24 22:48:12 -07002340 @Override
2341 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002342 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002343
Fred Quintanaa698f422009-04-08 19:14:54 -07002344 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002345 // no longer need to do anything since the work is done
2346 // when upgrading from version 2
2347 oldVersion++;
2348 }
2349
2350 if (oldVersion == 2) {
2351 createGrantsTable(db);
2352 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2353 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002354 oldVersion++;
2355 }
Costin Manolache3348f142009-09-29 18:58:36 -07002356
2357 if (oldVersion == 3) {
2358 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2359 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2360 oldVersion++;
2361 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002362
2363 if (oldVersion == 4) {
2364 createSharedAccountsTable(db);
2365 oldVersion++;
2366 }
2367
2368 if (oldVersion != newVersion) {
2369 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2370 }
Fred Quintana60307342009-03-24 22:48:12 -07002371 }
2372
2373 @Override
2374 public void onOpen(SQLiteDatabase db) {
2375 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2376 }
2377 }
2378
Fred Quintana60307342009-03-24 22:48:12 -07002379 public IBinder onBind(Intent intent) {
2380 return asBinder();
2381 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002382
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002383 /**
2384 * Searches array of arguments for the specified string
2385 * @param args array of argument strings
2386 * @param value value to search for
2387 * @return true if the value is contained in the array
2388 */
2389 private static boolean scanArgs(String[] args, String value) {
2390 if (args != null) {
2391 for (String arg : args) {
2392 if (value.equals(arg)) {
2393 return true;
2394 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002395 }
2396 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002397 return false;
2398 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002399
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002400 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002401 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002402 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2403 != PackageManager.PERMISSION_GRANTED) {
2404 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2405 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2406 + " without permission " + android.Manifest.permission.DUMP);
2407 return;
2408 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002409 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002410 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002411
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002412 final List<UserInfo> users = getUserManager().getUsers();
2413 for (UserInfo user : users) {
2414 ipw.println("User " + user + ":");
2415 ipw.increaseIndent();
2416 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2417 ipw.println();
2418 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002419 }
2420 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002421
Amith Yamasani04e0d262012-02-14 11:50:53 -08002422 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2423 String[] args, boolean isCheckinRequest) {
2424 synchronized (userAccounts.cacheLock) {
2425 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002426
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002427 if (isCheckinRequest) {
2428 // This is a checkin request. *Only* upload the account types and the count of each.
2429 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2430 null, null, ACCOUNTS_TYPE, null, null);
2431 try {
2432 while (cursor.moveToNext()) {
2433 // print type,count
2434 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2435 }
2436 } finally {
2437 if (cursor != null) {
2438 cursor.close();
2439 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002440 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002441 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002442 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002443 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002444 fout.println("Accounts: " + accounts.length);
2445 for (Account account : accounts) {
2446 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002447 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002448
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002449 fout.println();
2450 synchronized (mSessions) {
2451 final long now = SystemClock.elapsedRealtime();
2452 fout.println("Active Sessions: " + mSessions.size());
2453 for (Session session : mSessions.values()) {
2454 fout.println(" " + session.toDebugString(now));
2455 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002456 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002457
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002458 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002459 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002460 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002461 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002462 }
2463
Amith Yamasani04e0d262012-02-14 11:50:53 -08002464 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002465 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002466 long identityToken = clearCallingIdentity();
2467 try {
2468 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2469 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2470 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002471
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002472 if (intent.getComponent() != null &&
2473 GrantCredentialsPermissionActivity.class.getName().equals(
2474 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002475 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002476 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002477 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002478 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002479 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2480 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002481 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002482 final String notificationTitleFormat =
2483 mContext.getText(R.string.notification_title).toString();
2484 n.setLatestEventInfo(mContext,
2485 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002486 message, PendingIntent.getActivityAsUser(
2487 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002488 null, user));
2489 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002490 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002491 } finally {
2492 restoreCallingIdentity(identityToken);
2493 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002494 }
2495
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002496 protected void installNotification(final int notificationId, final Notification n,
2497 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002498 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002499 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002500 }
2501
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002502 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002503 long identityToken = clearCallingIdentity();
2504 try {
2505 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002506 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002507 } finally {
2508 restoreCallingIdentity(identityToken);
2509 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002510 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002511
Fred Quintanab38eb142010-02-24 13:40:54 -08002512 /** Succeeds if any of the specified permissions are granted. */
2513 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002514 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002515
2516 for (String perm : permissions) {
2517 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2518 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002519 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002520 }
2521 return;
2522 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002523 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002524
2525 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002526 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002527 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002528 }
2529
Amith Yamasani67df64b2012-12-14 12:09:36 -08002530 private int handleIncomingUser(int userId) {
2531 try {
2532 return ActivityManagerNative.getDefault().handleIncomingUser(
2533 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2534 } catch (RemoteException re) {
2535 // Shouldn't happen, local.
2536 }
2537 return userId;
2538 }
2539
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002540 private boolean inSystemImage(int callingUid) {
2541 final int callingUserId = UserHandle.getUserId(callingUid);
2542
2543 final PackageManager userPackageManager;
2544 try {
2545 userPackageManager = mContext.createPackageContextAsUser(
2546 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2547 } catch (NameNotFoundException e) {
2548 return false;
2549 }
2550
2551 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002552 for (String name : packages) {
2553 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002554 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002555 if (packageInfo != null
2556 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002557 return true;
2558 }
2559 } catch (PackageManager.NameNotFoundException e) {
2560 return false;
2561 }
2562 }
2563 return false;
2564 }
2565
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002566 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002567 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002568 final boolean fromAuthenticator = account != null
2569 && hasAuthenticatorUid(account.type, callerUid);
2570 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002571 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002572 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2573 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002574 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002575 + ": is authenticator? " + fromAuthenticator
2576 + ", has explicit permission? " + hasExplicitGrants);
2577 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002578 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002579 }
2580
Fred Quintana1a231912009-10-15 11:31:30 -07002581 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002582 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002583 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002584 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002585 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002586 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002587 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002588 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002589 }
2590 }
2591 return false;
2592 }
2593
Amith Yamasani04e0d262012-02-14 11:50:53 -08002594 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2595 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002596 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002597 return true;
2598 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002599 UserAccounts accounts = getUserAccountsForCaller();
2600 synchronized (accounts.cacheLock) {
2601 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2602 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002603 account.name, account.type};
2604 final boolean permissionGranted =
2605 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2606 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2607 // TODO: Skip this check when running automated tests. Replace this
2608 // with a more general solution.
2609 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002610 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002611 + " but ignoring since device is in test harness.");
2612 return true;
2613 }
2614 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002615 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002616 }
2617
2618 private void checkCallingUidAgainstAuthenticator(Account account) {
2619 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002620 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002621 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2622 Log.w(TAG, msg);
2623 throw new SecurityException(msg);
2624 }
2625 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2626 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2627 }
2628 }
2629
2630 private void checkAuthenticateAccountsPermission(Account account) {
2631 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2632 checkCallingUidAgainstAuthenticator(account);
2633 }
2634
2635 private void checkReadAccountsPermission() {
2636 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2637 }
2638
2639 private void checkManageAccountsPermission() {
2640 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2641 }
2642
Fred Quintanab38eb142010-02-24 13:40:54 -08002643 private void checkManageAccountsOrUseCredentialsPermissions() {
2644 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2645 Manifest.permission.USE_CREDENTIALS);
2646 }
2647
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002648 private boolean canUserModifyAccounts(int callingUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002649 if (callingUid != Process.myUid()) {
2650 if (getUserManager().getUserRestrictions(
2651 new UserHandle(UserHandle.getUserId(callingUid)))
2652 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002653 return false;
2654 }
2655 }
2656 return true;
2657 }
2658
Fred Quintanad9640ec2012-05-23 12:37:00 -07002659 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2660 throws RemoteException {
2661 final int callingUid = getCallingUid();
2662
Amith Yamasani27db4682013-03-30 17:07:47 -07002663 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002664 throw new SecurityException();
2665 }
2666
2667 if (value) {
2668 grantAppPermission(account, authTokenType, uid);
2669 } else {
2670 revokeAppPermission(account, authTokenType, uid);
2671 }
2672 }
2673
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002674 /**
2675 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2676 * <p>
2677 * Although this is public it can only be accessed via the AccountManagerService object
2678 * which is in the system. This means we don't need to protect it with permissions.
2679 * @hide
2680 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002681 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002682 if (account == null || authTokenType == null) {
2683 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002684 return;
2685 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002686 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002687 synchronized (accounts.cacheLock) {
2688 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002689 db.beginTransaction();
2690 try {
2691 long accountId = getAccountIdLocked(db, account);
2692 if (accountId >= 0) {
2693 ContentValues values = new ContentValues();
2694 values.put(GRANTS_ACCOUNTS_ID, accountId);
2695 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2696 values.put(GRANTS_GRANTEE_UID, uid);
2697 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2698 db.setTransactionSuccessful();
2699 }
2700 } finally {
2701 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002702 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002703 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2704 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002705 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002706 }
2707
2708 /**
2709 * Don't allow callers with the given uid permission to get credentials for
2710 * account/authTokenType.
2711 * <p>
2712 * Although this is public it can only be accessed via the AccountManagerService object
2713 * which is in the system. This means we don't need to protect it with permissions.
2714 * @hide
2715 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002716 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002717 if (account == null || authTokenType == null) {
2718 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002719 return;
2720 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002721 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002722 synchronized (accounts.cacheLock) {
2723 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002724 db.beginTransaction();
2725 try {
2726 long accountId = getAccountIdLocked(db, account);
2727 if (accountId >= 0) {
2728 db.delete(TABLE_GRANTS,
2729 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2730 + GRANTS_GRANTEE_UID + "=?",
2731 new String[]{String.valueOf(accountId), authTokenType,
2732 String.valueOf(uid)});
2733 db.setTransactionSuccessful();
2734 }
2735 } finally {
2736 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002737 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002738 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2739 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002740 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002741 }
Fred Quintana56285a62010-12-02 14:20:51 -08002742
2743 static final private String stringArrayToString(String[] value) {
2744 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2745 }
2746
Amith Yamasani04e0d262012-02-14 11:50:53 -08002747 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2748 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002749 if (oldAccountsForType != null) {
2750 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2751 for (Account curAccount : oldAccountsForType) {
2752 if (!curAccount.equals(account)) {
2753 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002754 }
2755 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002756 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002757 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002758 } else {
2759 Account[] newAccountsForType = new Account[newAccountsList.size()];
2760 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002761 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002762 }
Fred Quintana56285a62010-12-02 14:20:51 -08002763 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002764 accounts.userDataCache.remove(account);
2765 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002766 }
2767
2768 /**
2769 * This assumes that the caller has already checked that the account is not already present.
2770 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002771 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2772 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002773 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2774 Account[] newAccountsForType = new Account[oldLength + 1];
2775 if (accountsForType != null) {
2776 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002777 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002778 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002779 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002780 }
2781
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002782 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07002783 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002784 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07002785 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002786 return unfiltered;
2787 }
2788 if (mUserManager.getUserInfo(userAccounts.userId).isRestricted()) {
2789 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002790 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002791 // otherwise return non-shared accounts only.
2792 // This might be a temporary way to specify a whitelist
2793 String whiteList = mContext.getResources().getString(
2794 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2795 for (String packageName : packages) {
2796 if (whiteList.contains(";" + packageName + ";")) {
2797 return unfiltered;
2798 }
2799 }
2800 ArrayList<Account> allowed = new ArrayList<Account>();
2801 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2802 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002803 String requiredAccountType = "";
2804 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07002805 // If there's an explicit callingPackage specified, check if that package
2806 // opted in to see restricted accounts.
2807 if (callingPackage != null) {
2808 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002809 if (pi != null && pi.restrictedAccountType != null) {
2810 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07002811 }
2812 } else {
2813 // Otherwise check if the callingUid has a package that has opted in
2814 for (String packageName : packages) {
2815 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
2816 if (pi != null && pi.restrictedAccountType != null) {
2817 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07002818 break;
2819 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002820 }
2821 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002822 } catch (NameNotFoundException nnfe) {
2823 }
2824 for (Account account : unfiltered) {
2825 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002826 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002827 } else {
2828 boolean found = false;
2829 for (Account shared : sharedAccounts) {
2830 if (shared.equals(account)) {
2831 found = true;
2832 break;
2833 }
2834 }
2835 if (!found) {
2836 allowed.add(account);
2837 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002838 }
2839 }
2840 Account[] filtered = new Account[allowed.size()];
2841 allowed.toArray(filtered);
2842 return filtered;
2843 } else {
2844 return unfiltered;
2845 }
2846 }
2847
Amith Yamasani27db4682013-03-30 17:07:47 -07002848 /*
2849 * packageName can be null. If not null, it should be used to filter out restricted accounts
2850 * that the package is not allowed to access.
2851 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002852 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07002853 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002854 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002855 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002856 if (accounts == null) {
2857 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002858 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002859 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07002860 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002861 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002862 } else {
2863 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002864 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002865 totalLength += accounts.length;
2866 }
2867 if (totalLength == 0) {
2868 return EMPTY_ACCOUNT_ARRAY;
2869 }
2870 Account[] accounts = new Account[totalLength];
2871 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002872 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002873 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2874 accountsOfType.length);
2875 totalLength += accountsOfType.length;
2876 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002877 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002878 }
2879 }
2880
Amith Yamasani04e0d262012-02-14 11:50:53 -08002881 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2882 Account account, String key, String value) {
2883 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002884 if (userDataForAccount == null) {
2885 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002886 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002887 }
2888 if (value == null) {
2889 userDataForAccount.remove(key);
2890 } else {
2891 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002892 }
2893 }
2894
Amith Yamasani04e0d262012-02-14 11:50:53 -08002895 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2896 Account account, String key, String value) {
2897 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002898 if (authTokensForAccount == null) {
2899 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002900 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002901 }
2902 if (value == null) {
2903 authTokensForAccount.remove(key);
2904 } else {
2905 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002906 }
2907 }
2908
Amith Yamasani04e0d262012-02-14 11:50:53 -08002909 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2910 String authTokenType) {
2911 synchronized (accounts.cacheLock) {
2912 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002913 if (authTokensForAccount == null) {
2914 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002915 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002916 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002917 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002918 }
2919 return authTokensForAccount.get(authTokenType);
2920 }
2921 }
2922
Amith Yamasani04e0d262012-02-14 11:50:53 -08002923 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2924 synchronized (accounts.cacheLock) {
2925 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002926 if (userDataForAccount == null) {
2927 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002928 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002929 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002930 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002931 }
2932 return userDataForAccount.get(key);
2933 }
2934 }
2935
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002936 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2937 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002938 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002939 Cursor cursor = db.query(TABLE_EXTRAS,
2940 COLUMNS_EXTRAS_KEY_AND_VALUE,
2941 SELECTION_USERDATA_BY_ACCOUNT,
2942 new String[]{account.name, account.type},
2943 null, null, null);
2944 try {
2945 while (cursor.moveToNext()) {
2946 final String tmpkey = cursor.getString(0);
2947 final String value = cursor.getString(1);
2948 userDataForAccount.put(tmpkey, value);
2949 }
2950 } finally {
2951 cursor.close();
2952 }
2953 return userDataForAccount;
2954 }
2955
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002956 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2957 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002958 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002959 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2960 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2961 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2962 new String[]{account.name, account.type},
2963 null, null, null);
2964 try {
2965 while (cursor.moveToNext()) {
2966 final String type = cursor.getString(0);
2967 final String authToken = cursor.getString(1);
2968 authTokensForAccount.put(type, authToken);
2969 }
2970 } finally {
2971 cursor.close();
2972 }
2973 return authTokensForAccount;
2974 }
Fred Quintana60307342009-03-24 22:48:12 -07002975}