blob: cc43a9cce6efffd26a2f8991e17fdf08a0731e53 [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;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070050import android.content.pm.ResolveInfo;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070051import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070052import android.database.Cursor;
53import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070054import android.database.sqlite.SQLiteDatabase;
55import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070056import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070057import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080058import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070059import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070060import android.os.IBinder;
61import android.os.Looper;
62import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070063import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070064import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import android.os.RemoteException;
66import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070068import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.text.TextUtils;
70import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070071import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070072import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080073import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070074
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070075import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080076import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080077import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070078import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070079import com.google.android.collect.Lists;
80import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070081
Oscar Montemayora8529f62009-11-18 10:14:20 -080082import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070083import java.io.FileDescriptor;
84import java.io.PrintWriter;
85import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080086import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070087import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070088import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070089import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080090import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070091import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080092import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070093import java.util.concurrent.atomic.AtomicInteger;
94import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070095
Fred Quintana60307342009-03-24 22:48:12 -070096/**
97 * A system service that provides account, password, and authtoken management for all
98 * accounts on the device. Some of these calls are implemented with the help of the corresponding
99 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
100 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700101 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700102 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700103 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700104public class AccountManagerService
105 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800106 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700107 private static final String TAG = "AccountManagerService";
108
109 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
110 private static final String DATABASE_NAME = "accounts.db";
Amith Yamasani67df64b2012-12-14 12:09:36 -0800111 private static final int DATABASE_VERSION = 5;
Fred Quintana60307342009-03-24 22:48:12 -0700112
113 private final Context mContext;
114
Fred Quintana56285a62010-12-02 14:20:51 -0800115 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700116 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800117
Fred Quintana60307342009-03-24 22:48:12 -0700118 private final MessageHandler mMessageHandler;
119
120 // Messages that can be sent on mHandler
121 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700122 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700123
Fred Quintana56285a62010-12-02 14:20:51 -0800124 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700125
126 private static final String TABLE_ACCOUNTS = "accounts";
127 private static final String ACCOUNTS_ID = "_id";
128 private static final String ACCOUNTS_NAME = "name";
129 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700130 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700131 private static final String ACCOUNTS_PASSWORD = "password";
132
133 private static final String TABLE_AUTHTOKENS = "authtokens";
134 private static final String AUTHTOKENS_ID = "_id";
135 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
136 private static final String AUTHTOKENS_TYPE = "type";
137 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
138
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700139 private static final String TABLE_GRANTS = "grants";
140 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
141 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
142 private static final String GRANTS_GRANTEE_UID = "uid";
143
Fred Quintana60307342009-03-24 22:48:12 -0700144 private static final String TABLE_EXTRAS = "extras";
145 private static final String EXTRAS_ID = "_id";
146 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
147 private static final String EXTRAS_KEY = "key";
148 private static final String EXTRAS_VALUE = "value";
149
150 private static final String TABLE_META = "meta";
151 private static final String META_KEY = "key";
152 private static final String META_VALUE = "value";
153
Amith Yamasani67df64b2012-12-14 12:09:36 -0800154 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
155
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700156 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
157 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700158 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700159
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700160 private static final String COUNT_OF_MATCHING_GRANTS = ""
161 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
162 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
163 + " AND " + GRANTS_GRANTEE_UID + "=?"
164 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
165 + " AND " + ACCOUNTS_NAME + "=?"
166 + " AND " + ACCOUNTS_TYPE + "=?";
167
Fred Quintana56285a62010-12-02 14:20:51 -0800168 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
169 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
170 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
171 AUTHTOKENS_AUTHTOKEN};
172
173 private static final String SELECTION_USERDATA_BY_ACCOUNT =
174 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
175 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
176
Fred Quintanaa698f422009-04-08 19:14:54 -0700177 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700178 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
179
Amith Yamasani04e0d262012-02-14 11:50:53 -0800180 static class UserAccounts {
181 private final int userId;
182 private final DatabaseHelper openHelper;
183 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
184 credentialsPermissionNotificationIds =
185 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
186 private final HashMap<Account, Integer> signinRequiredNotificationIds =
187 new HashMap<Account, Integer>();
188 private final Object cacheLock = new Object();
189 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700190 private final HashMap<String, Account[]> accountCache =
191 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800192 /** protected by the {@link #cacheLock} */
193 private HashMap<Account, HashMap<String, String>> userDataCache =
194 new HashMap<Account, HashMap<String, String>>();
195 /** protected by the {@link #cacheLock} */
196 private HashMap<Account, HashMap<String, String>> authTokenCache =
197 new HashMap<Account, HashMap<String, String>>();
198
199 UserAccounts(Context context, int userId) {
200 this.userId = userId;
201 synchronized (cacheLock) {
202 openHelper = new DatabaseHelper(context, userId);
203 }
204 }
205 }
206
207 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
208
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700209 private static AtomicReference<AccountManagerService> sThis =
210 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700211 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700212
213 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700214 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700215 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
216 }
217
Fred Quintana56285a62010-12-02 14:20:51 -0800218
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700219 /**
220 * This should only be called by system code. One should only call this after the service
221 * has started.
222 * @return a reference to the AccountManagerService instance
223 * @hide
224 */
225 public static AccountManagerService getSingleton() {
226 return sThis.get();
227 }
Fred Quintana60307342009-03-24 22:48:12 -0700228
Fred Quintana56285a62010-12-02 14:20:51 -0800229 public AccountManagerService(Context context) {
230 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700231 }
232
Fred Quintana56285a62010-12-02 14:20:51 -0800233 public AccountManagerService(Context context, PackageManager packageManager,
234 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700235 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800236 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700237
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700238 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700239
Fred Quintana56285a62010-12-02 14:20:51 -0800240 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800241 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700242
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700243 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800244
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800245 IntentFilter intentFilter = new IntentFilter();
246 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
247 intentFilter.addDataScheme("package");
248 mContext.registerReceiver(new BroadcastReceiver() {
249 @Override
250 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800251 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800252 }
253 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800254
Amith Yamasani13593602012-03-22 16:16:17 -0700255 IntentFilter userFilter = new IntentFilter();
256 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800257 userFilter.addAction(Intent.ACTION_USER_STARTED);
258 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700259 @Override
260 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800261 String action = intent.getAction();
262 if (Intent.ACTION_USER_REMOVED.equals(action)) {
263 onUserRemoved(intent);
264 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
265 onUserStarted(intent);
266 }
Amith Yamasani13593602012-03-22 16:16:17 -0700267 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800268 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800269 }
270
Dianne Hackborn164371f2013-10-01 19:10:13 -0700271 @Override
272 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
273 throws RemoteException {
274 try {
275 return super.onTransact(code, data, reply, flags);
276 } catch (RuntimeException e) {
277 // The account manager only throws security exceptions, so let's
278 // log all others.
279 if (!(e instanceof SecurityException)) {
280 Slog.wtf(TAG, "Account Manager Crash", e);
281 }
282 throw e;
283 }
284 }
285
Kenny Root26ff6622012-07-30 12:58:03 -0700286 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700287 }
288
Amith Yamasani258848d2012-08-10 17:06:33 -0700289 private UserManager getUserManager() {
290 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700291 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700292 }
293 return mUserManager;
294 }
295
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700296 /* Caller should lock mUsers */
297 private UserAccounts initUserLocked(int userId) {
298 UserAccounts accounts = mUsers.get(userId);
299 if (accounts == null) {
300 accounts = new UserAccounts(mContext, userId);
301 mUsers.append(userId, accounts);
302 purgeOldGrants(accounts);
303 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800304 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700305 return accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800306 }
307
308 private void purgeOldGrantsAll() {
309 synchronized (mUsers) {
310 for (int i = 0; i < mUsers.size(); i++) {
311 purgeOldGrants(mUsers.valueAt(i));
312 }
313 }
314 }
315
316 private void purgeOldGrants(UserAccounts accounts) {
317 synchronized (accounts.cacheLock) {
318 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800319 final Cursor cursor = db.query(TABLE_GRANTS,
320 new String[]{GRANTS_GRANTEE_UID},
321 null, null, GRANTS_GRANTEE_UID, null, null);
322 try {
323 while (cursor.moveToNext()) {
324 final int uid = cursor.getInt(0);
325 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
326 if (packageExists) {
327 continue;
328 }
329 Log.d(TAG, "deleting grants for UID " + uid
330 + " because its package is no longer installed");
331 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
332 new String[]{Integer.toString(uid)});
333 }
334 } finally {
335 cursor.close();
336 }
337 }
338 }
339
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700340 /**
341 * Validate internal set of accounts against installed authenticators for
342 * given user. Clears cached authenticators before validating.
343 */
344 public void validateAccounts(int userId) {
345 final UserAccounts accounts = getUserAccounts(userId);
346
347 // Invalidate user-specific cache to make sure we catch any
348 // removed authenticators.
349 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
350 }
351
352 /**
353 * Validate internal set of accounts against installed authenticators for
354 * given user. Clear cached authenticators before validating when requested.
355 */
356 private void validateAccountsInternal(
357 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
358 if (invalidateAuthenticatorCache) {
359 mAuthenticatorCache.invalidateCache(accounts.userId);
360 }
361
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700362 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
363 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
364 mAuthenticatorCache.getAllServices(accounts.userId)) {
365 knownAuth.add(service.type);
366 }
367
Amith Yamasani04e0d262012-02-14 11:50:53 -0800368 synchronized (accounts.cacheLock) {
369 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800370 boolean accountDeleted = false;
371 Cursor cursor = db.query(TABLE_ACCOUNTS,
372 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
373 null, null, null, null, null);
374 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800375 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800376 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700377 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800378 while (cursor.moveToNext()) {
379 final long accountId = cursor.getLong(0);
380 final String accountType = cursor.getString(1);
381 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700382
383 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700384 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800385 + accountType + " no longer has a registered authenticator");
386 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
387 accountDeleted = true;
388 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800389 accounts.userDataCache.remove(account);
390 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800391 } else {
392 ArrayList<String> accountNames = accountNamesByType.get(accountType);
393 if (accountNames == null) {
394 accountNames = new ArrayList<String>();
395 accountNamesByType.put(accountType, accountNames);
396 }
397 accountNames.add(accountName);
398 }
399 }
Andy McFadden2f362292012-01-20 14:43:38 -0800400 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800401 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800402 final String accountType = cur.getKey();
403 final ArrayList<String> accountNames = cur.getValue();
404 final Account[] accountsForType = new Account[accountNames.size()];
405 int i = 0;
406 for (String accountName : accountNames) {
407 accountsForType[i] = new Account(accountName, accountType);
408 ++i;
409 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800410 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800411 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800412 } finally {
413 cursor.close();
414 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800415 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800416 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800417 }
418 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700419 }
420
Amith Yamasani04e0d262012-02-14 11:50:53 -0800421 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700422 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800423 }
424
425 protected UserAccounts getUserAccounts(int userId) {
426 synchronized (mUsers) {
427 UserAccounts accounts = mUsers.get(userId);
428 if (accounts == null) {
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700429 accounts = initUserLocked(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800430 mUsers.append(userId, accounts);
431 }
432 return accounts;
433 }
434 }
435
Amith Yamasani13593602012-03-22 16:16:17 -0700436 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700437 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700438 if (userId < 1) return;
439
440 UserAccounts accounts;
441 synchronized (mUsers) {
442 accounts = mUsers.get(userId);
443 mUsers.remove(userId);
444 }
445 if (accounts == null) {
446 File dbFile = new File(getDatabaseName(userId));
447 dbFile.delete();
448 return;
449 }
450
451 synchronized (accounts.cacheLock) {
452 accounts.openHelper.close();
453 File dbFile = new File(getDatabaseName(userId));
454 dbFile.delete();
455 }
456 }
457
Amith Yamasani67df64b2012-12-14 12:09:36 -0800458 private void onUserStarted(Intent intent) {
459 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
460 if (userId < 1) return;
461
462 // Check if there's a shared account that needs to be created as an account
463 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
464 if (sharedAccounts == null || sharedAccounts.length == 0) return;
465 Account[] accounts = getAccountsAsUser(null, userId);
466 for (Account sa : sharedAccounts) {
467 if (ArrayUtils.contains(accounts, sa)) continue;
468 // Account doesn't exist. Copy it now.
469 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
470 }
471 }
472
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700473 @Override
474 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700475 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700476 }
477
Fred Quintanaa698f422009-04-08 19:14:54 -0700478 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800479 if (Log.isLoggable(TAG, Log.VERBOSE)) {
480 Log.v(TAG, "getPassword: " + account
481 + ", caller's uid " + Binder.getCallingUid()
482 + ", pid " + Binder.getCallingPid());
483 }
Fred Quintana382601f2010-03-25 12:25:10 -0700484 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700485 checkAuthenticateAccountsPermission(account);
486
Amith Yamasani04e0d262012-02-14 11:50:53 -0800487 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700488 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700489 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800490 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700491 } finally {
492 restoreCallingIdentity(identityToken);
493 }
494 }
495
Amith Yamasani04e0d262012-02-14 11:50:53 -0800496 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700497 if (account == null) {
498 return null;
499 }
500
Amith Yamasani04e0d262012-02-14 11:50:53 -0800501 synchronized (accounts.cacheLock) {
502 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800503 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
504 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
505 new String[]{account.name, account.type}, null, null, null);
506 try {
507 if (cursor.moveToNext()) {
508 return cursor.getString(0);
509 }
510 return null;
511 } finally {
512 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700513 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700514 }
515 }
516
517 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800518 if (Log.isLoggable(TAG, Log.VERBOSE)) {
519 Log.v(TAG, "getUserData: " + account
520 + ", key " + key
521 + ", caller's uid " + Binder.getCallingUid()
522 + ", pid " + Binder.getCallingPid());
523 }
Fred Quintana382601f2010-03-25 12:25:10 -0700524 if (account == null) throw new IllegalArgumentException("account is null");
525 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700526 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800527 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700528 long identityToken = clearCallingIdentity();
529 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800530 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700531 } finally {
532 restoreCallingIdentity(identityToken);
533 }
534 }
535
Fred Quintana97889762009-06-15 12:29:24 -0700536 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800537 if (Log.isLoggable(TAG, Log.VERBOSE)) {
538 Log.v(TAG, "getAuthenticatorTypes: "
539 + "caller's uid " + Binder.getCallingUid()
540 + ", pid " + Binder.getCallingPid());
541 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700542 final int userId = UserHandle.getCallingUserId();
543 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700544 try {
Fred Quintana97889762009-06-15 12:29:24 -0700545 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700546 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700547 AuthenticatorDescription[] types =
548 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700549 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700550 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700551 : authenticatorCollection) {
552 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700553 i++;
554 }
555 return types;
556 } finally {
557 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700558 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700559 }
560
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700561 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700562 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800563 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700564 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800565 + ", caller's uid " + Binder.getCallingUid()
566 + ", pid " + Binder.getCallingPid());
567 }
Fred Quintana382601f2010-03-25 12:25:10 -0700568 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700569 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700570 /*
571 * Child users are not allowed to add accounts. Only the accounts that are
572 * shared by the parent profile can be added to child profile.
573 *
574 * TODO: Only allow accounts that were shared to be added by
575 * a limited user.
576 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700577
Amith Yamasani04e0d262012-02-14 11:50:53 -0800578 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700579 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700580 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700581 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800582 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700583 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700584 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700585 }
586 }
587
Amith Yamasani67df64b2012-12-14 12:09:36 -0800588 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
589 final UserAccounts fromAccounts = getUserAccounts(userFrom);
590 final UserAccounts toAccounts = getUserAccounts(userTo);
591 if (fromAccounts == null || toAccounts == null) {
592 return false;
593 }
594
595 long identityToken = clearCallingIdentity();
596 try {
597 new Session(fromAccounts, null, account.type, false,
598 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700599 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800600 protected String toDebugString(long now) {
601 return super.toDebugString(now) + ", getAccountCredentialsForClone"
602 + ", " + account.type;
603 }
604
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700605 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800606 public void run() throws RemoteException {
607 mAuthenticator.getAccountCredentialsForCloning(this, account);
608 }
609
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700610 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800611 public void onResult(Bundle result) {
612 if (result != null) {
613 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
614 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800615 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800616 }
617 return;
618 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800619 super.onResult(result);
620 }
621 }
622 }.bind();
623 } finally {
624 restoreCallingIdentity(identityToken);
625 }
626 return true;
627 }
628
Amith Yamasani67df64b2012-12-14 12:09:36 -0800629 void completeCloningAccount(final Bundle result, final Account account,
630 final UserAccounts targetUser) {
631 long id = clearCallingIdentity();
632 try {
633 new Session(targetUser, null, account.type, false,
634 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700635 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800636 protected String toDebugString(long now) {
637 return super.toDebugString(now) + ", getAccountCredentialsForClone"
638 + ", " + account.type;
639 }
640
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700641 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800642 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700643 // Confirm that the owner's account still exists before this step.
644 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
645 synchronized (owner.cacheLock) {
646 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
647 for (Account acc : ownerAccounts) {
648 if (acc.equals(account)) {
649 mAuthenticator.addAccountFromCredentials(this, account, result);
650 break;
651 }
652 }
653 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800654 }
655
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700656 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800657 public void onResult(Bundle result) {
658 if (result != null) {
659 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
660 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800661 } else {
662 // TODO: Show error notification
663 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800664 }
665 return;
666 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800667 super.onResult(result);
668 }
669 }
670
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700671 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800672 public void onError(int errorCode, String errorMessage) {
673 super.onError(errorCode, errorMessage);
674 // TODO: Show error notification to user
675 // TODO: Should we remove the shadow account so that it doesn't keep trying?
676 }
677
678 }.bind();
679 } finally {
680 restoreCallingIdentity(id);
681 }
682 }
683
Amith Yamasani04e0d262012-02-14 11:50:53 -0800684 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800685 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700686 if (account == null) {
687 return false;
688 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800689 synchronized (accounts.cacheLock) {
690 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800691 db.beginTransaction();
692 try {
693 long numMatches = DatabaseUtils.longForQuery(db,
694 "select count(*) from " + TABLE_ACCOUNTS
695 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
696 new String[]{account.name, account.type});
697 if (numMatches > 0) {
698 Log.w(TAG, "insertAccountIntoDatabase: " + account
699 + ", skipping since the account already exists");
700 return false;
701 }
702 ContentValues values = new ContentValues();
703 values.put(ACCOUNTS_NAME, account.name);
704 values.put(ACCOUNTS_TYPE, account.type);
705 values.put(ACCOUNTS_PASSWORD, password);
706 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
707 if (accountId < 0) {
708 Log.w(TAG, "insertAccountIntoDatabase: " + account
709 + ", skipping the DB insert failed");
710 return false;
711 }
712 if (extras != null) {
713 for (String key : extras.keySet()) {
714 final String value = extras.getString(key);
715 if (insertExtraLocked(db, accountId, key, value) < 0) {
716 Log.w(TAG, "insertAccountIntoDatabase: " + account
717 + ", skipping since insertExtra failed for key " + key);
718 return false;
719 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700720 }
721 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800722 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800723 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800724 } finally {
725 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700726 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800727 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700728 }
729 if (accounts.userId == UserHandle.USER_OWNER) {
730 addAccountToLimitedUsers(account);
731 }
732 return true;
733 }
734
735 /**
736 * Adds the account to all limited users as shared accounts. If the user is currently
737 * running, then clone the account too.
738 * @param account the account to share with limited users
739 */
740 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700741 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700742 for (UserInfo user : users) {
743 if (user.isRestricted()) {
744 addSharedAccountAsUser(account, user.id);
745 try {
746 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
747 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
748 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
749 account));
750 }
751 } catch (RemoteException re) {
752 // Shouldn't happen
753 }
754 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700755 }
756 }
757
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800758 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700759 ContentValues values = new ContentValues();
760 values.put(EXTRAS_KEY, key);
761 values.put(EXTRAS_ACCOUNTS_ID, accountId);
762 values.put(EXTRAS_VALUE, value);
763 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
764 }
765
Fred Quintana3084a6f2010-01-14 18:02:03 -0800766 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800767 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800768 if (Log.isLoggable(TAG, Log.VERBOSE)) {
769 Log.v(TAG, "hasFeatures: " + account
770 + ", response " + response
771 + ", features " + stringArrayToString(features)
772 + ", caller's uid " + Binder.getCallingUid()
773 + ", pid " + Binder.getCallingPid());
774 }
Fred Quintana382601f2010-03-25 12:25:10 -0700775 if (response == null) throw new IllegalArgumentException("response is null");
776 if (account == null) throw new IllegalArgumentException("account is null");
777 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800778 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800779 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800780 long identityToken = clearCallingIdentity();
781 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800782 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800783 } finally {
784 restoreCallingIdentity(identityToken);
785 }
786 }
787
788 private class TestFeaturesSession extends Session {
789 private final String[] mFeatures;
790 private final Account mAccount;
791
Amith Yamasani04e0d262012-02-14 11:50:53 -0800792 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800793 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800794 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800795 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800796 mFeatures = features;
797 mAccount = account;
798 }
799
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700800 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800801 public void run() throws RemoteException {
802 try {
803 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
804 } catch (RemoteException e) {
805 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
806 }
807 }
808
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700809 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800810 public void onResult(Bundle result) {
811 IAccountManagerResponse response = getResponseAndClose();
812 if (response != null) {
813 try {
814 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700815 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800816 return;
817 }
Fred Quintana56285a62010-12-02 14:20:51 -0800818 if (Log.isLoggable(TAG, Log.VERBOSE)) {
819 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
820 + response);
821 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800822 final Bundle newResult = new Bundle();
823 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
824 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
825 response.onResult(newResult);
826 } catch (RemoteException e) {
827 // if the caller is dead then there is no one to care about remote exceptions
828 if (Log.isLoggable(TAG, Log.VERBOSE)) {
829 Log.v(TAG, "failure while notifying response", e);
830 }
831 }
832 }
833 }
834
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700835 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800836 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800837 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800838 + ", " + mAccount
839 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
840 }
841 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800842
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700843 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800844 if (Log.isLoggable(TAG, Log.VERBOSE)) {
845 Log.v(TAG, "removeAccount: " + account
846 + ", response " + response
847 + ", caller's uid " + Binder.getCallingUid()
848 + ", pid " + Binder.getCallingPid());
849 }
Fred Quintana382601f2010-03-25 12:25:10 -0700850 if (response == null) throw new IllegalArgumentException("response is null");
851 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700852 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700853 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800854 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800855 if (!canUserModifyAccounts(Binder.getCallingUid())) {
856 try {
857 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
858 "User cannot modify accounts");
859 } catch (RemoteException re) {
860 }
861 }
862
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700863 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800864
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700865 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800866 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800867 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800868 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800869 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800870 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700871 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800872 }
873 }
874 }
875
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700876 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800877 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700878 } finally {
879 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700880 }
Fred Quintana60307342009-03-24 22:48:12 -0700881 }
882
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700883 private class RemoveAccountSession extends Session {
884 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800885 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
886 Account account) {
887 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800888 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700889 mAccount = account;
890 }
891
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700892 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700893 protected String toDebugString(long now) {
894 return super.toDebugString(now) + ", removeAccount"
895 + ", account " + mAccount;
896 }
897
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700898 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700899 public void run() throws RemoteException {
900 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
901 }
902
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700903 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700904 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700905 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
906 && !result.containsKey(AccountManager.KEY_INTENT)) {
907 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700908 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800909 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700910 }
911 IAccountManagerResponse response = getResponseAndClose();
912 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800913 if (Log.isLoggable(TAG, Log.VERBOSE)) {
914 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
915 + response);
916 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700917 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700918 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700919 try {
920 response.onResult(result2);
921 } catch (RemoteException e) {
922 // ignore
923 }
924 }
925 }
926 super.onResult(result);
927 }
928 }
929
Amith Yamasani04e0d262012-02-14 11:50:53 -0800930 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800931 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800932 removeAccountInternal(getUserAccountsForCaller(), account);
933 }
934
935 private void removeAccountInternal(UserAccounts accounts, Account account) {
936 synchronized (accounts.cacheLock) {
937 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800938 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
939 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800940 removeAccountFromCacheLocked(accounts, account);
941 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800942 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800943 if (accounts.userId == UserHandle.USER_OWNER) {
944 // Owner's account was removed, remove from any users that are sharing
945 // this account.
946 long id = Binder.clearCallingIdentity();
947 try {
948 List<UserInfo> users = mUserManager.getUsers(true);
949 for (UserInfo user : users) {
950 if (!user.isPrimary() && user.isRestricted()) {
951 removeSharedAccountAsUser(account, user.id);
952 }
953 }
954 } finally {
955 Binder.restoreCallingIdentity(id);
956 }
957 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700958 }
959
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400960 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700961 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800962 if (Log.isLoggable(TAG, Log.VERBOSE)) {
963 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
964 + ", caller's uid " + Binder.getCallingUid()
965 + ", pid " + Binder.getCallingPid());
966 }
Fred Quintana382601f2010-03-25 12:25:10 -0700967 if (accountType == null) throw new IllegalArgumentException("accountType is null");
968 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800969 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800970 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700971 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700972 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800973 synchronized (accounts.cacheLock) {
974 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800975 db.beginTransaction();
976 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800977 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800978 db.setTransactionSuccessful();
979 } finally {
980 db.endTransaction();
981 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700982 }
Fred Quintana60307342009-03-24 22:48:12 -0700983 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700984 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700985 }
986 }
987
Amith Yamasani04e0d262012-02-14 11:50:53 -0800988 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
989 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700990 if (authToken == null || accountType == null) {
991 return;
992 }
Fred Quintana33269202009-04-20 16:05:10 -0700993 Cursor cursor = db.rawQuery(
994 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
995 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
996 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
997 + " FROM " + TABLE_ACCOUNTS
998 + " JOIN " + TABLE_AUTHTOKENS
999 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1000 + " = " + AUTHTOKENS_ACCOUNTS_ID
1001 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1002 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1003 new String[]{authToken, accountType});
1004 try {
1005 while (cursor.moveToNext()) {
1006 long authTokenId = cursor.getLong(0);
1007 String accountName = cursor.getString(1);
1008 String authTokenType = cursor.getString(2);
1009 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001010 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001011 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -07001012 }
Fred Quintana33269202009-04-20 16:05:10 -07001013 } finally {
1014 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001015 }
1016 }
1017
Amith Yamasani04e0d262012-02-14 11:50:53 -08001018 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1019 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001020 if (account == null || type == null) {
1021 return false;
1022 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001023 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1024 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001025 synchronized (accounts.cacheLock) {
1026 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001027 db.beginTransaction();
1028 try {
1029 long accountId = getAccountIdLocked(db, account);
1030 if (accountId < 0) {
1031 return false;
1032 }
1033 db.delete(TABLE_AUTHTOKENS,
1034 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1035 new String[]{type});
1036 ContentValues values = new ContentValues();
1037 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1038 values.put(AUTHTOKENS_TYPE, type);
1039 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1040 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1041 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001042 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001043 return true;
1044 }
Fred Quintana33269202009-04-20 16:05:10 -07001045 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001046 } finally {
1047 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001048 }
Fred Quintana60307342009-03-24 22:48:12 -07001049 }
1050 }
1051
Fred Quintanaa698f422009-04-08 19:14:54 -07001052 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001053 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1054 Log.v(TAG, "peekAuthToken: " + account
1055 + ", authTokenType " + authTokenType
1056 + ", caller's uid " + Binder.getCallingUid()
1057 + ", pid " + Binder.getCallingPid());
1058 }
Fred Quintana382601f2010-03-25 12:25:10 -07001059 if (account == null) throw new IllegalArgumentException("account is null");
1060 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001061 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001062 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001063 long identityToken = clearCallingIdentity();
1064 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001065 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001066 } finally {
1067 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001068 }
Fred Quintana60307342009-03-24 22:48:12 -07001069 }
1070
Fred Quintanaa698f422009-04-08 19:14:54 -07001071 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001072 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1073 Log.v(TAG, "setAuthToken: " + account
1074 + ", authTokenType " + authTokenType
1075 + ", caller's uid " + Binder.getCallingUid()
1076 + ", pid " + Binder.getCallingPid());
1077 }
Fred Quintana382601f2010-03-25 12:25:10 -07001078 if (account == null) throw new IllegalArgumentException("account is null");
1079 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001080 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001081 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001082 long identityToken = clearCallingIdentity();
1083 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001084 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001085 } finally {
1086 restoreCallingIdentity(identityToken);
1087 }
Fred Quintana60307342009-03-24 22:48:12 -07001088 }
1089
Fred Quintanaa698f422009-04-08 19:14:54 -07001090 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001091 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1092 Log.v(TAG, "setAuthToken: " + account
1093 + ", caller's uid " + Binder.getCallingUid()
1094 + ", pid " + Binder.getCallingPid());
1095 }
Fred Quintana382601f2010-03-25 12:25:10 -07001096 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001097 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001098 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001099 long identityToken = clearCallingIdentity();
1100 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001101 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001102 } finally {
1103 restoreCallingIdentity(identityToken);
1104 }
Fred Quintana60307342009-03-24 22:48:12 -07001105 }
1106
Amith Yamasani04e0d262012-02-14 11:50:53 -08001107 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001108 if (account == null) {
1109 return;
1110 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001111 synchronized (accounts.cacheLock) {
1112 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001113 db.beginTransaction();
1114 try {
1115 final ContentValues values = new ContentValues();
1116 values.put(ACCOUNTS_PASSWORD, password);
1117 final long accountId = getAccountIdLocked(db, account);
1118 if (accountId >= 0) {
1119 final String[] argsAccountId = {String.valueOf(accountId)};
1120 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1121 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001122 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001123 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001124 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001125 } finally {
1126 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001127 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001128 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001129 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001130 }
1131
Amith Yamasani04e0d262012-02-14 11:50:53 -08001132 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001133 Log.i(TAG, "the accounts changed, sending broadcast of "
1134 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001135 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001136 }
1137
Fred Quintanaa698f422009-04-08 19:14:54 -07001138 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001139 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1140 Log.v(TAG, "clearPassword: " + account
1141 + ", caller's uid " + Binder.getCallingUid()
1142 + ", pid " + Binder.getCallingPid());
1143 }
Fred Quintana382601f2010-03-25 12:25:10 -07001144 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001145 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001146 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001147 long identityToken = clearCallingIdentity();
1148 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001149 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001150 } finally {
1151 restoreCallingIdentity(identityToken);
1152 }
Fred Quintana60307342009-03-24 22:48:12 -07001153 }
1154
Fred Quintanaa698f422009-04-08 19:14:54 -07001155 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001156 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1157 Log.v(TAG, "setUserData: " + account
1158 + ", key " + key
1159 + ", caller's uid " + Binder.getCallingUid()
1160 + ", pid " + Binder.getCallingPid());
1161 }
Fred Quintana382601f2010-03-25 12:25:10 -07001162 if (key == null) throw new IllegalArgumentException("key is null");
1163 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001164 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001165 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001166 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001167 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001168 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001169 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001170 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001171 }
1172 }
1173
Amith Yamasani04e0d262012-02-14 11:50:53 -08001174 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1175 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001176 if (account == null || key == null) {
1177 return;
1178 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001179 synchronized (accounts.cacheLock) {
1180 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001181 db.beginTransaction();
1182 try {
1183 long accountId = getAccountIdLocked(db, account);
1184 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001185 return;
1186 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001187 long extrasId = getExtrasIdLocked(db, accountId, key);
1188 if (extrasId < 0 ) {
1189 extrasId = insertExtraLocked(db, accountId, key, value);
1190 if (extrasId < 0) {
1191 return;
1192 }
1193 } else {
1194 ContentValues values = new ContentValues();
1195 values.put(EXTRAS_VALUE, value);
1196 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1197 return;
1198 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001199
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001200 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001201 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001202 db.setTransactionSuccessful();
1203 } finally {
1204 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001205 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001206 }
1207 }
1208
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001209 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001210 if (result == null) {
1211 Log.e(TAG, "the result is unexpectedly null", new Exception());
1212 }
1213 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1214 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1215 + response);
1216 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001217 try {
1218 response.onResult(result);
1219 } catch (RemoteException e) {
1220 // if the caller is dead then there is no one to care about remote
1221 // exceptions
1222 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1223 Log.v(TAG, "failure while notifying response", e);
1224 }
1225 }
1226 }
1227
Fred Quintanad9640ec2012-05-23 12:37:00 -07001228 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1229 final String authTokenType)
1230 throws RemoteException {
1231 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001232 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1233
Fred Quintanad9640ec2012-05-23 12:37:00 -07001234 final int callingUid = getCallingUid();
1235 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001236 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001237 throw new SecurityException("can only call from system");
1238 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001239 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001240 long identityToken = clearCallingIdentity();
1241 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001242 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001243 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001244 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001245 protected String toDebugString(long now) {
1246 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001247 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001248 + ", authTokenType " + authTokenType;
1249 }
1250
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001251 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001252 public void run() throws RemoteException {
1253 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1254 }
1255
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001256 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001257 public void onResult(Bundle result) {
1258 if (result != null) {
1259 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1260 Bundle bundle = new Bundle();
1261 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1262 super.onResult(bundle);
1263 return;
1264 } else {
1265 super.onResult(result);
1266 }
1267 }
1268 }.bind();
1269 } finally {
1270 restoreCallingIdentity(identityToken);
1271 }
1272 }
1273
Fred Quintanaa698f422009-04-08 19:14:54 -07001274 public void getAuthToken(IAccountManagerResponse response, final Account account,
1275 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001276 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001277 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1278 Log.v(TAG, "getAuthToken: " + account
1279 + ", response " + response
1280 + ", authTokenType " + authTokenType
1281 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1282 + ", expectActivityLaunch " + expectActivityLaunch
1283 + ", caller's uid " + Binder.getCallingUid()
1284 + ", pid " + Binder.getCallingPid());
1285 }
Fred Quintana382601f2010-03-25 12:25:10 -07001286 if (response == null) throw new IllegalArgumentException("response is null");
1287 if (account == null) throw new IllegalArgumentException("account is null");
1288 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001289 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001290 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001291 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1292 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1293 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001294 final boolean customTokens =
1295 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1296
Amith Yamasanid20ea2f2013-05-08 12:57:01 -07001297 // Check to see that the app is authorized to access the account, in case it's a
1298 // restricted account.
1299 if (!ArrayUtils.contains(getAccounts((String) null), account)) {
1300 throw new IllegalArgumentException("no such account");
1301 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001302 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001303 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001304 final boolean permissionGranted = customTokens ||
1305 permissionIsGranted(account, authTokenType, callerUid);
1306
Costin Manolachec6684f92011-01-14 11:25:39 -08001307 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1308 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001309 // let authenticator know the identity of the caller
1310 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1311 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1312 if (notifyOnAuthFailure) {
1313 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001314 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001315
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001316 long identityToken = clearCallingIdentity();
1317 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001318 // if the caller has permission, do the peek. otherwise go the more expensive
1319 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001320 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001321 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001322 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001323 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001324 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1325 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1326 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001327 onResult(response, result);
1328 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001329 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001330 }
1331
Amith Yamasani04e0d262012-02-14 11:50:53 -08001332 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001333 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001334 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001335 protected String toDebugString(long now) {
1336 if (loginOptions != null) loginOptions.keySet();
1337 return super.toDebugString(now) + ", getAuthToken"
1338 + ", " + account
1339 + ", authTokenType " + authTokenType
1340 + ", loginOptions " + loginOptions
1341 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1342 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001343
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001344 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001345 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001346 // If the caller doesn't have permission then create and return the
1347 // "grant permission" intent instead of the "getAuthToken" intent.
1348 if (!permissionGranted) {
1349 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1350 } else {
1351 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1352 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001353 }
1354
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001355 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001356 public void onResult(Bundle result) {
1357 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001358 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001359 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1360 new AccountAuthenticatorResponse(this),
1361 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001362 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001363 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001364 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001365 onResult(bundle);
1366 return;
1367 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001368 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001369 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001370 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1371 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001372 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001373 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001374 "the type and name should not be empty");
1375 return;
1376 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001377 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001378 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001379 authTokenType, authToken);
1380 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001381 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001382
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001383 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001384 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001385 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001386 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001387 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001388 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001389 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001390 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001391 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001392 }.bind();
1393 } finally {
1394 restoreCallingIdentity(identityToken);
1395 }
Fred Quintana60307342009-03-24 22:48:12 -07001396 }
1397
Dianne Hackborn41203752012-08-31 14:05:51 -07001398 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1399 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001400 int uid = intent.getIntExtra(
1401 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1402 String authTokenType = intent.getStringExtra(
1403 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1404 String authTokenLabel = intent.getStringExtra(
1405 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1406
1407 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1408 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001409 final String titleAndSubtitle =
1410 mContext.getString(R.string.permission_request_notification_with_subtitle,
1411 account.name);
1412 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001413 String title = titleAndSubtitle;
1414 String subtitle = "";
1415 if (index > 0) {
1416 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001417 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001418 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001419 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001420 n.setLatestEventInfo(mContext, title, subtitle,
1421 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001422 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1423 installNotification(getCredentialPermissionNotificationId(
1424 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001425 }
1426
Costin Manolache5f383ad92010-12-02 16:44:46 -08001427 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1428 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001429
1430 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001431 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001432 // Since it was set in Eclair+ we can't change it without breaking apps using
1433 // the intent from a non-Activity context.
1434 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001435 intent.addCategory(
1436 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001437
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001438 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001439 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1440 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001441 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001442
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001443 return intent;
1444 }
1445
1446 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1447 int uid) {
1448 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001449 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001450 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001451 final Pair<Pair<Account, String>, Integer> key =
1452 new Pair<Pair<Account, String>, Integer>(
1453 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001454 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001455 if (id == null) {
1456 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001457 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001458 }
1459 }
1460 return id;
1461 }
1462
Amith Yamasani04e0d262012-02-14 11:50:53 -08001463 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001464 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001465 synchronized (accounts.signinRequiredNotificationIds) {
1466 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001467 if (id == null) {
1468 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001469 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001470 }
1471 }
1472 return id;
1473 }
1474
Amith Yamasani27db4682013-03-30 17:07:47 -07001475 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001476 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001477 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001478 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1479 Log.v(TAG, "addAccount: accountType " + accountType
1480 + ", response " + response
1481 + ", authTokenType " + authTokenType
1482 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1483 + ", expectActivityLaunch " + expectActivityLaunch
1484 + ", caller's uid " + Binder.getCallingUid()
1485 + ", pid " + Binder.getCallingPid());
1486 }
Fred Quintana382601f2010-03-25 12:25:10 -07001487 if (response == null) throw new IllegalArgumentException("response is null");
1488 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001489 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001490
Amith Yamasani71e6c692013-03-24 17:39:28 -07001491 // Is user disallowed from modifying accounts?
Amith Yamasani27db4682013-03-30 17:07:47 -07001492 if (!canUserModifyAccounts(Binder.getCallingUid())) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001493 try {
1494 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1495 "User is not allowed to add an account!");
1496 } catch (RemoteException re) {
1497 }
Amith Yamasani23c8b962013-04-10 13:37:18 -07001498 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1499 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1500 long identityToken = clearCallingIdentity();
1501 try {
1502 mContext.startActivityAsUser(cantAddAccount, UserHandle.CURRENT);
1503 } finally {
1504 restoreCallingIdentity(identityToken);
1505 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001506 return;
1507 }
1508
Amith Yamasani04e0d262012-02-14 11:50:53 -08001509 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001510 final int pid = Binder.getCallingPid();
1511 final int uid = Binder.getCallingUid();
1512 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1513 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1514 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1515
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001516 long identityToken = clearCallingIdentity();
1517 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001518 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001519 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001520 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001521 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001522 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001523 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001524 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001525
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001526 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001527 protected String toDebugString(long now) {
1528 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001529 + ", accountType " + accountType
1530 + ", requiredFeatures "
1531 + (requiredFeatures != null
1532 ? TextUtils.join(",", requiredFeatures)
1533 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001534 }
1535 }.bind();
1536 } finally {
1537 restoreCallingIdentity(identityToken);
1538 }
Fred Quintana60307342009-03-24 22:48:12 -07001539 }
1540
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001541 @Override
1542 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1543 final Account account, final Bundle options, final boolean expectActivityLaunch,
1544 int userId) {
1545 // Only allow the system process to read accounts of other users
1546 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001547 && Binder.getCallingUid() != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001548 && mContext.checkCallingOrSelfPermission(
1549 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1550 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001551 throw new SecurityException("User " + UserHandle.getCallingUserId()
1552 + " trying to confirm account credentials for " + userId);
1553 }
1554
Fred Quintana56285a62010-12-02 14:20:51 -08001555 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1556 Log.v(TAG, "confirmCredentials: " + account
1557 + ", response " + response
1558 + ", expectActivityLaunch " + expectActivityLaunch
1559 + ", caller's uid " + Binder.getCallingUid()
1560 + ", pid " + Binder.getCallingPid());
1561 }
Fred Quintana382601f2010-03-25 12:25:10 -07001562 if (response == null) throw new IllegalArgumentException("response is null");
1563 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001564 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001565 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001566 long identityToken = clearCallingIdentity();
1567 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001568 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001569 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001570 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001571 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001572 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001573 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001574 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001575 protected String toDebugString(long now) {
1576 return super.toDebugString(now) + ", confirmCredentials"
1577 + ", " + account;
1578 }
1579 }.bind();
1580 } finally {
1581 restoreCallingIdentity(identityToken);
1582 }
Fred Quintana60307342009-03-24 22:48:12 -07001583 }
1584
Fred Quintanaa698f422009-04-08 19:14:54 -07001585 public void updateCredentials(IAccountManagerResponse response, final Account account,
1586 final String authTokenType, final boolean expectActivityLaunch,
1587 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001588 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1589 Log.v(TAG, "updateCredentials: " + account
1590 + ", response " + response
1591 + ", authTokenType " + authTokenType
1592 + ", expectActivityLaunch " + expectActivityLaunch
1593 + ", caller's uid " + Binder.getCallingUid()
1594 + ", pid " + Binder.getCallingPid());
1595 }
Fred Quintana382601f2010-03-25 12:25:10 -07001596 if (response == null) throw new IllegalArgumentException("response is null");
1597 if (account == null) throw new IllegalArgumentException("account is null");
1598 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001599 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001600 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001601 long identityToken = clearCallingIdentity();
1602 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001603 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001604 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001605 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001606 public void run() throws RemoteException {
1607 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1608 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001609 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001610 protected String toDebugString(long now) {
1611 if (loginOptions != null) loginOptions.keySet();
1612 return super.toDebugString(now) + ", updateCredentials"
1613 + ", " + account
1614 + ", authTokenType " + authTokenType
1615 + ", loginOptions " + loginOptions;
1616 }
1617 }.bind();
1618 } finally {
1619 restoreCallingIdentity(identityToken);
1620 }
Fred Quintana60307342009-03-24 22:48:12 -07001621 }
1622
Fred Quintanaa698f422009-04-08 19:14:54 -07001623 public void editProperties(IAccountManagerResponse response, final String accountType,
1624 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001625 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1626 Log.v(TAG, "editProperties: accountType " + accountType
1627 + ", response " + response
1628 + ", expectActivityLaunch " + expectActivityLaunch
1629 + ", caller's uid " + Binder.getCallingUid()
1630 + ", pid " + Binder.getCallingPid());
1631 }
Fred Quintana382601f2010-03-25 12:25:10 -07001632 if (response == null) throw new IllegalArgumentException("response is null");
1633 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001634 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001635 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001636 long identityToken = clearCallingIdentity();
1637 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001638 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001639 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001640 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001641 public void run() throws RemoteException {
1642 mAuthenticator.editProperties(this, mAccountType);
1643 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001644 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001645 protected String toDebugString(long now) {
1646 return super.toDebugString(now) + ", editProperties"
1647 + ", accountType " + accountType;
1648 }
1649 }.bind();
1650 } finally {
1651 restoreCallingIdentity(identityToken);
1652 }
Fred Quintana60307342009-03-24 22:48:12 -07001653 }
1654
Fred Quintana33269202009-04-20 16:05:10 -07001655 private class GetAccountsByTypeAndFeatureSession extends Session {
1656 private final String[] mFeatures;
1657 private volatile Account[] mAccountsOfType = null;
1658 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1659 private volatile int mCurrentAccount = 0;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001660 private int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001661
Amith Yamasani04e0d262012-02-14 11:50:53 -08001662 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001663 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001664 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001665 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001666 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001667 mFeatures = features;
1668 }
1669
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001670 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001671 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001672 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001673 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1674 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001675 }
Fred Quintana33269202009-04-20 16:05:10 -07001676 // check whether each account matches the requested features
1677 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1678 mCurrentAccount = 0;
1679
1680 checkAccount();
1681 }
1682
1683 public void checkAccount() {
1684 if (mCurrentAccount >= mAccountsOfType.length) {
1685 sendResult();
1686 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001687 }
Fred Quintana33269202009-04-20 16:05:10 -07001688
Fred Quintana29e94b82010-03-10 12:11:51 -08001689 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1690 if (accountAuthenticator == null) {
1691 // It is possible that the authenticator has died, which is indicated by
1692 // mAuthenticator being set to null. If this happens then just abort.
1693 // There is no need to send back a result or error in this case since
1694 // that already happened when mAuthenticator was cleared.
1695 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1696 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1697 + " connected to the authenticator, " + toDebugString());
1698 }
1699 return;
1700 }
Fred Quintana33269202009-04-20 16:05:10 -07001701 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001702 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001703 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001704 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001705 }
1706 }
1707
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001708 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001709 public void onResult(Bundle result) {
1710 mNumResults++;
1711 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001712 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001713 return;
1714 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001715 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001716 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1717 }
1718 mCurrentAccount++;
1719 checkAccount();
1720 }
1721
1722 public void sendResult() {
1723 IAccountManagerResponse response = getResponseAndClose();
1724 if (response != null) {
1725 try {
1726 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1727 for (int i = 0; i < accounts.length; i++) {
1728 accounts[i] = mAccountsWithFeatures.get(i);
1729 }
Fred Quintana56285a62010-12-02 14:20:51 -08001730 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1731 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1732 + response);
1733 }
Fred Quintana33269202009-04-20 16:05:10 -07001734 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001735 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001736 response.onResult(result);
1737 } catch (RemoteException e) {
1738 // if the caller is dead then there is no one to care about remote exceptions
1739 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1740 Log.v(TAG, "failure while notifying response", e);
1741 }
1742 }
1743 }
1744 }
1745
1746
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001747 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001748 protected String toDebugString(long now) {
1749 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1750 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1751 }
1752 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001753
Amith Yamasani04e0d262012-02-14 11:50:53 -08001754 /**
1755 * Returns the accounts for a specific user
1756 * @hide
1757 */
1758 public Account[] getAccounts(int userId) {
1759 checkReadAccountsPermission();
1760 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001761 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001762 long identityToken = clearCallingIdentity();
1763 try {
1764 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001765 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001766 }
1767 } finally {
1768 restoreCallingIdentity(identityToken);
1769 }
1770 }
1771
Amith Yamasanif29f2362012-04-05 18:29:52 -07001772 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001773 * Returns accounts for all running users.
1774 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001775 * @hide
1776 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001777 public AccountAndUser[] getRunningAccounts() {
1778 final int[] runningUserIds;
1779 try {
1780 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1781 } catch (RemoteException e) {
1782 // Running in system_server; should never happen
1783 throw new RuntimeException(e);
1784 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001785 return getAccounts(runningUserIds);
1786 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001787
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001788 /** {@hide} */
1789 public AccountAndUser[] getAllAccounts() {
1790 final List<UserInfo> users = getUserManager().getUsers();
1791 final int[] userIds = new int[users.size()];
1792 for (int i = 0; i < userIds.length; i++) {
1793 userIds[i] = users.get(i).id;
1794 }
1795 return getAccounts(userIds);
1796 }
1797
1798 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001799 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07001800 for (int userId : userIds) {
1801 UserAccounts userAccounts = getUserAccounts(userId);
1802 if (userAccounts == null) continue;
1803 synchronized (userAccounts.cacheLock) {
1804 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
1805 Binder.getCallingUid(), null);
1806 for (int a = 0; a < accounts.length; a++) {
1807 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001808 }
1809 }
1810 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001811
1812 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1813 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001814 }
1815
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001816 @Override
1817 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001818 return getAccountsAsUser(type, userId, null, -1);
1819 }
1820
1821 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
1822 int packageUid) {
1823 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001824 // Only allow the system process to read accounts of other users
1825 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001826 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001827 && mContext.checkCallingOrSelfPermission(
1828 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1829 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001830 throw new SecurityException("User " + UserHandle.getCallingUserId()
1831 + " trying to get account for " + userId);
1832 }
1833
Fred Quintana56285a62010-12-02 14:20:51 -08001834 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1835 Log.v(TAG, "getAccounts: accountType " + type
1836 + ", caller's uid " + Binder.getCallingUid()
1837 + ", pid " + Binder.getCallingPid());
1838 }
Amith Yamasani27db4682013-03-30 17:07:47 -07001839 // If the original calling app was using the framework account chooser activity, we'll
1840 // be passed in the original caller's uid here, which is what should be used for filtering.
1841 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
1842 callingUid = packageUid;
1843 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001844 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001845 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001846 long identityToken = clearCallingIdentity();
1847 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001848 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001849 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001850 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001851 } finally {
1852 restoreCallingIdentity(identityToken);
1853 }
1854 }
1855
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001856 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001857 public boolean addSharedAccountAsUser(Account account, int userId) {
1858 userId = handleIncomingUser(userId);
1859 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1860 ContentValues values = new ContentValues();
1861 values.put(ACCOUNTS_NAME, account.name);
1862 values.put(ACCOUNTS_TYPE, account.type);
1863 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1864 new String[] {account.name, account.type});
1865 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1866 if (accountId < 0) {
1867 Log.w(TAG, "insertAccountIntoDatabase: " + account
1868 + ", skipping the DB insert failed");
1869 return false;
1870 }
1871 return true;
1872 }
1873
1874 @Override
1875 public boolean removeSharedAccountAsUser(Account account, int userId) {
1876 userId = handleIncomingUser(userId);
1877 UserAccounts accounts = getUserAccounts(userId);
1878 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1879 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1880 new String[] {account.name, account.type});
1881 if (r > 0) {
1882 removeAccountInternal(accounts, account);
1883 }
1884 return r > 0;
1885 }
1886
1887 @Override
1888 public Account[] getSharedAccountsAsUser(int userId) {
1889 userId = handleIncomingUser(userId);
1890 UserAccounts accounts = getUserAccounts(userId);
1891 ArrayList<Account> accountList = new ArrayList<Account>();
1892 Cursor cursor = null;
1893 try {
1894 cursor = accounts.openHelper.getReadableDatabase()
1895 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1896 null, null, null, null, null);
1897 if (cursor != null && cursor.moveToFirst()) {
1898 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1899 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1900 do {
1901 accountList.add(new Account(cursor.getString(nameIndex),
1902 cursor.getString(typeIndex)));
1903 } while (cursor.moveToNext());
1904 }
1905 } finally {
1906 if (cursor != null) {
1907 cursor.close();
1908 }
1909 }
1910 Account[] accountArray = new Account[accountList.size()];
1911 accountList.toArray(accountArray);
1912 return accountArray;
1913 }
1914
1915 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001916 public Account[] getAccounts(String type) {
1917 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1918 }
1919
Amith Yamasani27db4682013-03-30 17:07:47 -07001920 @Override
1921 public Account[] getAccountsForPackage(String packageName, int uid) {
1922 int callingUid = Binder.getCallingUid();
1923 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
1924 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
1925 + callingUid + " with uid=" + uid);
1926 }
1927 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
1928 }
1929
Amith Yamasani3b458ad2013-04-18 18:40:07 -07001930 @Override
1931 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
1932 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
1933 int packageUid = -1;
1934 try {
1935 packageUid = AppGlobals.getPackageManager().getPackageUid(
1936 packageName, UserHandle.getCallingUserId());
1937 } catch (RemoteException re) {
1938 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
1939 return new Account[0];
1940 }
1941 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
1942 }
1943
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001944 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001945 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001946 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1947 Log.v(TAG, "getAccounts: accountType " + type
1948 + ", response " + response
1949 + ", features " + stringArrayToString(features)
1950 + ", caller's uid " + Binder.getCallingUid()
1951 + ", pid " + Binder.getCallingPid());
1952 }
Fred Quintana382601f2010-03-25 12:25:10 -07001953 if (response == null) throw new IllegalArgumentException("response is null");
1954 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001955 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001956 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001957 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001958 long identityToken = clearCallingIdentity();
1959 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001960 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001961 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001962 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001963 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001964 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001965 Bundle result = new Bundle();
1966 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1967 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001968 return;
1969 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001970 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
1971 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001972 } finally {
1973 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001974 }
1975 }
1976
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001977 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001978 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001979 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001980 try {
1981 if (cursor.moveToNext()) {
1982 return cursor.getLong(0);
1983 }
1984 return -1;
1985 } finally {
1986 cursor.close();
1987 }
1988 }
1989
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001990 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001991 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1992 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1993 new String[]{key}, null, null, null);
1994 try {
1995 if (cursor.moveToNext()) {
1996 return cursor.getLong(0);
1997 }
1998 return -1;
1999 } finally {
2000 cursor.close();
2001 }
2002 }
2003
Fred Quintanaa698f422009-04-08 19:14:54 -07002004 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002005 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002006 IAccountManagerResponse mResponse;
2007 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002008 final boolean mExpectActivityLaunch;
2009 final long mCreationTime;
2010
Fred Quintana33269202009-04-20 16:05:10 -07002011 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002012 private int mNumRequestContinued = 0;
2013 private int mNumErrors = 0;
2014
Fred Quintana60307342009-03-24 22:48:12 -07002015 IAccountAuthenticator mAuthenticator = null;
2016
Fred Quintana8570f742010-02-18 10:32:54 -08002017 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002018 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002019
Amith Yamasani04e0d262012-02-14 11:50:53 -08002020 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08002021 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07002022 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002023 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002024 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002025 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002026 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002027 mResponse = response;
2028 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002029 mExpectActivityLaunch = expectActivityLaunch;
2030 mCreationTime = SystemClock.elapsedRealtime();
2031 synchronized (mSessions) {
2032 mSessions.put(toString(), this);
2033 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002034 if (response != null) {
2035 try {
2036 response.asBinder().linkToDeath(this, 0 /* flags */);
2037 } catch (RemoteException e) {
2038 mResponse = null;
2039 binderDied();
2040 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002041 }
Fred Quintana60307342009-03-24 22:48:12 -07002042 }
2043
Fred Quintanaa698f422009-04-08 19:14:54 -07002044 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002045 if (mResponse == null) {
2046 // this session has already been closed
2047 return null;
2048 }
Fred Quintana60307342009-03-24 22:48:12 -07002049 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002050 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002051 return response;
2052 }
2053
Fred Quintanaa698f422009-04-08 19:14:54 -07002054 private void close() {
2055 synchronized (mSessions) {
2056 if (mSessions.remove(toString()) == null) {
2057 // the session was already closed, so bail out now
2058 return;
2059 }
2060 }
2061 if (mResponse != null) {
2062 // stop listening for response deaths
2063 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2064
2065 // clear this so that we don't accidentally send any further results
2066 mResponse = null;
2067 }
2068 cancelTimeout();
2069 unbind();
2070 }
2071
2072 public void binderDied() {
2073 mResponse = null;
2074 close();
2075 }
2076
2077 protected String toDebugString() {
2078 return toDebugString(SystemClock.elapsedRealtime());
2079 }
2080
2081 protected String toDebugString(long now) {
2082 return "Session: expectLaunch " + mExpectActivityLaunch
2083 + ", connected " + (mAuthenticator != null)
2084 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2085 + "/" + mNumErrors + ")"
2086 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2087 }
2088
Fred Quintana60307342009-03-24 22:48:12 -07002089 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002090 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2091 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2092 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002093 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002094 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002095 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002096 }
2097 }
2098
2099 private void unbind() {
2100 if (mAuthenticator != null) {
2101 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002102 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002103 }
2104 }
2105
2106 public void scheduleTimeout() {
2107 mMessageHandler.sendMessageDelayed(
2108 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2109 }
2110
2111 public void cancelTimeout() {
2112 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2113 }
2114
Fred Quintanab839afc2009-10-14 15:57:28 -07002115 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002116 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002117 try {
2118 run();
2119 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002120 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002121 "remote exception");
2122 }
Fred Quintana60307342009-03-24 22:48:12 -07002123 }
2124
Fred Quintanab839afc2009-10-14 15:57:28 -07002125 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002126 mAuthenticator = null;
2127 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002128 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002129 try {
2130 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2131 "disconnected");
2132 } catch (RemoteException e) {
2133 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2134 Log.v(TAG, "Session.onServiceDisconnected: "
2135 + "caught RemoteException while responding", e);
2136 }
2137 }
Fred Quintana60307342009-03-24 22:48:12 -07002138 }
2139 }
2140
Fred Quintanab839afc2009-10-14 15:57:28 -07002141 public abstract void run() throws RemoteException;
2142
Fred Quintana60307342009-03-24 22:48:12 -07002143 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002144 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002145 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002146 try {
2147 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2148 "timeout");
2149 } catch (RemoteException e) {
2150 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2151 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2152 e);
2153 }
2154 }
Fred Quintana60307342009-03-24 22:48:12 -07002155 }
2156 }
2157
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002158 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002159 public void onResult(Bundle result) {
2160 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002161 Intent intent = null;
2162 if (result != null
2163 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2164 /*
2165 * The Authenticator API allows third party authenticators to
2166 * supply arbitrary intents to other apps that they can run,
2167 * this can be very bad when those apps are in the system like
2168 * the System Settings.
2169 */
2170 PackageManager pm = mContext.getPackageManager();
2171 ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
2172 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2173 int authenticatorUid = Binder.getCallingUid();
2174 if (PackageManager.SIGNATURE_MATCH !=
2175 pm.checkSignatures(authenticatorUid, targetUid)) {
2176 throw new SecurityException(
2177 "Activity to be started with KEY_INTENT must " +
2178 "share Authenticator's signatures");
2179 }
2180 }
2181 if (result != null
2182 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002183 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2184 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002185 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2186 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002187 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2188 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002189 }
Fred Quintana60307342009-03-24 22:48:12 -07002190 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002191 IAccountManagerResponse response;
2192 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002193 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002194 response = mResponse;
2195 } else {
2196 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002197 }
Fred Quintana60307342009-03-24 22:48:12 -07002198 if (response != null) {
2199 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002200 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002201 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2202 Log.v(TAG, getClass().getSimpleName()
2203 + " calling onError() on response " + response);
2204 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002205 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002206 "null bundle returned");
2207 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002208 if (mStripAuthTokenFromResult) {
2209 result.remove(AccountManager.KEY_AUTHTOKEN);
2210 }
Fred Quintana56285a62010-12-02 14:20:51 -08002211 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2212 Log.v(TAG, getClass().getSimpleName()
2213 + " calling onResult() on response " + response);
2214 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002215 response.onResult(result);
2216 }
Fred Quintana60307342009-03-24 22:48:12 -07002217 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002218 // if the caller is dead then there is no one to care about remote exceptions
2219 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2220 Log.v(TAG, "failure while notifying response", e);
2221 }
Fred Quintana60307342009-03-24 22:48:12 -07002222 }
2223 }
2224 }
Fred Quintana60307342009-03-24 22:48:12 -07002225
Fred Quintanaa698f422009-04-08 19:14:54 -07002226 public void onRequestContinued() {
2227 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002228 }
2229
2230 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002231 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002232 IAccountManagerResponse response = getResponseAndClose();
2233 if (response != null) {
2234 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002235 Log.v(TAG, getClass().getSimpleName()
2236 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002237 }
2238 try {
2239 response.onError(errorCode, errorMessage);
2240 } catch (RemoteException e) {
2241 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2242 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2243 }
2244 }
2245 } else {
2246 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2247 Log.v(TAG, "Session.onError: already closed");
2248 }
Fred Quintana60307342009-03-24 22:48:12 -07002249 }
2250 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002251
2252 /**
2253 * find the component name for the authenticator and initiate a bind
2254 * if no authenticator or the bind fails then return false, otherwise return true
2255 */
2256 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002257 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2258 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2259 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002260 if (authenticatorInfo == null) {
2261 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2262 Log.v(TAG, "there is no authenticator for " + authenticatorType
2263 + ", bailing out");
2264 }
2265 return false;
2266 }
2267
2268 Intent intent = new Intent();
2269 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2270 intent.setComponent(authenticatorInfo.componentName);
2271 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2272 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2273 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002274 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2275 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002276 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2277 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2278 }
2279 return false;
2280 }
2281
2282
2283 return true;
2284 }
Fred Quintana60307342009-03-24 22:48:12 -07002285 }
2286
2287 private class MessageHandler extends Handler {
2288 MessageHandler(Looper looper) {
2289 super(looper);
2290 }
Costin Manolache3348f142009-09-29 18:58:36 -07002291
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002292 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002293 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002294 switch (msg.what) {
2295 case MESSAGE_TIMED_OUT:
2296 Session session = (Session)msg.obj;
2297 session.onTimedOut();
2298 break;
2299
Amith Yamasani5be347b2013-03-31 17:44:31 -07002300 case MESSAGE_COPY_SHARED_ACCOUNT:
2301 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2302 break;
2303
Fred Quintana60307342009-03-24 22:48:12 -07002304 default:
2305 throw new IllegalStateException("unhandled message: " + msg.what);
2306 }
2307 }
2308 }
2309
Amith Yamasani04e0d262012-02-14 11:50:53 -08002310 private static String getDatabaseName(int userId) {
2311 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002312 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002313 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002314 // Migrate old file, if it exists, to the new location.
2315 // Make sure the new file doesn't already exist. A dummy file could have been
2316 // accidentally created in the old location, causing the new one to become corrupted
2317 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002318 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002319 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002320 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002321 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002322 if (!userDir.exists()) {
2323 if (!userDir.mkdirs()) {
2324 throw new IllegalStateException("User dir cannot be created: " + userDir);
2325 }
2326 }
2327 if (!oldFile.renameTo(databaseFile)) {
2328 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2329 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002330 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002331 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002332 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002333 }
2334
Amith Yamasani04e0d262012-02-14 11:50:53 -08002335 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002336
Amith Yamasani04e0d262012-02-14 11:50:53 -08002337 public DatabaseHelper(Context context, int userId) {
2338 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002339 }
2340
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002341 /**
2342 * This call needs to be made while the mCacheLock is held. The way to
2343 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2344 * @param db The database.
2345 */
Fred Quintana60307342009-03-24 22:48:12 -07002346 @Override
2347 public void onCreate(SQLiteDatabase db) {
2348 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2349 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2350 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2351 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2352 + ACCOUNTS_PASSWORD + " TEXT, "
2353 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2354
2355 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2356 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2357 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2358 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2359 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2360 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2361
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002362 createGrantsTable(db);
2363
Fred Quintana60307342009-03-24 22:48:12 -07002364 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2365 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2366 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2367 + EXTRAS_KEY + " TEXT NOT NULL, "
2368 + EXTRAS_VALUE + " TEXT, "
2369 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2370
2371 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2372 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2373 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002374
Amith Yamasani67df64b2012-12-14 12:09:36 -08002375 createSharedAccountsTable(db);
2376
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002377 createAccountsDeletionTrigger(db);
2378 }
2379
Amith Yamasani67df64b2012-12-14 12:09:36 -08002380 private void createSharedAccountsTable(SQLiteDatabase db) {
2381 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2382 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2383 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2384 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2385 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2386 }
2387
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002388 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002389 db.execSQL(""
2390 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2391 + " BEGIN"
2392 + " DELETE FROM " + TABLE_AUTHTOKENS
2393 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2394 + " DELETE FROM " + TABLE_EXTRAS
2395 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002396 + " DELETE FROM " + TABLE_GRANTS
2397 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002398 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002399 }
2400
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002401 private void createGrantsTable(SQLiteDatabase db) {
2402 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2403 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2404 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2405 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2406 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2407 + "," + GRANTS_GRANTEE_UID + "))");
2408 }
2409
Fred Quintana60307342009-03-24 22:48:12 -07002410 @Override
2411 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002412 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002413
Fred Quintanaa698f422009-04-08 19:14:54 -07002414 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002415 // no longer need to do anything since the work is done
2416 // when upgrading from version 2
2417 oldVersion++;
2418 }
2419
2420 if (oldVersion == 2) {
2421 createGrantsTable(db);
2422 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2423 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002424 oldVersion++;
2425 }
Costin Manolache3348f142009-09-29 18:58:36 -07002426
2427 if (oldVersion == 3) {
2428 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2429 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2430 oldVersion++;
2431 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002432
2433 if (oldVersion == 4) {
2434 createSharedAccountsTable(db);
2435 oldVersion++;
2436 }
2437
2438 if (oldVersion != newVersion) {
2439 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2440 }
Fred Quintana60307342009-03-24 22:48:12 -07002441 }
2442
2443 @Override
2444 public void onOpen(SQLiteDatabase db) {
2445 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2446 }
2447 }
2448
Fred Quintana60307342009-03-24 22:48:12 -07002449 public IBinder onBind(Intent intent) {
2450 return asBinder();
2451 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002452
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002453 /**
2454 * Searches array of arguments for the specified string
2455 * @param args array of argument strings
2456 * @param value value to search for
2457 * @return true if the value is contained in the array
2458 */
2459 private static boolean scanArgs(String[] args, String value) {
2460 if (args != null) {
2461 for (String arg : args) {
2462 if (value.equals(arg)) {
2463 return true;
2464 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002465 }
2466 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002467 return false;
2468 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002469
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002470 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002471 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002472 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2473 != PackageManager.PERMISSION_GRANTED) {
2474 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2475 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2476 + " without permission " + android.Manifest.permission.DUMP);
2477 return;
2478 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002479 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002480 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002481
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002482 final List<UserInfo> users = getUserManager().getUsers();
2483 for (UserInfo user : users) {
2484 ipw.println("User " + user + ":");
2485 ipw.increaseIndent();
2486 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2487 ipw.println();
2488 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002489 }
2490 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002491
Amith Yamasani04e0d262012-02-14 11:50:53 -08002492 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2493 String[] args, boolean isCheckinRequest) {
2494 synchronized (userAccounts.cacheLock) {
2495 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002496
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002497 if (isCheckinRequest) {
2498 // This is a checkin request. *Only* upload the account types and the count of each.
2499 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2500 null, null, ACCOUNTS_TYPE, null, null);
2501 try {
2502 while (cursor.moveToNext()) {
2503 // print type,count
2504 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2505 }
2506 } finally {
2507 if (cursor != null) {
2508 cursor.close();
2509 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002510 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002511 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002512 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002513 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002514 fout.println("Accounts: " + accounts.length);
2515 for (Account account : accounts) {
2516 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002517 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002518
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002519 fout.println();
2520 synchronized (mSessions) {
2521 final long now = SystemClock.elapsedRealtime();
2522 fout.println("Active Sessions: " + mSessions.size());
2523 for (Session session : mSessions.values()) {
2524 fout.println(" " + session.toDebugString(now));
2525 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002526 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002527
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002528 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002529 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002530 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002531 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002532 }
2533
Amith Yamasani04e0d262012-02-14 11:50:53 -08002534 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002535 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002536 long identityToken = clearCallingIdentity();
2537 try {
2538 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2539 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2540 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002541
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002542 if (intent.getComponent() != null &&
2543 GrantCredentialsPermissionActivity.class.getName().equals(
2544 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002545 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002546 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002547 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002548 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002549 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2550 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002551 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002552 final String notificationTitleFormat =
2553 mContext.getText(R.string.notification_title).toString();
2554 n.setLatestEventInfo(mContext,
2555 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002556 message, PendingIntent.getActivityAsUser(
2557 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002558 null, user));
2559 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002560 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002561 } finally {
2562 restoreCallingIdentity(identityToken);
2563 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002564 }
2565
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002566 protected void installNotification(final int notificationId, final Notification n,
2567 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002568 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002569 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002570 }
2571
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002572 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002573 long identityToken = clearCallingIdentity();
2574 try {
2575 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002576 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002577 } finally {
2578 restoreCallingIdentity(identityToken);
2579 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002580 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002581
Fred Quintanab38eb142010-02-24 13:40:54 -08002582 /** Succeeds if any of the specified permissions are granted. */
2583 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002584 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002585
2586 for (String perm : permissions) {
2587 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2588 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002589 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002590 }
2591 return;
2592 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002593 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002594
2595 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002596 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002597 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002598 }
2599
Amith Yamasani67df64b2012-12-14 12:09:36 -08002600 private int handleIncomingUser(int userId) {
2601 try {
2602 return ActivityManagerNative.getDefault().handleIncomingUser(
2603 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2604 } catch (RemoteException re) {
2605 // Shouldn't happen, local.
2606 }
2607 return userId;
2608 }
2609
Christopher Tateccbf84f2013-05-08 15:25:41 -07002610 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002611 final int callingUserId = UserHandle.getUserId(callingUid);
2612
2613 final PackageManager userPackageManager;
2614 try {
2615 userPackageManager = mContext.createPackageContextAsUser(
2616 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2617 } catch (NameNotFoundException e) {
2618 return false;
2619 }
2620
2621 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002622 for (String name : packages) {
2623 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002624 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002625 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07002626 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002627 return true;
2628 }
2629 } catch (PackageManager.NameNotFoundException e) {
2630 return false;
2631 }
2632 }
2633 return false;
2634 }
2635
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002636 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07002637 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002638 final boolean fromAuthenticator = account != null
2639 && hasAuthenticatorUid(account.type, callerUid);
2640 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002641 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002642 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2643 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002644 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002645 + ": is authenticator? " + fromAuthenticator
2646 + ", has explicit permission? " + hasExplicitGrants);
2647 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07002648 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002649 }
2650
Fred Quintana1a231912009-10-15 11:31:30 -07002651 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002652 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002653 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002654 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002655 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002656 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002657 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002658 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002659 }
2660 }
2661 return false;
2662 }
2663
Amith Yamasani04e0d262012-02-14 11:50:53 -08002664 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2665 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002666 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002667 return true;
2668 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002669 UserAccounts accounts = getUserAccountsForCaller();
2670 synchronized (accounts.cacheLock) {
2671 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2672 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002673 account.name, account.type};
2674 final boolean permissionGranted =
2675 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2676 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2677 // TODO: Skip this check when running automated tests. Replace this
2678 // with a more general solution.
2679 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002680 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002681 + " but ignoring since device is in test harness.");
2682 return true;
2683 }
2684 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002685 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002686 }
2687
2688 private void checkCallingUidAgainstAuthenticator(Account account) {
2689 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002690 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002691 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2692 Log.w(TAG, msg);
2693 throw new SecurityException(msg);
2694 }
2695 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2696 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2697 }
2698 }
2699
2700 private void checkAuthenticateAccountsPermission(Account account) {
2701 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2702 checkCallingUidAgainstAuthenticator(account);
2703 }
2704
2705 private void checkReadAccountsPermission() {
2706 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2707 }
2708
2709 private void checkManageAccountsPermission() {
2710 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2711 }
2712
Fred Quintanab38eb142010-02-24 13:40:54 -08002713 private void checkManageAccountsOrUseCredentialsPermissions() {
2714 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2715 Manifest.permission.USE_CREDENTIALS);
2716 }
2717
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002718 private boolean canUserModifyAccounts(int callingUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002719 if (callingUid != Process.myUid()) {
2720 if (getUserManager().getUserRestrictions(
2721 new UserHandle(UserHandle.getUserId(callingUid)))
2722 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002723 return false;
2724 }
2725 }
2726 return true;
2727 }
2728
Fred Quintanad9640ec2012-05-23 12:37:00 -07002729 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2730 throws RemoteException {
2731 final int callingUid = getCallingUid();
2732
Amith Yamasani27db4682013-03-30 17:07:47 -07002733 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002734 throw new SecurityException();
2735 }
2736
2737 if (value) {
2738 grantAppPermission(account, authTokenType, uid);
2739 } else {
2740 revokeAppPermission(account, authTokenType, uid);
2741 }
2742 }
2743
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002744 /**
2745 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2746 * <p>
2747 * Although this is public it can only be accessed via the AccountManagerService object
2748 * which is in the system. This means we don't need to protect it with permissions.
2749 * @hide
2750 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002751 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002752 if (account == null || authTokenType == null) {
2753 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002754 return;
2755 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002756 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002757 synchronized (accounts.cacheLock) {
2758 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002759 db.beginTransaction();
2760 try {
2761 long accountId = getAccountIdLocked(db, account);
2762 if (accountId >= 0) {
2763 ContentValues values = new ContentValues();
2764 values.put(GRANTS_ACCOUNTS_ID, accountId);
2765 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2766 values.put(GRANTS_GRANTEE_UID, uid);
2767 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2768 db.setTransactionSuccessful();
2769 }
2770 } finally {
2771 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002772 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002773 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2774 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002775 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002776 }
2777
2778 /**
2779 * Don't allow callers with the given uid permission to get credentials for
2780 * account/authTokenType.
2781 * <p>
2782 * Although this is public it can only be accessed via the AccountManagerService object
2783 * which is in the system. This means we don't need to protect it with permissions.
2784 * @hide
2785 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002786 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002787 if (account == null || authTokenType == null) {
2788 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002789 return;
2790 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002791 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002792 synchronized (accounts.cacheLock) {
2793 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002794 db.beginTransaction();
2795 try {
2796 long accountId = getAccountIdLocked(db, account);
2797 if (accountId >= 0) {
2798 db.delete(TABLE_GRANTS,
2799 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2800 + GRANTS_GRANTEE_UID + "=?",
2801 new String[]{String.valueOf(accountId), authTokenType,
2802 String.valueOf(uid)});
2803 db.setTransactionSuccessful();
2804 }
2805 } finally {
2806 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002807 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002808 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2809 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002810 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002811 }
Fred Quintana56285a62010-12-02 14:20:51 -08002812
2813 static final private String stringArrayToString(String[] value) {
2814 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2815 }
2816
Amith Yamasani04e0d262012-02-14 11:50:53 -08002817 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2818 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002819 if (oldAccountsForType != null) {
2820 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2821 for (Account curAccount : oldAccountsForType) {
2822 if (!curAccount.equals(account)) {
2823 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002824 }
2825 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002826 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002827 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002828 } else {
2829 Account[] newAccountsForType = new Account[newAccountsList.size()];
2830 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002831 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002832 }
Fred Quintana56285a62010-12-02 14:20:51 -08002833 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002834 accounts.userDataCache.remove(account);
2835 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002836 }
2837
2838 /**
2839 * This assumes that the caller has already checked that the account is not already present.
2840 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002841 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2842 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002843 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2844 Account[] newAccountsForType = new Account[oldLength + 1];
2845 if (accountsForType != null) {
2846 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002847 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002848 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002849 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002850 }
2851
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002852 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07002853 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002854 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07002855 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002856 return unfiltered;
2857 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002858 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
2859 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002860 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002861 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002862 // otherwise return non-shared accounts only.
2863 // This might be a temporary way to specify a whitelist
2864 String whiteList = mContext.getResources().getString(
2865 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2866 for (String packageName : packages) {
2867 if (whiteList.contains(";" + packageName + ";")) {
2868 return unfiltered;
2869 }
2870 }
2871 ArrayList<Account> allowed = new ArrayList<Account>();
2872 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2873 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002874 String requiredAccountType = "";
2875 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07002876 // If there's an explicit callingPackage specified, check if that package
2877 // opted in to see restricted accounts.
2878 if (callingPackage != null) {
2879 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002880 if (pi != null && pi.restrictedAccountType != null) {
2881 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07002882 }
2883 } else {
2884 // Otherwise check if the callingUid has a package that has opted in
2885 for (String packageName : packages) {
2886 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
2887 if (pi != null && pi.restrictedAccountType != null) {
2888 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07002889 break;
2890 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002891 }
2892 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002893 } catch (NameNotFoundException nnfe) {
2894 }
2895 for (Account account : unfiltered) {
2896 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002897 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002898 } else {
2899 boolean found = false;
2900 for (Account shared : sharedAccounts) {
2901 if (shared.equals(account)) {
2902 found = true;
2903 break;
2904 }
2905 }
2906 if (!found) {
2907 allowed.add(account);
2908 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002909 }
2910 }
2911 Account[] filtered = new Account[allowed.size()];
2912 allowed.toArray(filtered);
2913 return filtered;
2914 } else {
2915 return unfiltered;
2916 }
2917 }
2918
Amith Yamasani27db4682013-03-30 17:07:47 -07002919 /*
2920 * packageName can be null. If not null, it should be used to filter out restricted accounts
2921 * that the package is not allowed to access.
2922 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002923 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07002924 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002925 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002926 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002927 if (accounts == null) {
2928 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002929 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002930 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07002931 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002932 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002933 } else {
2934 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002935 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002936 totalLength += accounts.length;
2937 }
2938 if (totalLength == 0) {
2939 return EMPTY_ACCOUNT_ARRAY;
2940 }
2941 Account[] accounts = new Account[totalLength];
2942 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002943 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002944 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2945 accountsOfType.length);
2946 totalLength += accountsOfType.length;
2947 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002948 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002949 }
2950 }
2951
Amith Yamasani04e0d262012-02-14 11:50:53 -08002952 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2953 Account account, String key, String value) {
2954 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002955 if (userDataForAccount == null) {
2956 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002957 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002958 }
2959 if (value == null) {
2960 userDataForAccount.remove(key);
2961 } else {
2962 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002963 }
2964 }
2965
Amith Yamasani04e0d262012-02-14 11:50:53 -08002966 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2967 Account account, String key, String value) {
2968 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002969 if (authTokensForAccount == null) {
2970 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002971 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002972 }
2973 if (value == null) {
2974 authTokensForAccount.remove(key);
2975 } else {
2976 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002977 }
2978 }
2979
Amith Yamasani04e0d262012-02-14 11:50:53 -08002980 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2981 String authTokenType) {
2982 synchronized (accounts.cacheLock) {
2983 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002984 if (authTokensForAccount == null) {
2985 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002986 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002987 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002988 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002989 }
2990 return authTokensForAccount.get(authTokenType);
2991 }
2992 }
2993
Amith Yamasani04e0d262012-02-14 11:50:53 -08002994 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2995 synchronized (accounts.cacheLock) {
2996 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002997 if (userDataForAccount == null) {
2998 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002999 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003000 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003001 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003002 }
3003 return userDataForAccount.get(key);
3004 }
3005 }
3006
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003007 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3008 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003009 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003010 Cursor cursor = db.query(TABLE_EXTRAS,
3011 COLUMNS_EXTRAS_KEY_AND_VALUE,
3012 SELECTION_USERDATA_BY_ACCOUNT,
3013 new String[]{account.name, account.type},
3014 null, null, null);
3015 try {
3016 while (cursor.moveToNext()) {
3017 final String tmpkey = cursor.getString(0);
3018 final String value = cursor.getString(1);
3019 userDataForAccount.put(tmpkey, value);
3020 }
3021 } finally {
3022 cursor.close();
3023 }
3024 return userDataForAccount;
3025 }
3026
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003027 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3028 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003029 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003030 Cursor cursor = db.query(TABLE_AUTHTOKENS,
3031 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3032 SELECTION_AUTHTOKENS_BY_ACCOUNT,
3033 new String[]{account.name, account.type},
3034 null, null, null);
3035 try {
3036 while (cursor.moveToNext()) {
3037 final String type = cursor.getString(0);
3038 final String authToken = cursor.getString(1);
3039 authTokensForAccount.put(type, authToken);
3040 }
3041 } finally {
3042 cursor.close();
3043 }
3044 return authTokensForAccount;
3045 }
Fred Quintana60307342009-03-24 22:48:12 -07003046}