blob: 3a3dfd5f1c0484bec96e9760d6fbdd71c120fbac [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;
Amith Yamasani27db4682013-03-30 17:07:47 -070063import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070064import android.os.RemoteException;
65import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070067import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070068import android.text.TextUtils;
69import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070070import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070071import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080072import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070073
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070074import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080075import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080076import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070077import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070078import com.google.android.collect.Lists;
79import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070080
Oscar Montemayora8529f62009-11-18 10:14:20 -080081import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070082import java.io.FileDescriptor;
83import java.io.PrintWriter;
84import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080085import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070086import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070087import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070088import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080089import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070090import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080091import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070092import java.util.concurrent.atomic.AtomicInteger;
93import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070094
Fred Quintana60307342009-03-24 22:48:12 -070095/**
96 * A system service that provides account, password, and authtoken management for all
97 * accounts on the device. Some of these calls are implemented with the help of the corresponding
98 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
99 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700100 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700101 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700102 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700103public class AccountManagerService
104 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800105 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700106 private static final String TAG = "AccountManagerService";
107
108 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
109 private static final String DATABASE_NAME = "accounts.db";
Amith Yamasani67df64b2012-12-14 12:09:36 -0800110 private static final int DATABASE_VERSION = 5;
Fred Quintana60307342009-03-24 22:48:12 -0700111
112 private final Context mContext;
113
Fred Quintana56285a62010-12-02 14:20:51 -0800114 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700115 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800116
Fred Quintana60307342009-03-24 22:48:12 -0700117 private final MessageHandler mMessageHandler;
118
119 // Messages that can be sent on mHandler
120 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700121 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700122
Fred Quintana56285a62010-12-02 14:20:51 -0800123 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700124
125 private static final String TABLE_ACCOUNTS = "accounts";
126 private static final String ACCOUNTS_ID = "_id";
127 private static final String ACCOUNTS_NAME = "name";
128 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700129 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700130 private static final String ACCOUNTS_PASSWORD = "password";
131
132 private static final String TABLE_AUTHTOKENS = "authtokens";
133 private static final String AUTHTOKENS_ID = "_id";
134 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
135 private static final String AUTHTOKENS_TYPE = "type";
136 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
137
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700138 private static final String TABLE_GRANTS = "grants";
139 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
140 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
141 private static final String GRANTS_GRANTEE_UID = "uid";
142
Fred Quintana60307342009-03-24 22:48:12 -0700143 private static final String TABLE_EXTRAS = "extras";
144 private static final String EXTRAS_ID = "_id";
145 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
146 private static final String EXTRAS_KEY = "key";
147 private static final String EXTRAS_VALUE = "value";
148
149 private static final String TABLE_META = "meta";
150 private static final String META_KEY = "key";
151 private static final String META_VALUE = "value";
152
Amith Yamasani67df64b2012-12-14 12:09:36 -0800153 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
154
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700155 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
156 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700157 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700158
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700159 private static final String COUNT_OF_MATCHING_GRANTS = ""
160 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
161 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
162 + " AND " + GRANTS_GRANTEE_UID + "=?"
163 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
164 + " AND " + ACCOUNTS_NAME + "=?"
165 + " AND " + ACCOUNTS_TYPE + "=?";
166
Fred Quintana56285a62010-12-02 14:20:51 -0800167 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
168 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
169 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
170 AUTHTOKENS_AUTHTOKEN};
171
172 private static final String SELECTION_USERDATA_BY_ACCOUNT =
173 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
174 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
175
Fred Quintanaa698f422009-04-08 19:14:54 -0700176 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700177 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
178
Amith Yamasani04e0d262012-02-14 11:50:53 -0800179 static class UserAccounts {
180 private final int userId;
181 private final DatabaseHelper openHelper;
182 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
183 credentialsPermissionNotificationIds =
184 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
185 private final HashMap<Account, Integer> signinRequiredNotificationIds =
186 new HashMap<Account, Integer>();
187 private final Object cacheLock = new Object();
188 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700189 private final HashMap<String, Account[]> accountCache =
190 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800191 /** protected by the {@link #cacheLock} */
192 private HashMap<Account, HashMap<String, String>> userDataCache =
193 new HashMap<Account, HashMap<String, String>>();
194 /** protected by the {@link #cacheLock} */
195 private HashMap<Account, HashMap<String, String>> authTokenCache =
196 new HashMap<Account, HashMap<String, String>>();
197
198 UserAccounts(Context context, int userId) {
199 this.userId = userId;
200 synchronized (cacheLock) {
201 openHelper = new DatabaseHelper(context, userId);
202 }
203 }
204 }
205
206 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
207
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700208 private static AtomicReference<AccountManagerService> sThis =
209 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700210 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700211
212 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700213 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700214 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
215 }
216
Fred Quintana56285a62010-12-02 14:20:51 -0800217
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700218 /**
219 * This should only be called by system code. One should only call this after the service
220 * has started.
221 * @return a reference to the AccountManagerService instance
222 * @hide
223 */
224 public static AccountManagerService getSingleton() {
225 return sThis.get();
226 }
Fred Quintana60307342009-03-24 22:48:12 -0700227
Fred Quintana56285a62010-12-02 14:20:51 -0800228 public AccountManagerService(Context context) {
229 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700230 }
231
Fred Quintana56285a62010-12-02 14:20:51 -0800232 public AccountManagerService(Context context, PackageManager packageManager,
233 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700234 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800235 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700236
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700237 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700238
Fred Quintana56285a62010-12-02 14:20:51 -0800239 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800240 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700241
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700242 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800243
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800244 IntentFilter intentFilter = new IntentFilter();
245 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
246 intentFilter.addDataScheme("package");
247 mContext.registerReceiver(new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800250 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800251 }
252 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800253
Amith Yamasani13593602012-03-22 16:16:17 -0700254 IntentFilter userFilter = new IntentFilter();
255 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800256 userFilter.addAction(Intent.ACTION_USER_STARTED);
257 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700258 @Override
259 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800260 String action = intent.getAction();
261 if (Intent.ACTION_USER_REMOVED.equals(action)) {
262 onUserRemoved(intent);
263 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
264 onUserStarted(intent);
265 }
Amith Yamasani13593602012-03-22 16:16:17 -0700266 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800267 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800268 }
269
Kenny Root26ff6622012-07-30 12:58:03 -0700270 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700271 }
272
Amith Yamasani258848d2012-08-10 17:06:33 -0700273 private UserManager getUserManager() {
274 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700275 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700276 }
277 return mUserManager;
278 }
279
Amith Yamasani04e0d262012-02-14 11:50:53 -0800280 private UserAccounts initUser(int userId) {
281 synchronized (mUsers) {
282 UserAccounts accounts = mUsers.get(userId);
283 if (accounts == null) {
284 accounts = new UserAccounts(mContext, userId);
285 mUsers.append(userId, accounts);
286 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700287 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800288 }
289 return accounts;
290 }
291 }
292
293 private void purgeOldGrantsAll() {
294 synchronized (mUsers) {
295 for (int i = 0; i < mUsers.size(); i++) {
296 purgeOldGrants(mUsers.valueAt(i));
297 }
298 }
299 }
300
301 private void purgeOldGrants(UserAccounts accounts) {
302 synchronized (accounts.cacheLock) {
303 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800304 final Cursor cursor = db.query(TABLE_GRANTS,
305 new String[]{GRANTS_GRANTEE_UID},
306 null, null, GRANTS_GRANTEE_UID, null, null);
307 try {
308 while (cursor.moveToNext()) {
309 final int uid = cursor.getInt(0);
310 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
311 if (packageExists) {
312 continue;
313 }
314 Log.d(TAG, "deleting grants for UID " + uid
315 + " because its package is no longer installed");
316 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
317 new String[]{Integer.toString(uid)});
318 }
319 } finally {
320 cursor.close();
321 }
322 }
323 }
324
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700325 /**
326 * Validate internal set of accounts against installed authenticators for
327 * given user. Clears cached authenticators before validating.
328 */
329 public void validateAccounts(int userId) {
330 final UserAccounts accounts = getUserAccounts(userId);
331
332 // Invalidate user-specific cache to make sure we catch any
333 // removed authenticators.
334 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
335 }
336
337 /**
338 * Validate internal set of accounts against installed authenticators for
339 * given user. Clear cached authenticators before validating when requested.
340 */
341 private void validateAccountsInternal(
342 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
343 if (invalidateAuthenticatorCache) {
344 mAuthenticatorCache.invalidateCache(accounts.userId);
345 }
346
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700347 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
348 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
349 mAuthenticatorCache.getAllServices(accounts.userId)) {
350 knownAuth.add(service.type);
351 }
352
Amith Yamasani04e0d262012-02-14 11:50:53 -0800353 synchronized (accounts.cacheLock) {
354 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800355 boolean accountDeleted = false;
356 Cursor cursor = db.query(TABLE_ACCOUNTS,
357 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
358 null, null, null, null, null);
359 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800360 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800361 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700362 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800363 while (cursor.moveToNext()) {
364 final long accountId = cursor.getLong(0);
365 final String accountType = cursor.getString(1);
366 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700367
368 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700369 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800370 + accountType + " no longer has a registered authenticator");
371 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
372 accountDeleted = true;
373 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800374 accounts.userDataCache.remove(account);
375 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800376 } else {
377 ArrayList<String> accountNames = accountNamesByType.get(accountType);
378 if (accountNames == null) {
379 accountNames = new ArrayList<String>();
380 accountNamesByType.put(accountType, accountNames);
381 }
382 accountNames.add(accountName);
383 }
384 }
Andy McFadden2f362292012-01-20 14:43:38 -0800385 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800386 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800387 final String accountType = cur.getKey();
388 final ArrayList<String> accountNames = cur.getValue();
389 final Account[] accountsForType = new Account[accountNames.size()];
390 int i = 0;
391 for (String accountName : accountNames) {
392 accountsForType[i] = new Account(accountName, accountType);
393 ++i;
394 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800395 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800396 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800397 } finally {
398 cursor.close();
399 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800400 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800401 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800402 }
403 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700404 }
405
Amith Yamasani04e0d262012-02-14 11:50:53 -0800406 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700407 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800408 }
409
410 protected UserAccounts getUserAccounts(int userId) {
411 synchronized (mUsers) {
412 UserAccounts accounts = mUsers.get(userId);
413 if (accounts == null) {
414 accounts = initUser(userId);
415 mUsers.append(userId, accounts);
416 }
417 return accounts;
418 }
419 }
420
Amith Yamasani13593602012-03-22 16:16:17 -0700421 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700422 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700423 if (userId < 1) return;
424
425 UserAccounts accounts;
426 synchronized (mUsers) {
427 accounts = mUsers.get(userId);
428 mUsers.remove(userId);
429 }
430 if (accounts == null) {
431 File dbFile = new File(getDatabaseName(userId));
432 dbFile.delete();
433 return;
434 }
435
436 synchronized (accounts.cacheLock) {
437 accounts.openHelper.close();
438 File dbFile = new File(getDatabaseName(userId));
439 dbFile.delete();
440 }
441 }
442
Amith Yamasani67df64b2012-12-14 12:09:36 -0800443 private void onUserStarted(Intent intent) {
444 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
445 if (userId < 1) return;
446
447 // Check if there's a shared account that needs to be created as an account
448 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
449 if (sharedAccounts == null || sharedAccounts.length == 0) return;
450 Account[] accounts = getAccountsAsUser(null, userId);
451 for (Account sa : sharedAccounts) {
452 if (ArrayUtils.contains(accounts, sa)) continue;
453 // Account doesn't exist. Copy it now.
454 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
455 }
456 }
457
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700458 @Override
459 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700460 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700461 }
462
Fred Quintanaa698f422009-04-08 19:14:54 -0700463 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800464 if (Log.isLoggable(TAG, Log.VERBOSE)) {
465 Log.v(TAG, "getPassword: " + account
466 + ", caller's uid " + Binder.getCallingUid()
467 + ", pid " + Binder.getCallingPid());
468 }
Fred Quintana382601f2010-03-25 12:25:10 -0700469 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700470 checkAuthenticateAccountsPermission(account);
471
Amith Yamasani04e0d262012-02-14 11:50:53 -0800472 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700473 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700474 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800475 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700476 } finally {
477 restoreCallingIdentity(identityToken);
478 }
479 }
480
Amith Yamasani04e0d262012-02-14 11:50:53 -0800481 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700482 if (account == null) {
483 return null;
484 }
485
Amith Yamasani04e0d262012-02-14 11:50:53 -0800486 synchronized (accounts.cacheLock) {
487 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800488 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
489 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
490 new String[]{account.name, account.type}, null, null, null);
491 try {
492 if (cursor.moveToNext()) {
493 return cursor.getString(0);
494 }
495 return null;
496 } finally {
497 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700498 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700499 }
500 }
501
502 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800503 if (Log.isLoggable(TAG, Log.VERBOSE)) {
504 Log.v(TAG, "getUserData: " + account
505 + ", key " + key
506 + ", caller's uid " + Binder.getCallingUid()
507 + ", pid " + Binder.getCallingPid());
508 }
Fred Quintana382601f2010-03-25 12:25:10 -0700509 if (account == null) throw new IllegalArgumentException("account is null");
510 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700511 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800512 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700513 long identityToken = clearCallingIdentity();
514 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800515 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700516 } finally {
517 restoreCallingIdentity(identityToken);
518 }
519 }
520
Fred Quintana97889762009-06-15 12:29:24 -0700521 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800522 if (Log.isLoggable(TAG, Log.VERBOSE)) {
523 Log.v(TAG, "getAuthenticatorTypes: "
524 + "caller's uid " + Binder.getCallingUid()
525 + ", pid " + Binder.getCallingPid());
526 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700527 final int userId = UserHandle.getCallingUserId();
528 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700529 try {
Fred Quintana97889762009-06-15 12:29:24 -0700530 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700531 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700532 AuthenticatorDescription[] types =
533 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700534 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700535 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700536 : authenticatorCollection) {
537 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700538 i++;
539 }
540 return types;
541 } finally {
542 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700543 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700544 }
545
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700546 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700547 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800548 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700549 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800550 + ", caller's uid " + Binder.getCallingUid()
551 + ", pid " + Binder.getCallingPid());
552 }
Fred Quintana382601f2010-03-25 12:25:10 -0700553 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700554 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700555 /*
556 * Child users are not allowed to add accounts. Only the accounts that are
557 * shared by the parent profile can be added to child profile.
558 *
559 * TODO: Only allow accounts that were shared to be added by
560 * a limited user.
561 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700562
Amith Yamasani04e0d262012-02-14 11:50:53 -0800563 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700564 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700565 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700566 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800567 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700568 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700569 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700570 }
571 }
572
Amith Yamasani67df64b2012-12-14 12:09:36 -0800573 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
574 final UserAccounts fromAccounts = getUserAccounts(userFrom);
575 final UserAccounts toAccounts = getUserAccounts(userTo);
576 if (fromAccounts == null || toAccounts == null) {
577 return false;
578 }
579
580 long identityToken = clearCallingIdentity();
581 try {
582 new Session(fromAccounts, null, account.type, false,
583 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700584 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800585 protected String toDebugString(long now) {
586 return super.toDebugString(now) + ", getAccountCredentialsForClone"
587 + ", " + account.type;
588 }
589
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700590 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800591 public void run() throws RemoteException {
592 mAuthenticator.getAccountCredentialsForCloning(this, account);
593 }
594
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700595 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800596 public void onResult(Bundle result) {
597 if (result != null) {
598 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
599 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800600 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800601 }
602 return;
603 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800604 super.onResult(result);
605 }
606 }
607 }.bind();
608 } finally {
609 restoreCallingIdentity(identityToken);
610 }
611 return true;
612 }
613
Amith Yamasani67df64b2012-12-14 12:09:36 -0800614 void completeCloningAccount(final Bundle result, final Account account,
615 final UserAccounts targetUser) {
616 long id = clearCallingIdentity();
617 try {
618 new Session(targetUser, null, account.type, false,
619 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700620 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800621 protected String toDebugString(long now) {
622 return super.toDebugString(now) + ", getAccountCredentialsForClone"
623 + ", " + account.type;
624 }
625
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700626 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800627 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700628 // Confirm that the owner's account still exists before this step.
629 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
630 synchronized (owner.cacheLock) {
631 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
632 for (Account acc : ownerAccounts) {
633 if (acc.equals(account)) {
634 mAuthenticator.addAccountFromCredentials(this, account, result);
635 break;
636 }
637 }
638 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800639 }
640
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700641 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800642 public void onResult(Bundle result) {
643 if (result != null) {
644 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
645 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800646 } else {
647 // TODO: Show error notification
648 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800649 }
650 return;
651 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800652 super.onResult(result);
653 }
654 }
655
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700656 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800657 public void onError(int errorCode, String errorMessage) {
658 super.onError(errorCode, errorMessage);
659 // TODO: Show error notification to user
660 // TODO: Should we remove the shadow account so that it doesn't keep trying?
661 }
662
663 }.bind();
664 } finally {
665 restoreCallingIdentity(id);
666 }
667 }
668
Amith Yamasani04e0d262012-02-14 11:50:53 -0800669 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800670 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700671 if (account == null) {
672 return false;
673 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800674 synchronized (accounts.cacheLock) {
675 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800676 db.beginTransaction();
677 try {
678 long numMatches = DatabaseUtils.longForQuery(db,
679 "select count(*) from " + TABLE_ACCOUNTS
680 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
681 new String[]{account.name, account.type});
682 if (numMatches > 0) {
683 Log.w(TAG, "insertAccountIntoDatabase: " + account
684 + ", skipping since the account already exists");
685 return false;
686 }
687 ContentValues values = new ContentValues();
688 values.put(ACCOUNTS_NAME, account.name);
689 values.put(ACCOUNTS_TYPE, account.type);
690 values.put(ACCOUNTS_PASSWORD, password);
691 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
692 if (accountId < 0) {
693 Log.w(TAG, "insertAccountIntoDatabase: " + account
694 + ", skipping the DB insert failed");
695 return false;
696 }
697 if (extras != null) {
698 for (String key : extras.keySet()) {
699 final String value = extras.getString(key);
700 if (insertExtraLocked(db, accountId, key, value) < 0) {
701 Log.w(TAG, "insertAccountIntoDatabase: " + account
702 + ", skipping since insertExtra failed for key " + key);
703 return false;
704 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700705 }
706 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800707 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800708 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800709 } finally {
710 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700711 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800712 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700713 }
714 if (accounts.userId == UserHandle.USER_OWNER) {
715 addAccountToLimitedUsers(account);
716 }
717 return true;
718 }
719
720 /**
721 * Adds the account to all limited users as shared accounts. If the user is currently
722 * running, then clone the account too.
723 * @param account the account to share with limited users
724 */
725 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700726 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700727 for (UserInfo user : users) {
728 if (user.isRestricted()) {
729 addSharedAccountAsUser(account, user.id);
730 try {
731 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
732 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
733 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
734 account));
735 }
736 } catch (RemoteException re) {
737 // Shouldn't happen
738 }
739 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700740 }
741 }
742
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800743 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700744 ContentValues values = new ContentValues();
745 values.put(EXTRAS_KEY, key);
746 values.put(EXTRAS_ACCOUNTS_ID, accountId);
747 values.put(EXTRAS_VALUE, value);
748 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
749 }
750
Fred Quintana3084a6f2010-01-14 18:02:03 -0800751 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800752 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800753 if (Log.isLoggable(TAG, Log.VERBOSE)) {
754 Log.v(TAG, "hasFeatures: " + account
755 + ", response " + response
756 + ", features " + stringArrayToString(features)
757 + ", caller's uid " + Binder.getCallingUid()
758 + ", pid " + Binder.getCallingPid());
759 }
Fred Quintana382601f2010-03-25 12:25:10 -0700760 if (response == null) throw new IllegalArgumentException("response is null");
761 if (account == null) throw new IllegalArgumentException("account is null");
762 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800763 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800764 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800765 long identityToken = clearCallingIdentity();
766 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800767 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800768 } finally {
769 restoreCallingIdentity(identityToken);
770 }
771 }
772
773 private class TestFeaturesSession extends Session {
774 private final String[] mFeatures;
775 private final Account mAccount;
776
Amith Yamasani04e0d262012-02-14 11:50:53 -0800777 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800778 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800779 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800780 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800781 mFeatures = features;
782 mAccount = account;
783 }
784
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700785 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800786 public void run() throws RemoteException {
787 try {
788 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
789 } catch (RemoteException e) {
790 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
791 }
792 }
793
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700794 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800795 public void onResult(Bundle result) {
796 IAccountManagerResponse response = getResponseAndClose();
797 if (response != null) {
798 try {
799 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700800 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800801 return;
802 }
Fred Quintana56285a62010-12-02 14:20:51 -0800803 if (Log.isLoggable(TAG, Log.VERBOSE)) {
804 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
805 + response);
806 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800807 final Bundle newResult = new Bundle();
808 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
809 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
810 response.onResult(newResult);
811 } catch (RemoteException e) {
812 // if the caller is dead then there is no one to care about remote exceptions
813 if (Log.isLoggable(TAG, Log.VERBOSE)) {
814 Log.v(TAG, "failure while notifying response", e);
815 }
816 }
817 }
818 }
819
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700820 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800821 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800822 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800823 + ", " + mAccount
824 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
825 }
826 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800827
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700828 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800829 if (Log.isLoggable(TAG, Log.VERBOSE)) {
830 Log.v(TAG, "removeAccount: " + account
831 + ", response " + response
832 + ", caller's uid " + Binder.getCallingUid()
833 + ", pid " + Binder.getCallingPid());
834 }
Fred Quintana382601f2010-03-25 12:25:10 -0700835 if (response == null) throw new IllegalArgumentException("response is null");
836 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700837 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700838 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800839 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800840 if (!canUserModifyAccounts(Binder.getCallingUid())) {
841 try {
842 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
843 "User cannot modify accounts");
844 } catch (RemoteException re) {
845 }
846 }
847
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700848 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800849
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700850 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800851 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800852 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800853 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800854 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800855 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700856 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800857 }
858 }
859 }
860
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700861 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800862 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700863 } finally {
864 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700865 }
Fred Quintana60307342009-03-24 22:48:12 -0700866 }
867
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700868 private class RemoveAccountSession extends Session {
869 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800870 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
871 Account account) {
872 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800873 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700874 mAccount = account;
875 }
876
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700877 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700878 protected String toDebugString(long now) {
879 return super.toDebugString(now) + ", removeAccount"
880 + ", account " + mAccount;
881 }
882
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700883 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700884 public void run() throws RemoteException {
885 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
886 }
887
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700888 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700889 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700890 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
891 && !result.containsKey(AccountManager.KEY_INTENT)) {
892 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700893 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800894 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700895 }
896 IAccountManagerResponse response = getResponseAndClose();
897 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800898 if (Log.isLoggable(TAG, Log.VERBOSE)) {
899 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
900 + response);
901 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700902 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700903 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700904 try {
905 response.onResult(result2);
906 } catch (RemoteException e) {
907 // ignore
908 }
909 }
910 }
911 super.onResult(result);
912 }
913 }
914
Amith Yamasani04e0d262012-02-14 11:50:53 -0800915 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800916 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800917 removeAccountInternal(getUserAccountsForCaller(), account);
918 }
919
920 private void removeAccountInternal(UserAccounts accounts, Account account) {
921 synchronized (accounts.cacheLock) {
922 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800923 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
924 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800925 removeAccountFromCacheLocked(accounts, account);
926 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800927 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800928 if (accounts.userId == UserHandle.USER_OWNER) {
929 // Owner's account was removed, remove from any users that are sharing
930 // this account.
931 long id = Binder.clearCallingIdentity();
932 try {
933 List<UserInfo> users = mUserManager.getUsers(true);
934 for (UserInfo user : users) {
935 if (!user.isPrimary() && user.isRestricted()) {
936 removeSharedAccountAsUser(account, user.id);
937 }
938 }
939 } finally {
940 Binder.restoreCallingIdentity(id);
941 }
942 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700943 }
944
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400945 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700946 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800947 if (Log.isLoggable(TAG, Log.VERBOSE)) {
948 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
949 + ", caller's uid " + Binder.getCallingUid()
950 + ", pid " + Binder.getCallingPid());
951 }
Fred Quintana382601f2010-03-25 12:25:10 -0700952 if (accountType == null) throw new IllegalArgumentException("accountType is null");
953 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800954 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800955 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700956 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700957 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800958 synchronized (accounts.cacheLock) {
959 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800960 db.beginTransaction();
961 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800962 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800963 db.setTransactionSuccessful();
964 } finally {
965 db.endTransaction();
966 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700967 }
Fred Quintana60307342009-03-24 22:48:12 -0700968 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700969 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700970 }
971 }
972
Amith Yamasani04e0d262012-02-14 11:50:53 -0800973 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
974 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700975 if (authToken == null || accountType == null) {
976 return;
977 }
Fred Quintana33269202009-04-20 16:05:10 -0700978 Cursor cursor = db.rawQuery(
979 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
980 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
981 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
982 + " FROM " + TABLE_ACCOUNTS
983 + " JOIN " + TABLE_AUTHTOKENS
984 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
985 + " = " + AUTHTOKENS_ACCOUNTS_ID
986 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
987 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
988 new String[]{authToken, accountType});
989 try {
990 while (cursor.moveToNext()) {
991 long authTokenId = cursor.getLong(0);
992 String accountName = cursor.getString(1);
993 String authTokenType = cursor.getString(2);
994 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800995 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800996 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700997 }
Fred Quintana33269202009-04-20 16:05:10 -0700998 } finally {
999 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001000 }
1001 }
1002
Amith Yamasani04e0d262012-02-14 11:50:53 -08001003 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1004 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001005 if (account == null || type == null) {
1006 return false;
1007 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001008 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1009 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001010 synchronized (accounts.cacheLock) {
1011 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001012 db.beginTransaction();
1013 try {
1014 long accountId = getAccountIdLocked(db, account);
1015 if (accountId < 0) {
1016 return false;
1017 }
1018 db.delete(TABLE_AUTHTOKENS,
1019 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1020 new String[]{type});
1021 ContentValues values = new ContentValues();
1022 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1023 values.put(AUTHTOKENS_TYPE, type);
1024 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1025 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1026 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001027 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001028 return true;
1029 }
Fred Quintana33269202009-04-20 16:05:10 -07001030 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001031 } finally {
1032 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001033 }
Fred Quintana60307342009-03-24 22:48:12 -07001034 }
1035 }
1036
Fred Quintanaa698f422009-04-08 19:14:54 -07001037 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001038 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1039 Log.v(TAG, "peekAuthToken: " + account
1040 + ", authTokenType " + authTokenType
1041 + ", caller's uid " + Binder.getCallingUid()
1042 + ", pid " + Binder.getCallingPid());
1043 }
Fred Quintana382601f2010-03-25 12:25:10 -07001044 if (account == null) throw new IllegalArgumentException("account is null");
1045 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001046 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001047 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001048 long identityToken = clearCallingIdentity();
1049 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001050 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001051 } finally {
1052 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001053 }
Fred Quintana60307342009-03-24 22:48:12 -07001054 }
1055
Fred Quintanaa698f422009-04-08 19:14:54 -07001056 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001057 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1058 Log.v(TAG, "setAuthToken: " + account
1059 + ", authTokenType " + authTokenType
1060 + ", caller's uid " + Binder.getCallingUid()
1061 + ", pid " + Binder.getCallingPid());
1062 }
Fred Quintana382601f2010-03-25 12:25:10 -07001063 if (account == null) throw new IllegalArgumentException("account is null");
1064 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001065 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001066 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001067 long identityToken = clearCallingIdentity();
1068 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001069 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001070 } finally {
1071 restoreCallingIdentity(identityToken);
1072 }
Fred Quintana60307342009-03-24 22:48:12 -07001073 }
1074
Fred Quintanaa698f422009-04-08 19:14:54 -07001075 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001076 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1077 Log.v(TAG, "setAuthToken: " + account
1078 + ", caller's uid " + Binder.getCallingUid()
1079 + ", pid " + Binder.getCallingPid());
1080 }
Fred Quintana382601f2010-03-25 12:25:10 -07001081 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001082 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001083 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001084 long identityToken = clearCallingIdentity();
1085 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001086 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001087 } finally {
1088 restoreCallingIdentity(identityToken);
1089 }
Fred Quintana60307342009-03-24 22:48:12 -07001090 }
1091
Amith Yamasani04e0d262012-02-14 11:50:53 -08001092 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001093 if (account == null) {
1094 return;
1095 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001096 synchronized (accounts.cacheLock) {
1097 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001098 db.beginTransaction();
1099 try {
1100 final ContentValues values = new ContentValues();
1101 values.put(ACCOUNTS_PASSWORD, password);
1102 final long accountId = getAccountIdLocked(db, account);
1103 if (accountId >= 0) {
1104 final String[] argsAccountId = {String.valueOf(accountId)};
1105 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1106 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001107 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001108 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001109 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001110 } finally {
1111 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001112 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001113 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001114 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001115 }
1116
Amith Yamasani04e0d262012-02-14 11:50:53 -08001117 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001118 Log.i(TAG, "the accounts changed, sending broadcast of "
1119 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001120 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001121 }
1122
Fred Quintanaa698f422009-04-08 19:14:54 -07001123 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001124 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1125 Log.v(TAG, "clearPassword: " + account
1126 + ", caller's uid " + Binder.getCallingUid()
1127 + ", pid " + Binder.getCallingPid());
1128 }
Fred Quintana382601f2010-03-25 12:25:10 -07001129 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001130 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001131 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001132 long identityToken = clearCallingIdentity();
1133 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001134 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001135 } finally {
1136 restoreCallingIdentity(identityToken);
1137 }
Fred Quintana60307342009-03-24 22:48:12 -07001138 }
1139
Fred Quintanaa698f422009-04-08 19:14:54 -07001140 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001141 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1142 Log.v(TAG, "setUserData: " + account
1143 + ", key " + key
1144 + ", caller's uid " + Binder.getCallingUid()
1145 + ", pid " + Binder.getCallingPid());
1146 }
Fred Quintana382601f2010-03-25 12:25:10 -07001147 if (key == null) throw new IllegalArgumentException("key is null");
1148 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001149 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001150 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001151 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001152 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001153 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001154 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001155 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001156 }
1157 }
1158
Amith Yamasani04e0d262012-02-14 11:50:53 -08001159 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1160 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001161 if (account == null || key == null) {
1162 return;
1163 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001164 synchronized (accounts.cacheLock) {
1165 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001166 db.beginTransaction();
1167 try {
1168 long accountId = getAccountIdLocked(db, account);
1169 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001170 return;
1171 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001172 long extrasId = getExtrasIdLocked(db, accountId, key);
1173 if (extrasId < 0 ) {
1174 extrasId = insertExtraLocked(db, accountId, key, value);
1175 if (extrasId < 0) {
1176 return;
1177 }
1178 } else {
1179 ContentValues values = new ContentValues();
1180 values.put(EXTRAS_VALUE, value);
1181 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1182 return;
1183 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001184
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001185 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001186 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001187 db.setTransactionSuccessful();
1188 } finally {
1189 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001190 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001191 }
1192 }
1193
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001194 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001195 if (result == null) {
1196 Log.e(TAG, "the result is unexpectedly null", new Exception());
1197 }
1198 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1199 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1200 + response);
1201 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001202 try {
1203 response.onResult(result);
1204 } catch (RemoteException e) {
1205 // if the caller is dead then there is no one to care about remote
1206 // exceptions
1207 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1208 Log.v(TAG, "failure while notifying response", e);
1209 }
1210 }
1211 }
1212
Fred Quintanad9640ec2012-05-23 12:37:00 -07001213 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1214 final String authTokenType)
1215 throws RemoteException {
1216 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001217 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1218
Fred Quintanad9640ec2012-05-23 12:37:00 -07001219 final int callingUid = getCallingUid();
1220 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001221 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001222 throw new SecurityException("can only call from system");
1223 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001224 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001225 long identityToken = clearCallingIdentity();
1226 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001227 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001228 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001229 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001230 protected String toDebugString(long now) {
1231 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001232 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001233 + ", authTokenType " + authTokenType;
1234 }
1235
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001236 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001237 public void run() throws RemoteException {
1238 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1239 }
1240
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001241 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001242 public void onResult(Bundle result) {
1243 if (result != null) {
1244 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1245 Bundle bundle = new Bundle();
1246 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1247 super.onResult(bundle);
1248 return;
1249 } else {
1250 super.onResult(result);
1251 }
1252 }
1253 }.bind();
1254 } finally {
1255 restoreCallingIdentity(identityToken);
1256 }
1257 }
1258
Fred Quintanaa698f422009-04-08 19:14:54 -07001259 public void getAuthToken(IAccountManagerResponse response, final Account account,
1260 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001261 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001262 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1263 Log.v(TAG, "getAuthToken: " + account
1264 + ", response " + response
1265 + ", authTokenType " + authTokenType
1266 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1267 + ", expectActivityLaunch " + expectActivityLaunch
1268 + ", caller's uid " + Binder.getCallingUid()
1269 + ", pid " + Binder.getCallingPid());
1270 }
Fred Quintana382601f2010-03-25 12:25:10 -07001271 if (response == null) throw new IllegalArgumentException("response is null");
1272 if (account == null) throw new IllegalArgumentException("account is null");
1273 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001274 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001275 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001276 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1277 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1278 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001279 final boolean customTokens =
1280 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1281
Amith Yamasanid20ea2f2013-05-08 12:57:01 -07001282 // Check to see that the app is authorized to access the account, in case it's a
1283 // restricted account.
1284 if (!ArrayUtils.contains(getAccounts((String) null), account)) {
1285 throw new IllegalArgumentException("no such account");
1286 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001287 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001288 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001289 final boolean permissionGranted = customTokens ||
1290 permissionIsGranted(account, authTokenType, callerUid);
1291
Costin Manolachec6684f92011-01-14 11:25:39 -08001292 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1293 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001294 // let authenticator know the identity of the caller
1295 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1296 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1297 if (notifyOnAuthFailure) {
1298 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001299 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001300
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001301 long identityToken = clearCallingIdentity();
1302 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001303 // if the caller has permission, do the peek. otherwise go the more expensive
1304 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001305 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001306 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001307 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001308 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001309 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1310 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1311 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001312 onResult(response, result);
1313 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001314 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001315 }
1316
Amith Yamasani04e0d262012-02-14 11:50:53 -08001317 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001318 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001319 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001320 protected String toDebugString(long now) {
1321 if (loginOptions != null) loginOptions.keySet();
1322 return super.toDebugString(now) + ", getAuthToken"
1323 + ", " + account
1324 + ", authTokenType " + authTokenType
1325 + ", loginOptions " + loginOptions
1326 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1327 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001328
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001329 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001330 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001331 // If the caller doesn't have permission then create and return the
1332 // "grant permission" intent instead of the "getAuthToken" intent.
1333 if (!permissionGranted) {
1334 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1335 } else {
1336 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1337 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001338 }
1339
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001340 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001341 public void onResult(Bundle result) {
1342 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001343 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001344 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1345 new AccountAuthenticatorResponse(this),
1346 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001347 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001348 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001349 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001350 onResult(bundle);
1351 return;
1352 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001353 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001354 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001355 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1356 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001357 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001358 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001359 "the type and name should not be empty");
1360 return;
1361 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001362 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001363 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001364 authTokenType, authToken);
1365 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001366 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001367
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001368 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001369 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001370 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001371 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001372 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001373 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001374 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001375 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001376 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001377 }.bind();
1378 } finally {
1379 restoreCallingIdentity(identityToken);
1380 }
Fred Quintana60307342009-03-24 22:48:12 -07001381 }
1382
Dianne Hackborn41203752012-08-31 14:05:51 -07001383 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1384 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001385 int uid = intent.getIntExtra(
1386 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1387 String authTokenType = intent.getStringExtra(
1388 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1389 String authTokenLabel = intent.getStringExtra(
1390 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1391
1392 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1393 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001394 final String titleAndSubtitle =
1395 mContext.getString(R.string.permission_request_notification_with_subtitle,
1396 account.name);
1397 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001398 String title = titleAndSubtitle;
1399 String subtitle = "";
1400 if (index > 0) {
1401 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001402 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001403 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001404 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001405 n.setLatestEventInfo(mContext, title, subtitle,
1406 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001407 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1408 installNotification(getCredentialPermissionNotificationId(
1409 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001410 }
1411
Costin Manolache5f383ad92010-12-02 16:44:46 -08001412 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1413 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001414
1415 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001416 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001417 // Since it was set in Eclair+ we can't change it without breaking apps using
1418 // the intent from a non-Activity context.
1419 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001420 intent.addCategory(
1421 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001422
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001423 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001424 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1425 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001426 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001427
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001428 return intent;
1429 }
1430
1431 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1432 int uid) {
1433 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001434 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001435 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001436 final Pair<Pair<Account, String>, Integer> key =
1437 new Pair<Pair<Account, String>, Integer>(
1438 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001439 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001440 if (id == null) {
1441 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001442 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001443 }
1444 }
1445 return id;
1446 }
1447
Amith Yamasani04e0d262012-02-14 11:50:53 -08001448 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001449 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001450 synchronized (accounts.signinRequiredNotificationIds) {
1451 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001452 if (id == null) {
1453 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001454 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001455 }
1456 }
1457 return id;
1458 }
1459
Amith Yamasani27db4682013-03-30 17:07:47 -07001460 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001461 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001462 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001463 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1464 Log.v(TAG, "addAccount: accountType " + accountType
1465 + ", response " + response
1466 + ", authTokenType " + authTokenType
1467 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1468 + ", expectActivityLaunch " + expectActivityLaunch
1469 + ", caller's uid " + Binder.getCallingUid()
1470 + ", pid " + Binder.getCallingPid());
1471 }
Fred Quintana382601f2010-03-25 12:25:10 -07001472 if (response == null) throw new IllegalArgumentException("response is null");
1473 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001474 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001475
Amith Yamasani71e6c692013-03-24 17:39:28 -07001476 // Is user disallowed from modifying accounts?
Amith Yamasani27db4682013-03-30 17:07:47 -07001477 if (!canUserModifyAccounts(Binder.getCallingUid())) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001478 try {
1479 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1480 "User is not allowed to add an account!");
1481 } catch (RemoteException re) {
1482 }
Amith Yamasani23c8b962013-04-10 13:37:18 -07001483 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1484 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1485 long identityToken = clearCallingIdentity();
1486 try {
1487 mContext.startActivityAsUser(cantAddAccount, UserHandle.CURRENT);
1488 } finally {
1489 restoreCallingIdentity(identityToken);
1490 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001491 return;
1492 }
1493
Amith Yamasani04e0d262012-02-14 11:50:53 -08001494 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001495 final int pid = Binder.getCallingPid();
1496 final int uid = Binder.getCallingUid();
1497 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1498 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1499 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1500
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001501 long identityToken = clearCallingIdentity();
1502 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001503 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001504 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001505 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001506 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001507 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001508 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001509 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001510
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001511 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001512 protected String toDebugString(long now) {
1513 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001514 + ", accountType " + accountType
1515 + ", requiredFeatures "
1516 + (requiredFeatures != null
1517 ? TextUtils.join(",", requiredFeatures)
1518 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001519 }
1520 }.bind();
1521 } finally {
1522 restoreCallingIdentity(identityToken);
1523 }
Fred Quintana60307342009-03-24 22:48:12 -07001524 }
1525
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001526 @Override
1527 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1528 final Account account, final Bundle options, final boolean expectActivityLaunch,
1529 int userId) {
1530 // Only allow the system process to read accounts of other users
1531 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001532 && Binder.getCallingUid() != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001533 && mContext.checkCallingOrSelfPermission(
1534 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1535 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001536 throw new SecurityException("User " + UserHandle.getCallingUserId()
1537 + " trying to confirm account credentials for " + userId);
1538 }
1539
Fred Quintana56285a62010-12-02 14:20:51 -08001540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1541 Log.v(TAG, "confirmCredentials: " + account
1542 + ", response " + response
1543 + ", expectActivityLaunch " + expectActivityLaunch
1544 + ", caller's uid " + Binder.getCallingUid()
1545 + ", pid " + Binder.getCallingPid());
1546 }
Fred Quintana382601f2010-03-25 12:25:10 -07001547 if (response == null) throw new IllegalArgumentException("response is null");
1548 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001549 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001550 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001551 long identityToken = clearCallingIdentity();
1552 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001553 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001554 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001555 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001556 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001557 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001558 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001559 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001560 protected String toDebugString(long now) {
1561 return super.toDebugString(now) + ", confirmCredentials"
1562 + ", " + account;
1563 }
1564 }.bind();
1565 } finally {
1566 restoreCallingIdentity(identityToken);
1567 }
Fred Quintana60307342009-03-24 22:48:12 -07001568 }
1569
Fred Quintanaa698f422009-04-08 19:14:54 -07001570 public void updateCredentials(IAccountManagerResponse response, final Account account,
1571 final String authTokenType, final boolean expectActivityLaunch,
1572 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001573 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1574 Log.v(TAG, "updateCredentials: " + account
1575 + ", response " + response
1576 + ", authTokenType " + authTokenType
1577 + ", expectActivityLaunch " + expectActivityLaunch
1578 + ", caller's uid " + Binder.getCallingUid()
1579 + ", pid " + Binder.getCallingPid());
1580 }
Fred Quintana382601f2010-03-25 12:25:10 -07001581 if (response == null) throw new IllegalArgumentException("response is null");
1582 if (account == null) throw new IllegalArgumentException("account is null");
1583 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001584 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001585 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001586 long identityToken = clearCallingIdentity();
1587 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001588 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001589 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001590 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001591 public void run() throws RemoteException {
1592 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1593 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001594 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001595 protected String toDebugString(long now) {
1596 if (loginOptions != null) loginOptions.keySet();
1597 return super.toDebugString(now) + ", updateCredentials"
1598 + ", " + account
1599 + ", authTokenType " + authTokenType
1600 + ", loginOptions " + loginOptions;
1601 }
1602 }.bind();
1603 } finally {
1604 restoreCallingIdentity(identityToken);
1605 }
Fred Quintana60307342009-03-24 22:48:12 -07001606 }
1607
Fred Quintanaa698f422009-04-08 19:14:54 -07001608 public void editProperties(IAccountManagerResponse response, final String accountType,
1609 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001610 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1611 Log.v(TAG, "editProperties: accountType " + accountType
1612 + ", response " + response
1613 + ", expectActivityLaunch " + expectActivityLaunch
1614 + ", caller's uid " + Binder.getCallingUid()
1615 + ", pid " + Binder.getCallingPid());
1616 }
Fred Quintana382601f2010-03-25 12:25:10 -07001617 if (response == null) throw new IllegalArgumentException("response is null");
1618 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001619 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001620 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001621 long identityToken = clearCallingIdentity();
1622 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001623 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001624 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001625 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001626 public void run() throws RemoteException {
1627 mAuthenticator.editProperties(this, mAccountType);
1628 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001629 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001630 protected String toDebugString(long now) {
1631 return super.toDebugString(now) + ", editProperties"
1632 + ", accountType " + accountType;
1633 }
1634 }.bind();
1635 } finally {
1636 restoreCallingIdentity(identityToken);
1637 }
Fred Quintana60307342009-03-24 22:48:12 -07001638 }
1639
Fred Quintana33269202009-04-20 16:05:10 -07001640 private class GetAccountsByTypeAndFeatureSession extends Session {
1641 private final String[] mFeatures;
1642 private volatile Account[] mAccountsOfType = null;
1643 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1644 private volatile int mCurrentAccount = 0;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001645 private int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001646
Amith Yamasani04e0d262012-02-14 11:50:53 -08001647 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001648 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001649 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001650 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001651 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001652 mFeatures = features;
1653 }
1654
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001655 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001656 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001657 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001658 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1659 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001660 }
Fred Quintana33269202009-04-20 16:05:10 -07001661 // check whether each account matches the requested features
1662 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1663 mCurrentAccount = 0;
1664
1665 checkAccount();
1666 }
1667
1668 public void checkAccount() {
1669 if (mCurrentAccount >= mAccountsOfType.length) {
1670 sendResult();
1671 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001672 }
Fred Quintana33269202009-04-20 16:05:10 -07001673
Fred Quintana29e94b82010-03-10 12:11:51 -08001674 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1675 if (accountAuthenticator == null) {
1676 // It is possible that the authenticator has died, which is indicated by
1677 // mAuthenticator being set to null. If this happens then just abort.
1678 // There is no need to send back a result or error in this case since
1679 // that already happened when mAuthenticator was cleared.
1680 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1681 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1682 + " connected to the authenticator, " + toDebugString());
1683 }
1684 return;
1685 }
Fred Quintana33269202009-04-20 16:05:10 -07001686 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001687 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001688 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001689 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001690 }
1691 }
1692
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001693 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001694 public void onResult(Bundle result) {
1695 mNumResults++;
1696 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001697 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001698 return;
1699 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001700 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001701 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1702 }
1703 mCurrentAccount++;
1704 checkAccount();
1705 }
1706
1707 public void sendResult() {
1708 IAccountManagerResponse response = getResponseAndClose();
1709 if (response != null) {
1710 try {
1711 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1712 for (int i = 0; i < accounts.length; i++) {
1713 accounts[i] = mAccountsWithFeatures.get(i);
1714 }
Fred Quintana56285a62010-12-02 14:20:51 -08001715 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1716 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1717 + response);
1718 }
Fred Quintana33269202009-04-20 16:05:10 -07001719 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001720 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001721 response.onResult(result);
1722 } catch (RemoteException e) {
1723 // if the caller is dead then there is no one to care about remote exceptions
1724 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1725 Log.v(TAG, "failure while notifying response", e);
1726 }
1727 }
1728 }
1729 }
1730
1731
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001732 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001733 protected String toDebugString(long now) {
1734 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1735 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1736 }
1737 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001738
Amith Yamasani04e0d262012-02-14 11:50:53 -08001739 /**
1740 * Returns the accounts for a specific user
1741 * @hide
1742 */
1743 public Account[] getAccounts(int userId) {
1744 checkReadAccountsPermission();
1745 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001746 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001747 long identityToken = clearCallingIdentity();
1748 try {
1749 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001750 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001751 }
1752 } finally {
1753 restoreCallingIdentity(identityToken);
1754 }
1755 }
1756
Amith Yamasanif29f2362012-04-05 18:29:52 -07001757 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001758 * Returns accounts for all running users.
1759 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001760 * @hide
1761 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001762 public AccountAndUser[] getRunningAccounts() {
1763 final int[] runningUserIds;
1764 try {
1765 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1766 } catch (RemoteException e) {
1767 // Running in system_server; should never happen
1768 throw new RuntimeException(e);
1769 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001770 return getAccounts(runningUserIds);
1771 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001772
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001773 /** {@hide} */
1774 public AccountAndUser[] getAllAccounts() {
1775 final List<UserInfo> users = getUserManager().getUsers();
1776 final int[] userIds = new int[users.size()];
1777 for (int i = 0; i < userIds.length; i++) {
1778 userIds[i] = users.get(i).id;
1779 }
1780 return getAccounts(userIds);
1781 }
1782
1783 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001784 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1785 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001786 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001787 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001788 if (userAccounts == null) continue;
1789 synchronized (userAccounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001790 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
Amith Yamasani27db4682013-03-30 17:07:47 -07001791 Binder.getCallingUid(), null);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001792 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001793 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001794 }
1795 }
1796 }
1797 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001798
1799 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1800 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001801 }
1802
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001803 @Override
1804 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001805 return getAccountsAsUser(type, userId, null, -1);
1806 }
1807
1808 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
1809 int packageUid) {
1810 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001811 // Only allow the system process to read accounts of other users
1812 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001813 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001814 && mContext.checkCallingOrSelfPermission(
1815 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1816 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001817 throw new SecurityException("User " + UserHandle.getCallingUserId()
1818 + " trying to get account for " + userId);
1819 }
1820
Fred Quintana56285a62010-12-02 14:20:51 -08001821 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1822 Log.v(TAG, "getAccounts: accountType " + type
1823 + ", caller's uid " + Binder.getCallingUid()
1824 + ", pid " + Binder.getCallingPid());
1825 }
Amith Yamasani27db4682013-03-30 17:07:47 -07001826 // If the original calling app was using the framework account chooser activity, we'll
1827 // be passed in the original caller's uid here, which is what should be used for filtering.
1828 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
1829 callingUid = packageUid;
1830 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001831 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001832 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001833 long identityToken = clearCallingIdentity();
1834 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001835 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001836 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001837 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001838 } finally {
1839 restoreCallingIdentity(identityToken);
1840 }
1841 }
1842
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001843 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001844 public boolean addSharedAccountAsUser(Account account, int userId) {
1845 userId = handleIncomingUser(userId);
1846 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1847 ContentValues values = new ContentValues();
1848 values.put(ACCOUNTS_NAME, account.name);
1849 values.put(ACCOUNTS_TYPE, account.type);
1850 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1851 new String[] {account.name, account.type});
1852 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1853 if (accountId < 0) {
1854 Log.w(TAG, "insertAccountIntoDatabase: " + account
1855 + ", skipping the DB insert failed");
1856 return false;
1857 }
1858 return true;
1859 }
1860
1861 @Override
1862 public boolean removeSharedAccountAsUser(Account account, int userId) {
1863 userId = handleIncomingUser(userId);
1864 UserAccounts accounts = getUserAccounts(userId);
1865 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1866 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1867 new String[] {account.name, account.type});
1868 if (r > 0) {
1869 removeAccountInternal(accounts, account);
1870 }
1871 return r > 0;
1872 }
1873
1874 @Override
1875 public Account[] getSharedAccountsAsUser(int userId) {
1876 userId = handleIncomingUser(userId);
1877 UserAccounts accounts = getUserAccounts(userId);
1878 ArrayList<Account> accountList = new ArrayList<Account>();
1879 Cursor cursor = null;
1880 try {
1881 cursor = accounts.openHelper.getReadableDatabase()
1882 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1883 null, null, null, null, null);
1884 if (cursor != null && cursor.moveToFirst()) {
1885 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1886 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1887 do {
1888 accountList.add(new Account(cursor.getString(nameIndex),
1889 cursor.getString(typeIndex)));
1890 } while (cursor.moveToNext());
1891 }
1892 } finally {
1893 if (cursor != null) {
1894 cursor.close();
1895 }
1896 }
1897 Account[] accountArray = new Account[accountList.size()];
1898 accountList.toArray(accountArray);
1899 return accountArray;
1900 }
1901
1902 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001903 public Account[] getAccounts(String type) {
1904 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1905 }
1906
Amith Yamasani27db4682013-03-30 17:07:47 -07001907 @Override
1908 public Account[] getAccountsForPackage(String packageName, int uid) {
1909 int callingUid = Binder.getCallingUid();
1910 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
1911 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
1912 + callingUid + " with uid=" + uid);
1913 }
1914 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
1915 }
1916
Amith Yamasani3b458ad2013-04-18 18:40:07 -07001917 @Override
1918 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
1919 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
1920 int packageUid = -1;
1921 try {
1922 packageUid = AppGlobals.getPackageManager().getPackageUid(
1923 packageName, UserHandle.getCallingUserId());
1924 } catch (RemoteException re) {
1925 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
1926 return new Account[0];
1927 }
1928 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
1929 }
1930
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001931 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001932 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001933 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1934 Log.v(TAG, "getAccounts: accountType " + type
1935 + ", response " + response
1936 + ", features " + stringArrayToString(features)
1937 + ", caller's uid " + Binder.getCallingUid()
1938 + ", pid " + Binder.getCallingPid());
1939 }
Fred Quintana382601f2010-03-25 12:25:10 -07001940 if (response == null) throw new IllegalArgumentException("response is null");
1941 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001942 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001943 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001944 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001945 long identityToken = clearCallingIdentity();
1946 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001947 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001948 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001949 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001950 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001951 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001952 Bundle result = new Bundle();
1953 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1954 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001955 return;
1956 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001957 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
1958 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001959 } finally {
1960 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001961 }
1962 }
1963
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001964 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001965 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001966 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001967 try {
1968 if (cursor.moveToNext()) {
1969 return cursor.getLong(0);
1970 }
1971 return -1;
1972 } finally {
1973 cursor.close();
1974 }
1975 }
1976
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001977 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001978 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1979 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1980 new String[]{key}, null, null, null);
1981 try {
1982 if (cursor.moveToNext()) {
1983 return cursor.getLong(0);
1984 }
1985 return -1;
1986 } finally {
1987 cursor.close();
1988 }
1989 }
1990
Fred Quintanaa698f422009-04-08 19:14:54 -07001991 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001992 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001993 IAccountManagerResponse mResponse;
1994 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001995 final boolean mExpectActivityLaunch;
1996 final long mCreationTime;
1997
Fred Quintana33269202009-04-20 16:05:10 -07001998 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001999 private int mNumRequestContinued = 0;
2000 private int mNumErrors = 0;
2001
Fred Quintana60307342009-03-24 22:48:12 -07002002 IAccountAuthenticator mAuthenticator = null;
2003
Fred Quintana8570f742010-02-18 10:32:54 -08002004 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002005 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002006
Amith Yamasani04e0d262012-02-14 11:50:53 -08002007 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08002008 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07002009 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002010 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002011 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002012 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002013 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002014 mResponse = response;
2015 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002016 mExpectActivityLaunch = expectActivityLaunch;
2017 mCreationTime = SystemClock.elapsedRealtime();
2018 synchronized (mSessions) {
2019 mSessions.put(toString(), this);
2020 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002021 if (response != null) {
2022 try {
2023 response.asBinder().linkToDeath(this, 0 /* flags */);
2024 } catch (RemoteException e) {
2025 mResponse = null;
2026 binderDied();
2027 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002028 }
Fred Quintana60307342009-03-24 22:48:12 -07002029 }
2030
Fred Quintanaa698f422009-04-08 19:14:54 -07002031 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002032 if (mResponse == null) {
2033 // this session has already been closed
2034 return null;
2035 }
Fred Quintana60307342009-03-24 22:48:12 -07002036 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002037 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002038 return response;
2039 }
2040
Fred Quintanaa698f422009-04-08 19:14:54 -07002041 private void close() {
2042 synchronized (mSessions) {
2043 if (mSessions.remove(toString()) == null) {
2044 // the session was already closed, so bail out now
2045 return;
2046 }
2047 }
2048 if (mResponse != null) {
2049 // stop listening for response deaths
2050 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2051
2052 // clear this so that we don't accidentally send any further results
2053 mResponse = null;
2054 }
2055 cancelTimeout();
2056 unbind();
2057 }
2058
2059 public void binderDied() {
2060 mResponse = null;
2061 close();
2062 }
2063
2064 protected String toDebugString() {
2065 return toDebugString(SystemClock.elapsedRealtime());
2066 }
2067
2068 protected String toDebugString(long now) {
2069 return "Session: expectLaunch " + mExpectActivityLaunch
2070 + ", connected " + (mAuthenticator != null)
2071 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2072 + "/" + mNumErrors + ")"
2073 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2074 }
2075
Fred Quintana60307342009-03-24 22:48:12 -07002076 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002077 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2078 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2079 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002080 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002081 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002082 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002083 }
2084 }
2085
2086 private void unbind() {
2087 if (mAuthenticator != null) {
2088 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002089 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002090 }
2091 }
2092
2093 public void scheduleTimeout() {
2094 mMessageHandler.sendMessageDelayed(
2095 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2096 }
2097
2098 public void cancelTimeout() {
2099 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2100 }
2101
Fred Quintanab839afc2009-10-14 15:57:28 -07002102 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002103 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002104 try {
2105 run();
2106 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002107 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002108 "remote exception");
2109 }
Fred Quintana60307342009-03-24 22:48:12 -07002110 }
2111
Fred Quintanab839afc2009-10-14 15:57:28 -07002112 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002113 mAuthenticator = null;
2114 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002115 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002116 try {
2117 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2118 "disconnected");
2119 } catch (RemoteException e) {
2120 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2121 Log.v(TAG, "Session.onServiceDisconnected: "
2122 + "caught RemoteException while responding", e);
2123 }
2124 }
Fred Quintana60307342009-03-24 22:48:12 -07002125 }
2126 }
2127
Fred Quintanab839afc2009-10-14 15:57:28 -07002128 public abstract void run() throws RemoteException;
2129
Fred Quintana60307342009-03-24 22:48:12 -07002130 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002131 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002132 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002133 try {
2134 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2135 "timeout");
2136 } catch (RemoteException e) {
2137 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2138 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2139 e);
2140 }
2141 }
Fred Quintana60307342009-03-24 22:48:12 -07002142 }
2143 }
2144
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002145 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002146 public void onResult(Bundle result) {
2147 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002148 Intent intent = null;
2149 if (result != null
2150 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2151 /*
2152 * The Authenticator API allows third party authenticators to
2153 * supply arbitrary intents to other apps that they can run,
2154 * this can be very bad when those apps are in the system like
2155 * the System Settings.
2156 */
2157 PackageManager pm = mContext.getPackageManager();
2158 ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
2159 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2160 int authenticatorUid = Binder.getCallingUid();
2161 if (PackageManager.SIGNATURE_MATCH !=
2162 pm.checkSignatures(authenticatorUid, targetUid)) {
2163 throw new SecurityException(
2164 "Activity to be started with KEY_INTENT must " +
2165 "share Authenticator's signatures");
2166 }
2167 }
2168 if (result != null
2169 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002170 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2171 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002172 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2173 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002174 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2175 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002176 }
Fred Quintana60307342009-03-24 22:48:12 -07002177 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002178 IAccountManagerResponse response;
2179 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002180 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002181 response = mResponse;
2182 } else {
2183 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002184 }
Fred Quintana60307342009-03-24 22:48:12 -07002185 if (response != null) {
2186 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002187 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002188 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2189 Log.v(TAG, getClass().getSimpleName()
2190 + " calling onError() on response " + response);
2191 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002192 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002193 "null bundle returned");
2194 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002195 if (mStripAuthTokenFromResult) {
2196 result.remove(AccountManager.KEY_AUTHTOKEN);
2197 }
Fred Quintana56285a62010-12-02 14:20:51 -08002198 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2199 Log.v(TAG, getClass().getSimpleName()
2200 + " calling onResult() on response " + response);
2201 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002202 response.onResult(result);
2203 }
Fred Quintana60307342009-03-24 22:48:12 -07002204 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002205 // if the caller is dead then there is no one to care about remote exceptions
2206 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2207 Log.v(TAG, "failure while notifying response", e);
2208 }
Fred Quintana60307342009-03-24 22:48:12 -07002209 }
2210 }
2211 }
Fred Quintana60307342009-03-24 22:48:12 -07002212
Fred Quintanaa698f422009-04-08 19:14:54 -07002213 public void onRequestContinued() {
2214 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002215 }
2216
2217 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002218 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002219 IAccountManagerResponse response = getResponseAndClose();
2220 if (response != null) {
2221 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002222 Log.v(TAG, getClass().getSimpleName()
2223 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002224 }
2225 try {
2226 response.onError(errorCode, errorMessage);
2227 } catch (RemoteException e) {
2228 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2229 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2230 }
2231 }
2232 } else {
2233 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2234 Log.v(TAG, "Session.onError: already closed");
2235 }
Fred Quintana60307342009-03-24 22:48:12 -07002236 }
2237 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002238
2239 /**
2240 * find the component name for the authenticator and initiate a bind
2241 * if no authenticator or the bind fails then return false, otherwise return true
2242 */
2243 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002244 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2245 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2246 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002247 if (authenticatorInfo == null) {
2248 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2249 Log.v(TAG, "there is no authenticator for " + authenticatorType
2250 + ", bailing out");
2251 }
2252 return false;
2253 }
2254
2255 Intent intent = new Intent();
2256 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2257 intent.setComponent(authenticatorInfo.componentName);
2258 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2259 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2260 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002261 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2262 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002263 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2264 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2265 }
2266 return false;
2267 }
2268
2269
2270 return true;
2271 }
Fred Quintana60307342009-03-24 22:48:12 -07002272 }
2273
2274 private class MessageHandler extends Handler {
2275 MessageHandler(Looper looper) {
2276 super(looper);
2277 }
Costin Manolache3348f142009-09-29 18:58:36 -07002278
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002279 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002280 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002281 switch (msg.what) {
2282 case MESSAGE_TIMED_OUT:
2283 Session session = (Session)msg.obj;
2284 session.onTimedOut();
2285 break;
2286
Amith Yamasani5be347b2013-03-31 17:44:31 -07002287 case MESSAGE_COPY_SHARED_ACCOUNT:
2288 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2289 break;
2290
Fred Quintana60307342009-03-24 22:48:12 -07002291 default:
2292 throw new IllegalStateException("unhandled message: " + msg.what);
2293 }
2294 }
2295 }
2296
Amith Yamasani04e0d262012-02-14 11:50:53 -08002297 private static String getDatabaseName(int userId) {
2298 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002299 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002300 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002301 // Migrate old file, if it exists, to the new location.
2302 // Make sure the new file doesn't already exist. A dummy file could have been
2303 // accidentally created in the old location, causing the new one to become corrupted
2304 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002305 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002306 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002307 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002308 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002309 if (!userDir.exists()) {
2310 if (!userDir.mkdirs()) {
2311 throw new IllegalStateException("User dir cannot be created: " + userDir);
2312 }
2313 }
2314 if (!oldFile.renameTo(databaseFile)) {
2315 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2316 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002317 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002318 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002319 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002320 }
2321
Amith Yamasani04e0d262012-02-14 11:50:53 -08002322 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002323
Amith Yamasani04e0d262012-02-14 11:50:53 -08002324 public DatabaseHelper(Context context, int userId) {
2325 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002326 }
2327
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002328 /**
2329 * This call needs to be made while the mCacheLock is held. The way to
2330 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2331 * @param db The database.
2332 */
Fred Quintana60307342009-03-24 22:48:12 -07002333 @Override
2334 public void onCreate(SQLiteDatabase db) {
2335 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2336 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2337 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2338 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2339 + ACCOUNTS_PASSWORD + " TEXT, "
2340 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2341
2342 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2343 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2344 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2345 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2346 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2347 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2348
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002349 createGrantsTable(db);
2350
Fred Quintana60307342009-03-24 22:48:12 -07002351 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2352 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2353 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2354 + EXTRAS_KEY + " TEXT NOT NULL, "
2355 + EXTRAS_VALUE + " TEXT, "
2356 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2357
2358 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2359 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2360 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002361
Amith Yamasani67df64b2012-12-14 12:09:36 -08002362 createSharedAccountsTable(db);
2363
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002364 createAccountsDeletionTrigger(db);
2365 }
2366
Amith Yamasani67df64b2012-12-14 12:09:36 -08002367 private void createSharedAccountsTable(SQLiteDatabase db) {
2368 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2369 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2370 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2371 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2372 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2373 }
2374
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002375 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002376 db.execSQL(""
2377 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2378 + " BEGIN"
2379 + " DELETE FROM " + TABLE_AUTHTOKENS
2380 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2381 + " DELETE FROM " + TABLE_EXTRAS
2382 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002383 + " DELETE FROM " + TABLE_GRANTS
2384 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002385 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002386 }
2387
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002388 private void createGrantsTable(SQLiteDatabase db) {
2389 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2390 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2391 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2392 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2393 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2394 + "," + GRANTS_GRANTEE_UID + "))");
2395 }
2396
Fred Quintana60307342009-03-24 22:48:12 -07002397 @Override
2398 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002399 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002400
Fred Quintanaa698f422009-04-08 19:14:54 -07002401 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002402 // no longer need to do anything since the work is done
2403 // when upgrading from version 2
2404 oldVersion++;
2405 }
2406
2407 if (oldVersion == 2) {
2408 createGrantsTable(db);
2409 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2410 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002411 oldVersion++;
2412 }
Costin Manolache3348f142009-09-29 18:58:36 -07002413
2414 if (oldVersion == 3) {
2415 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2416 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2417 oldVersion++;
2418 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002419
2420 if (oldVersion == 4) {
2421 createSharedAccountsTable(db);
2422 oldVersion++;
2423 }
2424
2425 if (oldVersion != newVersion) {
2426 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2427 }
Fred Quintana60307342009-03-24 22:48:12 -07002428 }
2429
2430 @Override
2431 public void onOpen(SQLiteDatabase db) {
2432 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2433 }
2434 }
2435
Fred Quintana60307342009-03-24 22:48:12 -07002436 public IBinder onBind(Intent intent) {
2437 return asBinder();
2438 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002439
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002440 /**
2441 * Searches array of arguments for the specified string
2442 * @param args array of argument strings
2443 * @param value value to search for
2444 * @return true if the value is contained in the array
2445 */
2446 private static boolean scanArgs(String[] args, String value) {
2447 if (args != null) {
2448 for (String arg : args) {
2449 if (value.equals(arg)) {
2450 return true;
2451 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002452 }
2453 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002454 return false;
2455 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002456
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002457 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002458 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002459 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2460 != PackageManager.PERMISSION_GRANTED) {
2461 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2462 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2463 + " without permission " + android.Manifest.permission.DUMP);
2464 return;
2465 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002466 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002467 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002468
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002469 final List<UserInfo> users = getUserManager().getUsers();
2470 for (UserInfo user : users) {
2471 ipw.println("User " + user + ":");
2472 ipw.increaseIndent();
2473 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2474 ipw.println();
2475 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002476 }
2477 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002478
Amith Yamasani04e0d262012-02-14 11:50:53 -08002479 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2480 String[] args, boolean isCheckinRequest) {
2481 synchronized (userAccounts.cacheLock) {
2482 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002483
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002484 if (isCheckinRequest) {
2485 // This is a checkin request. *Only* upload the account types and the count of each.
2486 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2487 null, null, ACCOUNTS_TYPE, null, null);
2488 try {
2489 while (cursor.moveToNext()) {
2490 // print type,count
2491 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2492 }
2493 } finally {
2494 if (cursor != null) {
2495 cursor.close();
2496 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002497 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002498 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002499 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002500 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002501 fout.println("Accounts: " + accounts.length);
2502 for (Account account : accounts) {
2503 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002504 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002505
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002506 fout.println();
2507 synchronized (mSessions) {
2508 final long now = SystemClock.elapsedRealtime();
2509 fout.println("Active Sessions: " + mSessions.size());
2510 for (Session session : mSessions.values()) {
2511 fout.println(" " + session.toDebugString(now));
2512 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002513 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002514
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002515 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002516 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002517 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002518 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002519 }
2520
Amith Yamasani04e0d262012-02-14 11:50:53 -08002521 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002522 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002523 long identityToken = clearCallingIdentity();
2524 try {
2525 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2526 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2527 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002528
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002529 if (intent.getComponent() != null &&
2530 GrantCredentialsPermissionActivity.class.getName().equals(
2531 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002532 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002533 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002534 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002535 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002536 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2537 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002538 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002539 final String notificationTitleFormat =
2540 mContext.getText(R.string.notification_title).toString();
2541 n.setLatestEventInfo(mContext,
2542 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002543 message, PendingIntent.getActivityAsUser(
2544 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002545 null, user));
2546 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002547 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002548 } finally {
2549 restoreCallingIdentity(identityToken);
2550 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002551 }
2552
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002553 protected void installNotification(final int notificationId, final Notification n,
2554 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002555 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002556 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002557 }
2558
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002559 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002560 long identityToken = clearCallingIdentity();
2561 try {
2562 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002563 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002564 } finally {
2565 restoreCallingIdentity(identityToken);
2566 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002567 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002568
Fred Quintanab38eb142010-02-24 13:40:54 -08002569 /** Succeeds if any of the specified permissions are granted. */
2570 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002571 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002572
2573 for (String perm : permissions) {
2574 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2575 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002576 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002577 }
2578 return;
2579 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002580 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002581
2582 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002583 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002584 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002585 }
2586
Amith Yamasani67df64b2012-12-14 12:09:36 -08002587 private int handleIncomingUser(int userId) {
2588 try {
2589 return ActivityManagerNative.getDefault().handleIncomingUser(
2590 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2591 } catch (RemoteException re) {
2592 // Shouldn't happen, local.
2593 }
2594 return userId;
2595 }
2596
Christopher Tateccbf84f2013-05-08 15:25:41 -07002597 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002598 final int callingUserId = UserHandle.getUserId(callingUid);
2599
2600 final PackageManager userPackageManager;
2601 try {
2602 userPackageManager = mContext.createPackageContextAsUser(
2603 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2604 } catch (NameNotFoundException e) {
2605 return false;
2606 }
2607
2608 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002609 for (String name : packages) {
2610 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002611 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002612 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07002613 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002614 return true;
2615 }
2616 } catch (PackageManager.NameNotFoundException e) {
2617 return false;
2618 }
2619 }
2620 return false;
2621 }
2622
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002623 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07002624 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002625 final boolean fromAuthenticator = account != null
2626 && hasAuthenticatorUid(account.type, callerUid);
2627 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002628 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002629 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2630 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002631 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002632 + ": is authenticator? " + fromAuthenticator
2633 + ", has explicit permission? " + hasExplicitGrants);
2634 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07002635 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002636 }
2637
Fred Quintana1a231912009-10-15 11:31:30 -07002638 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002639 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002640 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002641 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002642 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002643 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002644 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002645 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002646 }
2647 }
2648 return false;
2649 }
2650
Amith Yamasani04e0d262012-02-14 11:50:53 -08002651 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2652 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002653 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002654 return true;
2655 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002656 UserAccounts accounts = getUserAccountsForCaller();
2657 synchronized (accounts.cacheLock) {
2658 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2659 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002660 account.name, account.type};
2661 final boolean permissionGranted =
2662 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2663 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2664 // TODO: Skip this check when running automated tests. Replace this
2665 // with a more general solution.
2666 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002667 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002668 + " but ignoring since device is in test harness.");
2669 return true;
2670 }
2671 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002672 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002673 }
2674
2675 private void checkCallingUidAgainstAuthenticator(Account account) {
2676 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002677 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002678 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2679 Log.w(TAG, msg);
2680 throw new SecurityException(msg);
2681 }
2682 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2683 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2684 }
2685 }
2686
2687 private void checkAuthenticateAccountsPermission(Account account) {
2688 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2689 checkCallingUidAgainstAuthenticator(account);
2690 }
2691
2692 private void checkReadAccountsPermission() {
2693 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2694 }
2695
2696 private void checkManageAccountsPermission() {
2697 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2698 }
2699
Fred Quintanab38eb142010-02-24 13:40:54 -08002700 private void checkManageAccountsOrUseCredentialsPermissions() {
2701 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2702 Manifest.permission.USE_CREDENTIALS);
2703 }
2704
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002705 private boolean canUserModifyAccounts(int callingUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002706 if (callingUid != Process.myUid()) {
2707 if (getUserManager().getUserRestrictions(
2708 new UserHandle(UserHandle.getUserId(callingUid)))
2709 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002710 return false;
2711 }
2712 }
2713 return true;
2714 }
2715
Fred Quintanad9640ec2012-05-23 12:37:00 -07002716 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2717 throws RemoteException {
2718 final int callingUid = getCallingUid();
2719
Amith Yamasani27db4682013-03-30 17:07:47 -07002720 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002721 throw new SecurityException();
2722 }
2723
2724 if (value) {
2725 grantAppPermission(account, authTokenType, uid);
2726 } else {
2727 revokeAppPermission(account, authTokenType, uid);
2728 }
2729 }
2730
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002731 /**
2732 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2733 * <p>
2734 * Although this is public it can only be accessed via the AccountManagerService object
2735 * which is in the system. This means we don't need to protect it with permissions.
2736 * @hide
2737 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002738 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002739 if (account == null || authTokenType == null) {
2740 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002741 return;
2742 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002743 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002744 synchronized (accounts.cacheLock) {
2745 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002746 db.beginTransaction();
2747 try {
2748 long accountId = getAccountIdLocked(db, account);
2749 if (accountId >= 0) {
2750 ContentValues values = new ContentValues();
2751 values.put(GRANTS_ACCOUNTS_ID, accountId);
2752 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2753 values.put(GRANTS_GRANTEE_UID, uid);
2754 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2755 db.setTransactionSuccessful();
2756 }
2757 } finally {
2758 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002759 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002760 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2761 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002762 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002763 }
2764
2765 /**
2766 * Don't allow callers with the given uid permission to get credentials for
2767 * account/authTokenType.
2768 * <p>
2769 * Although this is public it can only be accessed via the AccountManagerService object
2770 * which is in the system. This means we don't need to protect it with permissions.
2771 * @hide
2772 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002773 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002774 if (account == null || authTokenType == null) {
2775 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002776 return;
2777 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002778 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002779 synchronized (accounts.cacheLock) {
2780 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002781 db.beginTransaction();
2782 try {
2783 long accountId = getAccountIdLocked(db, account);
2784 if (accountId >= 0) {
2785 db.delete(TABLE_GRANTS,
2786 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2787 + GRANTS_GRANTEE_UID + "=?",
2788 new String[]{String.valueOf(accountId), authTokenType,
2789 String.valueOf(uid)});
2790 db.setTransactionSuccessful();
2791 }
2792 } finally {
2793 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002794 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002795 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2796 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002797 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002798 }
Fred Quintana56285a62010-12-02 14:20:51 -08002799
2800 static final private String stringArrayToString(String[] value) {
2801 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2802 }
2803
Amith Yamasani04e0d262012-02-14 11:50:53 -08002804 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2805 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002806 if (oldAccountsForType != null) {
2807 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2808 for (Account curAccount : oldAccountsForType) {
2809 if (!curAccount.equals(account)) {
2810 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002811 }
2812 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002813 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002814 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002815 } else {
2816 Account[] newAccountsForType = new Account[newAccountsList.size()];
2817 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002818 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002819 }
Fred Quintana56285a62010-12-02 14:20:51 -08002820 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002821 accounts.userDataCache.remove(account);
2822 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002823 }
2824
2825 /**
2826 * This assumes that the caller has already checked that the account is not already present.
2827 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002828 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2829 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002830 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2831 Account[] newAccountsForType = new Account[oldLength + 1];
2832 if (accountsForType != null) {
2833 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002834 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002835 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002836 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002837 }
2838
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002839 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07002840 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002841 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07002842 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002843 return unfiltered;
2844 }
2845 if (mUserManager.getUserInfo(userAccounts.userId).isRestricted()) {
2846 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002847 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002848 // otherwise return non-shared accounts only.
2849 // This might be a temporary way to specify a whitelist
2850 String whiteList = mContext.getResources().getString(
2851 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2852 for (String packageName : packages) {
2853 if (whiteList.contains(";" + packageName + ";")) {
2854 return unfiltered;
2855 }
2856 }
2857 ArrayList<Account> allowed = new ArrayList<Account>();
2858 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2859 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002860 String requiredAccountType = "";
2861 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07002862 // If there's an explicit callingPackage specified, check if that package
2863 // opted in to see restricted accounts.
2864 if (callingPackage != null) {
2865 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002866 if (pi != null && pi.restrictedAccountType != null) {
2867 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07002868 }
2869 } else {
2870 // Otherwise check if the callingUid has a package that has opted in
2871 for (String packageName : packages) {
2872 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
2873 if (pi != null && pi.restrictedAccountType != null) {
2874 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07002875 break;
2876 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002877 }
2878 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002879 } catch (NameNotFoundException nnfe) {
2880 }
2881 for (Account account : unfiltered) {
2882 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002883 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002884 } else {
2885 boolean found = false;
2886 for (Account shared : sharedAccounts) {
2887 if (shared.equals(account)) {
2888 found = true;
2889 break;
2890 }
2891 }
2892 if (!found) {
2893 allowed.add(account);
2894 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002895 }
2896 }
2897 Account[] filtered = new Account[allowed.size()];
2898 allowed.toArray(filtered);
2899 return filtered;
2900 } else {
2901 return unfiltered;
2902 }
2903 }
2904
Amith Yamasani27db4682013-03-30 17:07:47 -07002905 /*
2906 * packageName can be null. If not null, it should be used to filter out restricted accounts
2907 * that the package is not allowed to access.
2908 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002909 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07002910 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002911 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002912 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002913 if (accounts == null) {
2914 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002915 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002916 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07002917 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002918 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002919 } else {
2920 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002921 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002922 totalLength += accounts.length;
2923 }
2924 if (totalLength == 0) {
2925 return EMPTY_ACCOUNT_ARRAY;
2926 }
2927 Account[] accounts = new Account[totalLength];
2928 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002929 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002930 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2931 accountsOfType.length);
2932 totalLength += accountsOfType.length;
2933 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002934 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002935 }
2936 }
2937
Amith Yamasani04e0d262012-02-14 11:50:53 -08002938 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2939 Account account, String key, String value) {
2940 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002941 if (userDataForAccount == null) {
2942 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002943 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002944 }
2945 if (value == null) {
2946 userDataForAccount.remove(key);
2947 } else {
2948 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002949 }
2950 }
2951
Amith Yamasani04e0d262012-02-14 11:50:53 -08002952 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2953 Account account, String key, String value) {
2954 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002955 if (authTokensForAccount == null) {
2956 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002957 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002958 }
2959 if (value == null) {
2960 authTokensForAccount.remove(key);
2961 } else {
2962 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002963 }
2964 }
2965
Amith Yamasani04e0d262012-02-14 11:50:53 -08002966 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2967 String authTokenType) {
2968 synchronized (accounts.cacheLock) {
2969 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002970 if (authTokensForAccount == null) {
2971 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002972 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002973 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002974 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002975 }
2976 return authTokensForAccount.get(authTokenType);
2977 }
2978 }
2979
Amith Yamasani04e0d262012-02-14 11:50:53 -08002980 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2981 synchronized (accounts.cacheLock) {
2982 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002983 if (userDataForAccount == null) {
2984 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002985 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002986 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002987 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002988 }
2989 return userDataForAccount.get(key);
2990 }
2991 }
2992
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002993 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2994 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002995 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002996 Cursor cursor = db.query(TABLE_EXTRAS,
2997 COLUMNS_EXTRAS_KEY_AND_VALUE,
2998 SELECTION_USERDATA_BY_ACCOUNT,
2999 new String[]{account.name, account.type},
3000 null, null, null);
3001 try {
3002 while (cursor.moveToNext()) {
3003 final String tmpkey = cursor.getString(0);
3004 final String value = cursor.getString(1);
3005 userDataForAccount.put(tmpkey, value);
3006 }
3007 } finally {
3008 cursor.close();
3009 }
3010 return userDataForAccount;
3011 }
3012
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003013 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3014 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003015 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003016 Cursor cursor = db.query(TABLE_AUTHTOKENS,
3017 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3018 SELECTION_AUTHTOKENS_BY_ACCOUNT,
3019 new String[]{account.name, account.type},
3020 null, null, null);
3021 try {
3022 while (cursor.moveToNext()) {
3023 final String type = cursor.getString(0);
3024 final String authToken = cursor.getString(1);
3025 authTokensForAccount.put(type, authToken);
3026 }
3027 } finally {
3028 cursor.close();
3029 }
3030 return authTokensForAccount;
3031 }
Fred Quintana60307342009-03-24 22:48:12 -07003032}