blob: aa9849ef56416e9f6bc0ff20f7c92cddc51a3572 [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080020import android.accounts.Account;
21import android.accounts.AccountAndUser;
22import android.accounts.AccountAuthenticatorResponse;
23import android.accounts.AccountManager;
24import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070025import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080026import android.accounts.GrantCredentialsPermissionActivity;
27import android.accounts.IAccountAuthenticator;
28import android.accounts.IAccountAuthenticatorResponse;
29import android.accounts.IAccountManager;
30import android.accounts.IAccountManagerResponse;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080031import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070032import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070033import android.app.AppGlobals;
Doug Zongker885cfc232009-10-21 16:52:44 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070037import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070038import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070039import android.content.ContentValues;
40import android.content.Context;
41import android.content.Intent;
42import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070043import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070044import android.content.pm.ApplicationInfo;
45import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070046import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070047import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070048import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070049import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070050import android.content.pm.ResolveInfo;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070051import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070052import android.database.Cursor;
53import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070054import android.database.sqlite.SQLiteDatabase;
55import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070056import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070057import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080058import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070059import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070060import android.os.IBinder;
61import android.os.Looper;
62import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070063import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070064import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import android.os.RemoteException;
66import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070068import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.text.TextUtils;
70import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070071import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070072import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080073import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070074
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070075import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080076import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080077import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070078import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070079import com.google.android.collect.Lists;
80import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070081
Oscar Montemayora8529f62009-11-18 10:14:20 -080082import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070083import java.io.FileDescriptor;
84import java.io.PrintWriter;
85import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080086import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070087import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070088import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070089import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080090import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070091import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080092import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070093import java.util.concurrent.atomic.AtomicInteger;
94import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070095
Fred Quintana60307342009-03-24 22:48:12 -070096/**
97 * A system service that provides account, password, and authtoken management for all
98 * accounts on the device. Some of these calls are implemented with the help of the corresponding
99 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
100 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700101 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700102 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700103 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700104public class AccountManagerService
105 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800106 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700107 private static final String TAG = "AccountManagerService";
108
109 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
110 private static final String DATABASE_NAME = "accounts.db";
Amith Yamasani67df64b2012-12-14 12:09:36 -0800111 private static final int DATABASE_VERSION = 5;
Fred Quintana60307342009-03-24 22:48:12 -0700112
113 private final Context mContext;
114
Fred Quintana56285a62010-12-02 14:20:51 -0800115 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700116 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800117
Fred Quintana60307342009-03-24 22:48:12 -0700118 private final MessageHandler mMessageHandler;
119
120 // Messages that can be sent on mHandler
121 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700122 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700123
Fred Quintana56285a62010-12-02 14:20:51 -0800124 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700125
126 private static final String TABLE_ACCOUNTS = "accounts";
127 private static final String ACCOUNTS_ID = "_id";
128 private static final String ACCOUNTS_NAME = "name";
129 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700130 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700131 private static final String ACCOUNTS_PASSWORD = "password";
132
133 private static final String TABLE_AUTHTOKENS = "authtokens";
134 private static final String AUTHTOKENS_ID = "_id";
135 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
136 private static final String AUTHTOKENS_TYPE = "type";
137 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
138
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700139 private static final String TABLE_GRANTS = "grants";
140 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
141 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
142 private static final String GRANTS_GRANTEE_UID = "uid";
143
Fred Quintana60307342009-03-24 22:48:12 -0700144 private static final String TABLE_EXTRAS = "extras";
145 private static final String EXTRAS_ID = "_id";
146 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
147 private static final String EXTRAS_KEY = "key";
148 private static final String EXTRAS_VALUE = "value";
149
150 private static final String TABLE_META = "meta";
151 private static final String META_KEY = "key";
152 private static final String META_VALUE = "value";
153
Amith Yamasani67df64b2012-12-14 12:09:36 -0800154 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
155
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700156 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
157 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700158 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700159
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700160 private static final String COUNT_OF_MATCHING_GRANTS = ""
161 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
162 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
163 + " AND " + GRANTS_GRANTEE_UID + "=?"
164 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
165 + " AND " + ACCOUNTS_NAME + "=?"
166 + " AND " + ACCOUNTS_TYPE + "=?";
167
Fred Quintana56285a62010-12-02 14:20:51 -0800168 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
169 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
170 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
171 AUTHTOKENS_AUTHTOKEN};
172
173 private static final String SELECTION_USERDATA_BY_ACCOUNT =
174 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
175 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
176
Fred Quintanaa698f422009-04-08 19:14:54 -0700177 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700178 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
179
Amith Yamasani04e0d262012-02-14 11:50:53 -0800180 static class UserAccounts {
181 private final int userId;
182 private final DatabaseHelper openHelper;
183 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
184 credentialsPermissionNotificationIds =
185 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
186 private final HashMap<Account, Integer> signinRequiredNotificationIds =
187 new HashMap<Account, Integer>();
188 private final Object cacheLock = new Object();
189 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700190 private final HashMap<String, Account[]> accountCache =
191 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800192 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800193 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800194 new HashMap<Account, HashMap<String, String>>();
195 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800196 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800197 new HashMap<Account, HashMap<String, String>>();
198
199 UserAccounts(Context context, int userId) {
200 this.userId = userId;
201 synchronized (cacheLock) {
202 openHelper = new DatabaseHelper(context, userId);
203 }
204 }
205 }
206
207 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
208
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700209 private static AtomicReference<AccountManagerService> sThis =
210 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700211 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700212
213 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700214 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700215 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
216 }
217
Fred Quintana56285a62010-12-02 14:20:51 -0800218
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700219 /**
220 * This should only be called by system code. One should only call this after the service
221 * has started.
222 * @return a reference to the AccountManagerService instance
223 * @hide
224 */
225 public static AccountManagerService getSingleton() {
226 return sThis.get();
227 }
Fred Quintana60307342009-03-24 22:48:12 -0700228
Fred Quintana56285a62010-12-02 14:20:51 -0800229 public AccountManagerService(Context context) {
230 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700231 }
232
Fred Quintana56285a62010-12-02 14:20:51 -0800233 public AccountManagerService(Context context, PackageManager packageManager,
234 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700235 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800236 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700237
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700238 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700239
Fred Quintana56285a62010-12-02 14:20:51 -0800240 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800241 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700242
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700243 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800244
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800245 IntentFilter intentFilter = new IntentFilter();
246 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
247 intentFilter.addDataScheme("package");
248 mContext.registerReceiver(new BroadcastReceiver() {
249 @Override
250 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800251 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800252 }
253 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800254
Amith Yamasani13593602012-03-22 16:16:17 -0700255 IntentFilter userFilter = new IntentFilter();
256 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800257 userFilter.addAction(Intent.ACTION_USER_STARTED);
258 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700259 @Override
260 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800261 String action = intent.getAction();
262 if (Intent.ACTION_USER_REMOVED.equals(action)) {
263 onUserRemoved(intent);
264 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
265 onUserStarted(intent);
266 }
Amith Yamasani13593602012-03-22 16:16:17 -0700267 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800268 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800269 }
270
Dianne Hackborn164371f2013-10-01 19:10:13 -0700271 @Override
272 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
273 throws RemoteException {
274 try {
275 return super.onTransact(code, data, reply, flags);
276 } catch (RuntimeException e) {
277 // The account manager only throws security exceptions, so let's
278 // log all others.
279 if (!(e instanceof SecurityException)) {
280 Slog.wtf(TAG, "Account Manager Crash", e);
281 }
282 throw e;
283 }
284 }
285
Kenny Root26ff6622012-07-30 12:58:03 -0700286 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700287 }
288
Amith Yamasani258848d2012-08-10 17:06:33 -0700289 private UserManager getUserManager() {
290 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700291 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700292 }
293 return mUserManager;
294 }
295
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700296 /* Caller should lock mUsers */
297 private UserAccounts initUserLocked(int userId) {
298 UserAccounts accounts = mUsers.get(userId);
299 if (accounts == null) {
300 accounts = new UserAccounts(mContext, userId);
301 mUsers.append(userId, accounts);
302 purgeOldGrants(accounts);
303 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800304 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700305 return accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800306 }
307
308 private void purgeOldGrantsAll() {
309 synchronized (mUsers) {
310 for (int i = 0; i < mUsers.size(); i++) {
311 purgeOldGrants(mUsers.valueAt(i));
312 }
313 }
314 }
315
316 private void purgeOldGrants(UserAccounts accounts) {
317 synchronized (accounts.cacheLock) {
318 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800319 final Cursor cursor = db.query(TABLE_GRANTS,
320 new String[]{GRANTS_GRANTEE_UID},
321 null, null, GRANTS_GRANTEE_UID, null, null);
322 try {
323 while (cursor.moveToNext()) {
324 final int uid = cursor.getInt(0);
325 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
326 if (packageExists) {
327 continue;
328 }
329 Log.d(TAG, "deleting grants for UID " + uid
330 + " because its package is no longer installed");
331 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
332 new String[]{Integer.toString(uid)});
333 }
334 } finally {
335 cursor.close();
336 }
337 }
338 }
339
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700340 /**
341 * Validate internal set of accounts against installed authenticators for
342 * given user. Clears cached authenticators before validating.
343 */
344 public void validateAccounts(int userId) {
345 final UserAccounts accounts = getUserAccounts(userId);
346
347 // Invalidate user-specific cache to make sure we catch any
348 // removed authenticators.
349 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
350 }
351
352 /**
353 * Validate internal set of accounts against installed authenticators for
354 * given user. Clear cached authenticators before validating when requested.
355 */
356 private void validateAccountsInternal(
357 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
358 if (invalidateAuthenticatorCache) {
359 mAuthenticatorCache.invalidateCache(accounts.userId);
360 }
361
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700362 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
363 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
364 mAuthenticatorCache.getAllServices(accounts.userId)) {
365 knownAuth.add(service.type);
366 }
367
Amith Yamasani04e0d262012-02-14 11:50:53 -0800368 synchronized (accounts.cacheLock) {
369 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800370 boolean accountDeleted = false;
371 Cursor cursor = db.query(TABLE_ACCOUNTS,
372 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
373 null, null, null, null, null);
374 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800375 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800376 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700377 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800378 while (cursor.moveToNext()) {
379 final long accountId = cursor.getLong(0);
380 final String accountType = cursor.getString(1);
381 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700382
383 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700384 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800385 + accountType + " no longer has a registered authenticator");
386 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
387 accountDeleted = true;
388 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800389 accounts.userDataCache.remove(account);
390 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800391 } else {
392 ArrayList<String> accountNames = accountNamesByType.get(accountType);
393 if (accountNames == null) {
394 accountNames = new ArrayList<String>();
395 accountNamesByType.put(accountType, accountNames);
396 }
397 accountNames.add(accountName);
398 }
399 }
Andy McFadden2f362292012-01-20 14:43:38 -0800400 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800401 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800402 final String accountType = cur.getKey();
403 final ArrayList<String> accountNames = cur.getValue();
404 final Account[] accountsForType = new Account[accountNames.size()];
405 int i = 0;
406 for (String accountName : accountNames) {
407 accountsForType[i] = new Account(accountName, accountType);
408 ++i;
409 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800410 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800411 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800412 } finally {
413 cursor.close();
414 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800415 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800416 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800417 }
418 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700419 }
420
Amith Yamasani04e0d262012-02-14 11:50:53 -0800421 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700422 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800423 }
424
425 protected UserAccounts getUserAccounts(int userId) {
426 synchronized (mUsers) {
427 UserAccounts accounts = mUsers.get(userId);
428 if (accounts == null) {
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700429 accounts = initUserLocked(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800430 mUsers.append(userId, accounts);
431 }
432 return accounts;
433 }
434 }
435
Amith Yamasani13593602012-03-22 16:16:17 -0700436 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700437 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700438 if (userId < 1) return;
439
440 UserAccounts accounts;
441 synchronized (mUsers) {
442 accounts = mUsers.get(userId);
443 mUsers.remove(userId);
444 }
445 if (accounts == null) {
446 File dbFile = new File(getDatabaseName(userId));
447 dbFile.delete();
448 return;
449 }
450
451 synchronized (accounts.cacheLock) {
452 accounts.openHelper.close();
453 File dbFile = new File(getDatabaseName(userId));
454 dbFile.delete();
455 }
456 }
457
Amith Yamasani67df64b2012-12-14 12:09:36 -0800458 private void onUserStarted(Intent intent) {
459 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
460 if (userId < 1) return;
461
462 // Check if there's a shared account that needs to be created as an account
463 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
464 if (sharedAccounts == null || sharedAccounts.length == 0) return;
465 Account[] accounts = getAccountsAsUser(null, userId);
466 for (Account sa : sharedAccounts) {
467 if (ArrayUtils.contains(accounts, sa)) continue;
468 // Account doesn't exist. Copy it now.
469 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
470 }
471 }
472
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700473 @Override
474 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700475 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700476 }
477
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800478 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700479 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800480 if (Log.isLoggable(TAG, Log.VERBOSE)) {
481 Log.v(TAG, "getPassword: " + account
482 + ", caller's uid " + Binder.getCallingUid()
483 + ", pid " + Binder.getCallingPid());
484 }
Fred Quintana382601f2010-03-25 12:25:10 -0700485 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700486 checkAuthenticateAccountsPermission(account);
487
Amith Yamasani04e0d262012-02-14 11:50:53 -0800488 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700489 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700490 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800491 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700492 } finally {
493 restoreCallingIdentity(identityToken);
494 }
495 }
496
Amith Yamasani04e0d262012-02-14 11:50:53 -0800497 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700498 if (account == null) {
499 return null;
500 }
501
Amith Yamasani04e0d262012-02-14 11:50:53 -0800502 synchronized (accounts.cacheLock) {
503 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800504 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
505 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
506 new String[]{account.name, account.type}, null, null, null);
507 try {
508 if (cursor.moveToNext()) {
509 return cursor.getString(0);
510 }
511 return null;
512 } finally {
513 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700514 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 }
516 }
517
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800518 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700519 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800520 if (Log.isLoggable(TAG, Log.VERBOSE)) {
521 Log.v(TAG, "getUserData: " + account
522 + ", key " + key
523 + ", caller's uid " + Binder.getCallingUid()
524 + ", pid " + Binder.getCallingPid());
525 }
Fred Quintana382601f2010-03-25 12:25:10 -0700526 if (account == null) throw new IllegalArgumentException("account is null");
527 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700528 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800529 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700530 long identityToken = clearCallingIdentity();
531 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800532 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700533 } finally {
534 restoreCallingIdentity(identityToken);
535 }
536 }
537
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800538 @Override
Fred Quintana97889762009-06-15 12:29:24 -0700539 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
541 Log.v(TAG, "getAuthenticatorTypes: "
542 + "caller's uid " + Binder.getCallingUid()
543 + ", pid " + Binder.getCallingPid());
544 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700545 final int userId = UserHandle.getCallingUserId();
546 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700547 try {
Fred Quintana97889762009-06-15 12:29:24 -0700548 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700549 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700550 AuthenticatorDescription[] types =
551 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700552 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700553 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700554 : authenticatorCollection) {
555 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700556 i++;
557 }
558 return types;
559 } finally {
560 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700561 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700562 }
563
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700564 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700565 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800566 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700567 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800568 + ", caller's uid " + Binder.getCallingUid()
569 + ", pid " + Binder.getCallingPid());
570 }
Fred Quintana382601f2010-03-25 12:25:10 -0700571 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700572 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700573 /*
574 * Child users are not allowed to add accounts. Only the accounts that are
575 * shared by the parent profile can be added to child profile.
576 *
577 * TODO: Only allow accounts that were shared to be added by
578 * a limited user.
579 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700580
Amith Yamasani04e0d262012-02-14 11:50:53 -0800581 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700582 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700583 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700584 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800585 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700586 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700587 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700588 }
589 }
590
Amith Yamasani67df64b2012-12-14 12:09:36 -0800591 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
592 final UserAccounts fromAccounts = getUserAccounts(userFrom);
593 final UserAccounts toAccounts = getUserAccounts(userTo);
594 if (fromAccounts == null || toAccounts == null) {
595 return false;
596 }
597
598 long identityToken = clearCallingIdentity();
599 try {
600 new Session(fromAccounts, null, account.type, false,
601 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700602 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800603 protected String toDebugString(long now) {
604 return super.toDebugString(now) + ", getAccountCredentialsForClone"
605 + ", " + account.type;
606 }
607
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700608 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800609 public void run() throws RemoteException {
610 mAuthenticator.getAccountCredentialsForCloning(this, account);
611 }
612
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700613 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800614 public void onResult(Bundle result) {
615 if (result != null) {
616 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
617 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800618 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800619 }
620 return;
621 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800622 super.onResult(result);
623 }
624 }
625 }.bind();
626 } finally {
627 restoreCallingIdentity(identityToken);
628 }
629 return true;
630 }
631
Amith Yamasani67df64b2012-12-14 12:09:36 -0800632 void completeCloningAccount(final Bundle result, final Account account,
633 final UserAccounts targetUser) {
634 long id = clearCallingIdentity();
635 try {
636 new Session(targetUser, null, account.type, false,
637 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700638 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800639 protected String toDebugString(long now) {
640 return super.toDebugString(now) + ", getAccountCredentialsForClone"
641 + ", " + account.type;
642 }
643
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700644 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800645 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700646 // Confirm that the owner's account still exists before this step.
647 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
648 synchronized (owner.cacheLock) {
649 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
650 for (Account acc : ownerAccounts) {
651 if (acc.equals(account)) {
652 mAuthenticator.addAccountFromCredentials(this, account, result);
653 break;
654 }
655 }
656 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800657 }
658
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700659 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800660 public void onResult(Bundle result) {
661 if (result != null) {
662 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
663 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800664 } else {
665 // TODO: Show error notification
666 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800667 }
668 return;
669 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800670 super.onResult(result);
671 }
672 }
673
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700674 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800675 public void onError(int errorCode, String errorMessage) {
676 super.onError(errorCode, errorMessage);
677 // TODO: Show error notification to user
678 // TODO: Should we remove the shadow account so that it doesn't keep trying?
679 }
680
681 }.bind();
682 } finally {
683 restoreCallingIdentity(id);
684 }
685 }
686
Amith Yamasani04e0d262012-02-14 11:50:53 -0800687 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800688 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700689 if (account == null) {
690 return false;
691 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800692 synchronized (accounts.cacheLock) {
693 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800694 db.beginTransaction();
695 try {
696 long numMatches = DatabaseUtils.longForQuery(db,
697 "select count(*) from " + TABLE_ACCOUNTS
698 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
699 new String[]{account.name, account.type});
700 if (numMatches > 0) {
701 Log.w(TAG, "insertAccountIntoDatabase: " + account
702 + ", skipping since the account already exists");
703 return false;
704 }
705 ContentValues values = new ContentValues();
706 values.put(ACCOUNTS_NAME, account.name);
707 values.put(ACCOUNTS_TYPE, account.type);
708 values.put(ACCOUNTS_PASSWORD, password);
709 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
710 if (accountId < 0) {
711 Log.w(TAG, "insertAccountIntoDatabase: " + account
712 + ", skipping the DB insert failed");
713 return false;
714 }
715 if (extras != null) {
716 for (String key : extras.keySet()) {
717 final String value = extras.getString(key);
718 if (insertExtraLocked(db, accountId, key, value) < 0) {
719 Log.w(TAG, "insertAccountIntoDatabase: " + account
720 + ", skipping since insertExtra failed for key " + key);
721 return false;
722 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700723 }
724 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800725 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800726 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800727 } finally {
728 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700729 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800730 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700731 }
732 if (accounts.userId == UserHandle.USER_OWNER) {
733 addAccountToLimitedUsers(account);
734 }
735 return true;
736 }
737
738 /**
739 * Adds the account to all limited users as shared accounts. If the user is currently
740 * running, then clone the account too.
741 * @param account the account to share with limited users
742 */
743 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700744 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700745 for (UserInfo user : users) {
746 if (user.isRestricted()) {
747 addSharedAccountAsUser(account, user.id);
748 try {
749 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
750 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
751 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
752 account));
753 }
754 } catch (RemoteException re) {
755 // Shouldn't happen
756 }
757 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700758 }
759 }
760
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800761 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700762 ContentValues values = new ContentValues();
763 values.put(EXTRAS_KEY, key);
764 values.put(EXTRAS_ACCOUNTS_ID, accountId);
765 values.put(EXTRAS_VALUE, value);
766 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
767 }
768
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800769 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -0800770 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800771 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800772 if (Log.isLoggable(TAG, Log.VERBOSE)) {
773 Log.v(TAG, "hasFeatures: " + account
774 + ", response " + response
775 + ", features " + stringArrayToString(features)
776 + ", caller's uid " + Binder.getCallingUid()
777 + ", pid " + Binder.getCallingPid());
778 }
Fred Quintana382601f2010-03-25 12:25:10 -0700779 if (response == null) throw new IllegalArgumentException("response is null");
780 if (account == null) throw new IllegalArgumentException("account is null");
781 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800782 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800783 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800784 long identityToken = clearCallingIdentity();
785 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800786 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800787 } finally {
788 restoreCallingIdentity(identityToken);
789 }
790 }
791
792 private class TestFeaturesSession extends Session {
793 private final String[] mFeatures;
794 private final Account mAccount;
795
Amith Yamasani04e0d262012-02-14 11:50:53 -0800796 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800797 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800798 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800799 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800800 mFeatures = features;
801 mAccount = account;
802 }
803
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700804 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800805 public void run() throws RemoteException {
806 try {
807 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
808 } catch (RemoteException e) {
809 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
810 }
811 }
812
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700813 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800814 public void onResult(Bundle result) {
815 IAccountManagerResponse response = getResponseAndClose();
816 if (response != null) {
817 try {
818 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700819 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800820 return;
821 }
Fred Quintana56285a62010-12-02 14:20:51 -0800822 if (Log.isLoggable(TAG, Log.VERBOSE)) {
823 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
824 + response);
825 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800826 final Bundle newResult = new Bundle();
827 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
828 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
829 response.onResult(newResult);
830 } catch (RemoteException e) {
831 // if the caller is dead then there is no one to care about remote exceptions
832 if (Log.isLoggable(TAG, Log.VERBOSE)) {
833 Log.v(TAG, "failure while notifying response", e);
834 }
835 }
836 }
837 }
838
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700839 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800840 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800841 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800842 + ", " + mAccount
843 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
844 }
845 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800846
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800847 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700848 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800849 if (Log.isLoggable(TAG, Log.VERBOSE)) {
850 Log.v(TAG, "removeAccount: " + account
851 + ", response " + response
852 + ", caller's uid " + Binder.getCallingUid()
853 + ", pid " + Binder.getCallingPid());
854 }
Fred Quintana382601f2010-03-25 12:25:10 -0700855 if (response == null) throw new IllegalArgumentException("response is null");
856 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700857 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700858 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800859 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800860 if (!canUserModifyAccounts(Binder.getCallingUid())) {
861 try {
862 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
863 "User cannot modify accounts");
864 } catch (RemoteException re) {
865 }
866 }
867
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700868 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800869
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700870 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800871 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800872 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800873 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800874 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800875 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700876 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800877 }
878 }
879 }
880
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700881 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800882 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700883 } finally {
884 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700885 }
Fred Quintana60307342009-03-24 22:48:12 -0700886 }
887
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700888 private class RemoveAccountSession extends Session {
889 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800890 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
891 Account account) {
892 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800893 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700894 mAccount = account;
895 }
896
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700897 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700898 protected String toDebugString(long now) {
899 return super.toDebugString(now) + ", removeAccount"
900 + ", account " + mAccount;
901 }
902
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700903 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700904 public void run() throws RemoteException {
905 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
906 }
907
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700908 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700909 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700910 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
911 && !result.containsKey(AccountManager.KEY_INTENT)) {
912 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700913 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800914 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700915 }
916 IAccountManagerResponse response = getResponseAndClose();
917 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800918 if (Log.isLoggable(TAG, Log.VERBOSE)) {
919 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
920 + response);
921 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700922 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700923 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700924 try {
925 response.onResult(result2);
926 } catch (RemoteException e) {
927 // ignore
928 }
929 }
930 }
931 super.onResult(result);
932 }
933 }
934
Amith Yamasani04e0d262012-02-14 11:50:53 -0800935 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800936 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800937 removeAccountInternal(getUserAccountsForCaller(), account);
938 }
939
940 private void removeAccountInternal(UserAccounts accounts, Account account) {
941 synchronized (accounts.cacheLock) {
942 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800943 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
944 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800945 removeAccountFromCacheLocked(accounts, account);
946 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800947 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800948 if (accounts.userId == UserHandle.USER_OWNER) {
949 // Owner's account was removed, remove from any users that are sharing
950 // this account.
951 long id = Binder.clearCallingIdentity();
952 try {
953 List<UserInfo> users = mUserManager.getUsers(true);
954 for (UserInfo user : users) {
955 if (!user.isPrimary() && user.isRestricted()) {
956 removeSharedAccountAsUser(account, user.id);
957 }
958 }
959 } finally {
960 Binder.restoreCallingIdentity(id);
961 }
962 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700963 }
964
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400965 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700966 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800967 if (Log.isLoggable(TAG, Log.VERBOSE)) {
968 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
969 + ", caller's uid " + Binder.getCallingUid()
970 + ", pid " + Binder.getCallingPid());
971 }
Fred Quintana382601f2010-03-25 12:25:10 -0700972 if (accountType == null) throw new IllegalArgumentException("accountType is null");
973 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800974 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800975 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700976 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700977 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800978 synchronized (accounts.cacheLock) {
979 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800980 db.beginTransaction();
981 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800982 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800983 db.setTransactionSuccessful();
984 } finally {
985 db.endTransaction();
986 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700987 }
Fred Quintana60307342009-03-24 22:48:12 -0700988 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700989 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700990 }
991 }
992
Amith Yamasani04e0d262012-02-14 11:50:53 -0800993 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
994 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700995 if (authToken == null || accountType == null) {
996 return;
997 }
Fred Quintana33269202009-04-20 16:05:10 -0700998 Cursor cursor = db.rawQuery(
999 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1000 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1001 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1002 + " FROM " + TABLE_ACCOUNTS
1003 + " JOIN " + TABLE_AUTHTOKENS
1004 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1005 + " = " + AUTHTOKENS_ACCOUNTS_ID
1006 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1007 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1008 new String[]{authToken, accountType});
1009 try {
1010 while (cursor.moveToNext()) {
1011 long authTokenId = cursor.getLong(0);
1012 String accountName = cursor.getString(1);
1013 String authTokenType = cursor.getString(2);
1014 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001015 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001016 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -07001017 }
Fred Quintana33269202009-04-20 16:05:10 -07001018 } finally {
1019 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001020 }
1021 }
1022
Amith Yamasani04e0d262012-02-14 11:50:53 -08001023 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1024 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001025 if (account == null || type == null) {
1026 return false;
1027 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001028 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1029 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001030 synchronized (accounts.cacheLock) {
1031 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001032 db.beginTransaction();
1033 try {
1034 long accountId = getAccountIdLocked(db, account);
1035 if (accountId < 0) {
1036 return false;
1037 }
1038 db.delete(TABLE_AUTHTOKENS,
1039 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1040 new String[]{type});
1041 ContentValues values = new ContentValues();
1042 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1043 values.put(AUTHTOKENS_TYPE, type);
1044 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1045 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1046 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001047 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001048 return true;
1049 }
Fred Quintana33269202009-04-20 16:05:10 -07001050 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001051 } finally {
1052 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001053 }
Fred Quintana60307342009-03-24 22:48:12 -07001054 }
1055 }
1056
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001057 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001058 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001059 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1060 Log.v(TAG, "peekAuthToken: " + account
1061 + ", authTokenType " + authTokenType
1062 + ", caller's uid " + Binder.getCallingUid()
1063 + ", pid " + Binder.getCallingPid());
1064 }
Fred Quintana382601f2010-03-25 12:25:10 -07001065 if (account == null) throw new IllegalArgumentException("account is null");
1066 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001067 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001068 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001069 long identityToken = clearCallingIdentity();
1070 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001071 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001072 } finally {
1073 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001074 }
Fred Quintana60307342009-03-24 22:48:12 -07001075 }
1076
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001077 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001078 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001079 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1080 Log.v(TAG, "setAuthToken: " + account
1081 + ", authTokenType " + authTokenType
1082 + ", caller's uid " + Binder.getCallingUid()
1083 + ", pid " + Binder.getCallingPid());
1084 }
Fred Quintana382601f2010-03-25 12:25:10 -07001085 if (account == null) throw new IllegalArgumentException("account is null");
1086 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001087 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001088 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001089 long identityToken = clearCallingIdentity();
1090 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001091 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001092 } finally {
1093 restoreCallingIdentity(identityToken);
1094 }
Fred Quintana60307342009-03-24 22:48:12 -07001095 }
1096
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001097 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001098 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001099 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1100 Log.v(TAG, "setAuthToken: " + account
1101 + ", caller's uid " + Binder.getCallingUid()
1102 + ", pid " + Binder.getCallingPid());
1103 }
Fred Quintana382601f2010-03-25 12:25:10 -07001104 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001105 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001106 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001107 long identityToken = clearCallingIdentity();
1108 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001109 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001110 } finally {
1111 restoreCallingIdentity(identityToken);
1112 }
Fred Quintana60307342009-03-24 22:48:12 -07001113 }
1114
Amith Yamasani04e0d262012-02-14 11:50:53 -08001115 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001116 if (account == null) {
1117 return;
1118 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001119 synchronized (accounts.cacheLock) {
1120 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001121 db.beginTransaction();
1122 try {
1123 final ContentValues values = new ContentValues();
1124 values.put(ACCOUNTS_PASSWORD, password);
1125 final long accountId = getAccountIdLocked(db, account);
1126 if (accountId >= 0) {
1127 final String[] argsAccountId = {String.valueOf(accountId)};
1128 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1129 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001130 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001131 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001132 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001133 } finally {
1134 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001135 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001136 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001137 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001138 }
1139
Amith Yamasani04e0d262012-02-14 11:50:53 -08001140 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001141 Log.i(TAG, "the accounts changed, sending broadcast of "
1142 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001143 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001144 }
1145
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001146 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001147 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001148 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1149 Log.v(TAG, "clearPassword: " + account
1150 + ", caller's uid " + Binder.getCallingUid()
1151 + ", pid " + Binder.getCallingPid());
1152 }
Fred Quintana382601f2010-03-25 12:25:10 -07001153 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001154 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001155 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001156 long identityToken = clearCallingIdentity();
1157 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001158 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001159 } finally {
1160 restoreCallingIdentity(identityToken);
1161 }
Fred Quintana60307342009-03-24 22:48:12 -07001162 }
1163
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001164 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001165 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001166 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1167 Log.v(TAG, "setUserData: " + account
1168 + ", key " + key
1169 + ", caller's uid " + Binder.getCallingUid()
1170 + ", pid " + Binder.getCallingPid());
1171 }
Fred Quintana382601f2010-03-25 12:25:10 -07001172 if (key == null) throw new IllegalArgumentException("key is null");
1173 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001174 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001175 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001176 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001177 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001178 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001179 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001180 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001181 }
1182 }
1183
Amith Yamasani04e0d262012-02-14 11:50:53 -08001184 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1185 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001186 if (account == null || key == null) {
1187 return;
1188 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001189 synchronized (accounts.cacheLock) {
1190 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001191 db.beginTransaction();
1192 try {
1193 long accountId = getAccountIdLocked(db, account);
1194 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001195 return;
1196 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001197 long extrasId = getExtrasIdLocked(db, accountId, key);
1198 if (extrasId < 0 ) {
1199 extrasId = insertExtraLocked(db, accountId, key, value);
1200 if (extrasId < 0) {
1201 return;
1202 }
1203 } else {
1204 ContentValues values = new ContentValues();
1205 values.put(EXTRAS_VALUE, value);
1206 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1207 return;
1208 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001209
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001210 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001211 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001212 db.setTransactionSuccessful();
1213 } finally {
1214 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001215 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001216 }
1217 }
1218
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001219 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001220 if (result == null) {
1221 Log.e(TAG, "the result is unexpectedly null", new Exception());
1222 }
1223 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1224 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1225 + response);
1226 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001227 try {
1228 response.onResult(result);
1229 } catch (RemoteException e) {
1230 // if the caller is dead then there is no one to care about remote
1231 // exceptions
1232 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1233 Log.v(TAG, "failure while notifying response", e);
1234 }
1235 }
1236 }
1237
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001238 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001239 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1240 final String authTokenType)
1241 throws RemoteException {
1242 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001243 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1244
Fred Quintanad9640ec2012-05-23 12:37:00 -07001245 final int callingUid = getCallingUid();
1246 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001247 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001248 throw new SecurityException("can only call from system");
1249 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001250 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001251 long identityToken = clearCallingIdentity();
1252 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001253 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001254 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001255 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001256 protected String toDebugString(long now) {
1257 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001258 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001259 + ", authTokenType " + authTokenType;
1260 }
1261
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001262 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001263 public void run() throws RemoteException {
1264 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1265 }
1266
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001267 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001268 public void onResult(Bundle result) {
1269 if (result != null) {
1270 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1271 Bundle bundle = new Bundle();
1272 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1273 super.onResult(bundle);
1274 return;
1275 } else {
1276 super.onResult(result);
1277 }
1278 }
1279 }.bind();
1280 } finally {
1281 restoreCallingIdentity(identityToken);
1282 }
1283 }
1284
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001285 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001286 public void getAuthToken(IAccountManagerResponse response, final Account account,
1287 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001288 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001289 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1290 Log.v(TAG, "getAuthToken: " + account
1291 + ", response " + response
1292 + ", authTokenType " + authTokenType
1293 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1294 + ", expectActivityLaunch " + expectActivityLaunch
1295 + ", caller's uid " + Binder.getCallingUid()
1296 + ", pid " + Binder.getCallingPid());
1297 }
Fred Quintana382601f2010-03-25 12:25:10 -07001298 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001299 try {
1300 if (account == null) {
1301 Slog.w(TAG, "getAuthToken called with null account");
1302 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1303 return;
1304 }
1305 if (authTokenType == null) {
1306 Slog.w(TAG, "getAuthToken called with null authTokenType");
1307 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1308 return;
1309 }
1310 } catch (RemoteException e) {
1311 Slog.w(TAG, "Failed to report error back to the client." + e);
1312 return;
1313 }
1314
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001315 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001316 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001317 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1318 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1319 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001320 final boolean customTokens =
1321 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1322
1323 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001324 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001325 final boolean permissionGranted = customTokens ||
1326 permissionIsGranted(account, authTokenType, callerUid);
1327
Costin Manolachec6684f92011-01-14 11:25:39 -08001328 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1329 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001330 // let authenticator know the identity of the caller
1331 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1332 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1333 if (notifyOnAuthFailure) {
1334 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001335 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001336
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001337 long identityToken = clearCallingIdentity();
1338 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001339 // if the caller has permission, do the peek. otherwise go the more expensive
1340 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001341 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001342 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001343 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001344 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001345 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1346 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1347 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001348 onResult(response, result);
1349 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001350 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001351 }
1352
Amith Yamasani04e0d262012-02-14 11:50:53 -08001353 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001354 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001355 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001356 protected String toDebugString(long now) {
1357 if (loginOptions != null) loginOptions.keySet();
1358 return super.toDebugString(now) + ", getAuthToken"
1359 + ", " + account
1360 + ", authTokenType " + authTokenType
1361 + ", loginOptions " + loginOptions
1362 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1363 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001364
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001365 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001366 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001367 // If the caller doesn't have permission then create and return the
1368 // "grant permission" intent instead of the "getAuthToken" intent.
1369 if (!permissionGranted) {
1370 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1371 } else {
1372 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1373 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001374 }
1375
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001376 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001377 public void onResult(Bundle result) {
1378 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001379 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001380 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1381 new AccountAuthenticatorResponse(this),
1382 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001383 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001384 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001385 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001386 onResult(bundle);
1387 return;
1388 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001389 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001390 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001391 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1392 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001393 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001394 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001395 "the type and name should not be empty");
1396 return;
1397 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001398 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001399 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001400 authTokenType, authToken);
1401 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001402 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001403
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001404 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001405 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001406 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001407 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001408 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001409 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001410 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001411 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001412 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001413 }.bind();
1414 } finally {
1415 restoreCallingIdentity(identityToken);
1416 }
Fred Quintana60307342009-03-24 22:48:12 -07001417 }
1418
Dianne Hackborn41203752012-08-31 14:05:51 -07001419 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1420 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001421 int uid = intent.getIntExtra(
1422 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1423 String authTokenType = intent.getStringExtra(
1424 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1425 String authTokenLabel = intent.getStringExtra(
1426 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1427
1428 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1429 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001430 final String titleAndSubtitle =
1431 mContext.getString(R.string.permission_request_notification_with_subtitle,
1432 account.name);
1433 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001434 String title = titleAndSubtitle;
1435 String subtitle = "";
1436 if (index > 0) {
1437 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001438 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001439 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001440 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001441 n.setLatestEventInfo(mContext, title, subtitle,
1442 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001443 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1444 installNotification(getCredentialPermissionNotificationId(
1445 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001446 }
1447
Costin Manolache5f383ad92010-12-02 16:44:46 -08001448 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1449 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001450
1451 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001452 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001453 // Since it was set in Eclair+ we can't change it without breaking apps using
1454 // the intent from a non-Activity context.
1455 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001456 intent.addCategory(
1457 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001458
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001459 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001460 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1461 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001462 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001463
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001464 return intent;
1465 }
1466
1467 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1468 int uid) {
1469 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001470 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001471 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001472 final Pair<Pair<Account, String>, Integer> key =
1473 new Pair<Pair<Account, String>, Integer>(
1474 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001475 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001476 if (id == null) {
1477 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001478 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001479 }
1480 }
1481 return id;
1482 }
1483
Amith Yamasani04e0d262012-02-14 11:50:53 -08001484 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001485 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001486 synchronized (accounts.signinRequiredNotificationIds) {
1487 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001488 if (id == null) {
1489 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001490 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001491 }
1492 }
1493 return id;
1494 }
1495
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001496 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001497 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001498 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001499 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001500 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1501 Log.v(TAG, "addAccount: accountType " + accountType
1502 + ", response " + response
1503 + ", authTokenType " + authTokenType
1504 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1505 + ", expectActivityLaunch " + expectActivityLaunch
1506 + ", caller's uid " + Binder.getCallingUid()
1507 + ", pid " + Binder.getCallingPid());
1508 }
Fred Quintana382601f2010-03-25 12:25:10 -07001509 if (response == null) throw new IllegalArgumentException("response is null");
1510 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001511 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001512
Amith Yamasani71e6c692013-03-24 17:39:28 -07001513 // Is user disallowed from modifying accounts?
Amith Yamasani27db4682013-03-30 17:07:47 -07001514 if (!canUserModifyAccounts(Binder.getCallingUid())) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001515 try {
1516 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1517 "User is not allowed to add an account!");
1518 } catch (RemoteException re) {
1519 }
Amith Yamasani23c8b962013-04-10 13:37:18 -07001520 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1521 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1522 long identityToken = clearCallingIdentity();
1523 try {
1524 mContext.startActivityAsUser(cantAddAccount, UserHandle.CURRENT);
1525 } finally {
1526 restoreCallingIdentity(identityToken);
1527 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001528 return;
1529 }
1530
Amith Yamasani04e0d262012-02-14 11:50:53 -08001531 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001532 final int pid = Binder.getCallingPid();
1533 final int uid = Binder.getCallingUid();
1534 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1535 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1536 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1537
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001538 long identityToken = clearCallingIdentity();
1539 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001540 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001541 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001542 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001543 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001544 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001545 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001546 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001547
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001548 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001549 protected String toDebugString(long now) {
1550 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001551 + ", accountType " + accountType
1552 + ", requiredFeatures "
1553 + (requiredFeatures != null
1554 ? TextUtils.join(",", requiredFeatures)
1555 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001556 }
1557 }.bind();
1558 } finally {
1559 restoreCallingIdentity(identityToken);
1560 }
Fred Quintana60307342009-03-24 22:48:12 -07001561 }
1562
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001563 @Override
1564 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1565 final Account account, final Bundle options, final boolean expectActivityLaunch,
1566 int userId) {
1567 // Only allow the system process to read accounts of other users
1568 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001569 && Binder.getCallingUid() != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001570 && mContext.checkCallingOrSelfPermission(
1571 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1572 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001573 throw new SecurityException("User " + UserHandle.getCallingUserId()
1574 + " trying to confirm account credentials for " + userId);
1575 }
1576
Fred Quintana56285a62010-12-02 14:20:51 -08001577 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1578 Log.v(TAG, "confirmCredentials: " + account
1579 + ", response " + response
1580 + ", expectActivityLaunch " + expectActivityLaunch
1581 + ", caller's uid " + Binder.getCallingUid()
1582 + ", pid " + Binder.getCallingPid());
1583 }
Fred Quintana382601f2010-03-25 12:25:10 -07001584 if (response == null) throw new IllegalArgumentException("response is null");
1585 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001586 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001587 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001588 long identityToken = clearCallingIdentity();
1589 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001590 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001591 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001592 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001593 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001594 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001595 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001596 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001597 protected String toDebugString(long now) {
1598 return super.toDebugString(now) + ", confirmCredentials"
1599 + ", " + account;
1600 }
1601 }.bind();
1602 } finally {
1603 restoreCallingIdentity(identityToken);
1604 }
Fred Quintana60307342009-03-24 22:48:12 -07001605 }
1606
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001607 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001608 public void updateCredentials(IAccountManagerResponse response, final Account account,
1609 final String authTokenType, final boolean expectActivityLaunch,
1610 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001611 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1612 Log.v(TAG, "updateCredentials: " + account
1613 + ", response " + response
1614 + ", authTokenType " + authTokenType
1615 + ", expectActivityLaunch " + expectActivityLaunch
1616 + ", caller's uid " + Binder.getCallingUid()
1617 + ", pid " + Binder.getCallingPid());
1618 }
Fred Quintana382601f2010-03-25 12:25:10 -07001619 if (response == null) throw new IllegalArgumentException("response is null");
1620 if (account == null) throw new IllegalArgumentException("account is null");
1621 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001622 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001623 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001624 long identityToken = clearCallingIdentity();
1625 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001626 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001627 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001628 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001629 public void run() throws RemoteException {
1630 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1631 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001632 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001633 protected String toDebugString(long now) {
1634 if (loginOptions != null) loginOptions.keySet();
1635 return super.toDebugString(now) + ", updateCredentials"
1636 + ", " + account
1637 + ", authTokenType " + authTokenType
1638 + ", loginOptions " + loginOptions;
1639 }
1640 }.bind();
1641 } finally {
1642 restoreCallingIdentity(identityToken);
1643 }
Fred Quintana60307342009-03-24 22:48:12 -07001644 }
1645
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001646 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001647 public void editProperties(IAccountManagerResponse response, final String accountType,
1648 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001649 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1650 Log.v(TAG, "editProperties: accountType " + accountType
1651 + ", response " + response
1652 + ", expectActivityLaunch " + expectActivityLaunch
1653 + ", caller's uid " + Binder.getCallingUid()
1654 + ", pid " + Binder.getCallingPid());
1655 }
Fred Quintana382601f2010-03-25 12:25:10 -07001656 if (response == null) throw new IllegalArgumentException("response is null");
1657 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001658 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001659 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001660 long identityToken = clearCallingIdentity();
1661 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001662 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001663 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001664 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001665 public void run() throws RemoteException {
1666 mAuthenticator.editProperties(this, mAccountType);
1667 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001668 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001669 protected String toDebugString(long now) {
1670 return super.toDebugString(now) + ", editProperties"
1671 + ", accountType " + accountType;
1672 }
1673 }.bind();
1674 } finally {
1675 restoreCallingIdentity(identityToken);
1676 }
Fred Quintana60307342009-03-24 22:48:12 -07001677 }
1678
Fred Quintana33269202009-04-20 16:05:10 -07001679 private class GetAccountsByTypeAndFeatureSession extends Session {
1680 private final String[] mFeatures;
1681 private volatile Account[] mAccountsOfType = null;
1682 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1683 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001684 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001685
Amith Yamasani04e0d262012-02-14 11:50:53 -08001686 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001687 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001688 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001689 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001690 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001691 mFeatures = features;
1692 }
1693
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001694 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001695 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001696 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001697 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1698 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001699 }
Fred Quintana33269202009-04-20 16:05:10 -07001700 // check whether each account matches the requested features
1701 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1702 mCurrentAccount = 0;
1703
1704 checkAccount();
1705 }
1706
1707 public void checkAccount() {
1708 if (mCurrentAccount >= mAccountsOfType.length) {
1709 sendResult();
1710 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001711 }
Fred Quintana33269202009-04-20 16:05:10 -07001712
Fred Quintana29e94b82010-03-10 12:11:51 -08001713 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1714 if (accountAuthenticator == null) {
1715 // It is possible that the authenticator has died, which is indicated by
1716 // mAuthenticator being set to null. If this happens then just abort.
1717 // There is no need to send back a result or error in this case since
1718 // that already happened when mAuthenticator was cleared.
1719 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1720 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1721 + " connected to the authenticator, " + toDebugString());
1722 }
1723 return;
1724 }
Fred Quintana33269202009-04-20 16:05:10 -07001725 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001726 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001727 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001728 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001729 }
1730 }
1731
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001732 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001733 public void onResult(Bundle result) {
1734 mNumResults++;
1735 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001736 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001737 return;
1738 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001739 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001740 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1741 }
1742 mCurrentAccount++;
1743 checkAccount();
1744 }
1745
1746 public void sendResult() {
1747 IAccountManagerResponse response = getResponseAndClose();
1748 if (response != null) {
1749 try {
1750 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1751 for (int i = 0; i < accounts.length; i++) {
1752 accounts[i] = mAccountsWithFeatures.get(i);
1753 }
Fred Quintana56285a62010-12-02 14:20:51 -08001754 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1755 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1756 + response);
1757 }
Fred Quintana33269202009-04-20 16:05:10 -07001758 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001759 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001760 response.onResult(result);
1761 } catch (RemoteException e) {
1762 // if the caller is dead then there is no one to care about remote exceptions
1763 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1764 Log.v(TAG, "failure while notifying response", e);
1765 }
1766 }
1767 }
1768 }
1769
1770
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001771 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001772 protected String toDebugString(long now) {
1773 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1774 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1775 }
1776 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001777
Amith Yamasani04e0d262012-02-14 11:50:53 -08001778 /**
1779 * Returns the accounts for a specific user
1780 * @hide
1781 */
1782 public Account[] getAccounts(int userId) {
1783 checkReadAccountsPermission();
1784 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001785 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001786 long identityToken = clearCallingIdentity();
1787 try {
1788 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001789 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001790 }
1791 } finally {
1792 restoreCallingIdentity(identityToken);
1793 }
1794 }
1795
Amith Yamasanif29f2362012-04-05 18:29:52 -07001796 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001797 * Returns accounts for all running users.
1798 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001799 * @hide
1800 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001801 public AccountAndUser[] getRunningAccounts() {
1802 final int[] runningUserIds;
1803 try {
1804 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1805 } catch (RemoteException e) {
1806 // Running in system_server; should never happen
1807 throw new RuntimeException(e);
1808 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001809 return getAccounts(runningUserIds);
1810 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001811
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001812 /** {@hide} */
1813 public AccountAndUser[] getAllAccounts() {
1814 final List<UserInfo> users = getUserManager().getUsers();
1815 final int[] userIds = new int[users.size()];
1816 for (int i = 0; i < userIds.length; i++) {
1817 userIds[i] = users.get(i).id;
1818 }
1819 return getAccounts(userIds);
1820 }
1821
1822 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001823 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07001824 for (int userId : userIds) {
1825 UserAccounts userAccounts = getUserAccounts(userId);
1826 if (userAccounts == null) continue;
1827 synchronized (userAccounts.cacheLock) {
1828 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
1829 Binder.getCallingUid(), null);
1830 for (int a = 0; a < accounts.length; a++) {
1831 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001832 }
1833 }
1834 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001835
1836 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1837 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001838 }
1839
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001840 @Override
1841 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001842 return getAccountsAsUser(type, userId, null, -1);
1843 }
1844
1845 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
1846 int packageUid) {
1847 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001848 // Only allow the system process to read accounts of other users
1849 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001850 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001851 && mContext.checkCallingOrSelfPermission(
1852 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1853 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001854 throw new SecurityException("User " + UserHandle.getCallingUserId()
1855 + " trying to get account for " + userId);
1856 }
1857
Fred Quintana56285a62010-12-02 14:20:51 -08001858 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1859 Log.v(TAG, "getAccounts: accountType " + type
1860 + ", caller's uid " + Binder.getCallingUid()
1861 + ", pid " + Binder.getCallingPid());
1862 }
Amith Yamasani27db4682013-03-30 17:07:47 -07001863 // If the original calling app was using the framework account chooser activity, we'll
1864 // be passed in the original caller's uid here, which is what should be used for filtering.
1865 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
1866 callingUid = packageUid;
1867 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001868 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001869 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001870 long identityToken = clearCallingIdentity();
1871 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001872 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001873 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001874 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001875 } finally {
1876 restoreCallingIdentity(identityToken);
1877 }
1878 }
1879
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001880 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001881 public boolean addSharedAccountAsUser(Account account, int userId) {
1882 userId = handleIncomingUser(userId);
1883 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1884 ContentValues values = new ContentValues();
1885 values.put(ACCOUNTS_NAME, account.name);
1886 values.put(ACCOUNTS_TYPE, account.type);
1887 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1888 new String[] {account.name, account.type});
1889 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1890 if (accountId < 0) {
1891 Log.w(TAG, "insertAccountIntoDatabase: " + account
1892 + ", skipping the DB insert failed");
1893 return false;
1894 }
1895 return true;
1896 }
1897
1898 @Override
1899 public boolean removeSharedAccountAsUser(Account account, int userId) {
1900 userId = handleIncomingUser(userId);
1901 UserAccounts accounts = getUserAccounts(userId);
1902 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1903 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1904 new String[] {account.name, account.type});
1905 if (r > 0) {
1906 removeAccountInternal(accounts, account);
1907 }
1908 return r > 0;
1909 }
1910
1911 @Override
1912 public Account[] getSharedAccountsAsUser(int userId) {
1913 userId = handleIncomingUser(userId);
1914 UserAccounts accounts = getUserAccounts(userId);
1915 ArrayList<Account> accountList = new ArrayList<Account>();
1916 Cursor cursor = null;
1917 try {
1918 cursor = accounts.openHelper.getReadableDatabase()
1919 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1920 null, null, null, null, null);
1921 if (cursor != null && cursor.moveToFirst()) {
1922 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1923 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1924 do {
1925 accountList.add(new Account(cursor.getString(nameIndex),
1926 cursor.getString(typeIndex)));
1927 } while (cursor.moveToNext());
1928 }
1929 } finally {
1930 if (cursor != null) {
1931 cursor.close();
1932 }
1933 }
1934 Account[] accountArray = new Account[accountList.size()];
1935 accountList.toArray(accountArray);
1936 return accountArray;
1937 }
1938
1939 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001940 public Account[] getAccounts(String type) {
1941 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1942 }
1943
Amith Yamasani27db4682013-03-30 17:07:47 -07001944 @Override
1945 public Account[] getAccountsForPackage(String packageName, int uid) {
1946 int callingUid = Binder.getCallingUid();
1947 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
1948 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
1949 + callingUid + " with uid=" + uid);
1950 }
1951 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
1952 }
1953
Amith Yamasani3b458ad2013-04-18 18:40:07 -07001954 @Override
1955 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
1956 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
1957 int packageUid = -1;
1958 try {
1959 packageUid = AppGlobals.getPackageManager().getPackageUid(
1960 packageName, UserHandle.getCallingUserId());
1961 } catch (RemoteException re) {
1962 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
1963 return new Account[0];
1964 }
1965 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
1966 }
1967
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001968 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001969 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001970 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001971 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1972 Log.v(TAG, "getAccounts: accountType " + type
1973 + ", response " + response
1974 + ", features " + stringArrayToString(features)
1975 + ", caller's uid " + Binder.getCallingUid()
1976 + ", pid " + Binder.getCallingPid());
1977 }
Fred Quintana382601f2010-03-25 12:25:10 -07001978 if (response == null) throw new IllegalArgumentException("response is null");
1979 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001980 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001981 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001982 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001983 long identityToken = clearCallingIdentity();
1984 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001985 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001986 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001987 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001988 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001989 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001990 Bundle result = new Bundle();
1991 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1992 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001993 return;
1994 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001995 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
1996 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001997 } finally {
1998 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001999 }
2000 }
2001
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002002 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002003 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002004 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002005 try {
2006 if (cursor.moveToNext()) {
2007 return cursor.getLong(0);
2008 }
2009 return -1;
2010 } finally {
2011 cursor.close();
2012 }
2013 }
2014
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002015 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002016 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2017 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2018 new String[]{key}, null, null, null);
2019 try {
2020 if (cursor.moveToNext()) {
2021 return cursor.getLong(0);
2022 }
2023 return -1;
2024 } finally {
2025 cursor.close();
2026 }
2027 }
2028
Fred Quintanaa698f422009-04-08 19:14:54 -07002029 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002030 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002031 IAccountManagerResponse mResponse;
2032 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002033 final boolean mExpectActivityLaunch;
2034 final long mCreationTime;
2035
Fred Quintana33269202009-04-20 16:05:10 -07002036 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002037 private int mNumRequestContinued = 0;
2038 private int mNumErrors = 0;
2039
Fred Quintana60307342009-03-24 22:48:12 -07002040 IAccountAuthenticator mAuthenticator = null;
2041
Fred Quintana8570f742010-02-18 10:32:54 -08002042 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002043 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002044
Amith Yamasani04e0d262012-02-14 11:50:53 -08002045 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08002046 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07002047 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002048 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002049 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002050 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002051 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002052 mResponse = response;
2053 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002054 mExpectActivityLaunch = expectActivityLaunch;
2055 mCreationTime = SystemClock.elapsedRealtime();
2056 synchronized (mSessions) {
2057 mSessions.put(toString(), this);
2058 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002059 if (response != null) {
2060 try {
2061 response.asBinder().linkToDeath(this, 0 /* flags */);
2062 } catch (RemoteException e) {
2063 mResponse = null;
2064 binderDied();
2065 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002066 }
Fred Quintana60307342009-03-24 22:48:12 -07002067 }
2068
Fred Quintanaa698f422009-04-08 19:14:54 -07002069 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002070 if (mResponse == null) {
2071 // this session has already been closed
2072 return null;
2073 }
Fred Quintana60307342009-03-24 22:48:12 -07002074 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002075 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002076 return response;
2077 }
2078
Fred Quintanaa698f422009-04-08 19:14:54 -07002079 private void close() {
2080 synchronized (mSessions) {
2081 if (mSessions.remove(toString()) == null) {
2082 // the session was already closed, so bail out now
2083 return;
2084 }
2085 }
2086 if (mResponse != null) {
2087 // stop listening for response deaths
2088 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2089
2090 // clear this so that we don't accidentally send any further results
2091 mResponse = null;
2092 }
2093 cancelTimeout();
2094 unbind();
2095 }
2096
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002097 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002098 public void binderDied() {
2099 mResponse = null;
2100 close();
2101 }
2102
2103 protected String toDebugString() {
2104 return toDebugString(SystemClock.elapsedRealtime());
2105 }
2106
2107 protected String toDebugString(long now) {
2108 return "Session: expectLaunch " + mExpectActivityLaunch
2109 + ", connected " + (mAuthenticator != null)
2110 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2111 + "/" + mNumErrors + ")"
2112 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2113 }
2114
Fred Quintana60307342009-03-24 22:48:12 -07002115 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002116 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2117 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2118 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002119 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002120 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002121 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002122 }
2123 }
2124
2125 private void unbind() {
2126 if (mAuthenticator != null) {
2127 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002128 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002129 }
2130 }
2131
2132 public void scheduleTimeout() {
2133 mMessageHandler.sendMessageDelayed(
2134 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2135 }
2136
2137 public void cancelTimeout() {
2138 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2139 }
2140
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002141 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002142 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002143 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002144 try {
2145 run();
2146 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002147 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002148 "remote exception");
2149 }
Fred Quintana60307342009-03-24 22:48:12 -07002150 }
2151
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002152 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002153 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002154 mAuthenticator = null;
2155 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002156 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002157 try {
2158 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2159 "disconnected");
2160 } catch (RemoteException e) {
2161 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2162 Log.v(TAG, "Session.onServiceDisconnected: "
2163 + "caught RemoteException while responding", e);
2164 }
2165 }
Fred Quintana60307342009-03-24 22:48:12 -07002166 }
2167 }
2168
Fred Quintanab839afc2009-10-14 15:57:28 -07002169 public abstract void run() throws RemoteException;
2170
Fred Quintana60307342009-03-24 22:48:12 -07002171 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002172 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002173 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002174 try {
2175 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2176 "timeout");
2177 } catch (RemoteException e) {
2178 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2179 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2180 e);
2181 }
2182 }
Fred Quintana60307342009-03-24 22:48:12 -07002183 }
2184 }
2185
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002186 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002187 public void onResult(Bundle result) {
2188 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002189 Intent intent = null;
2190 if (result != null
2191 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2192 /*
2193 * The Authenticator API allows third party authenticators to
2194 * supply arbitrary intents to other apps that they can run,
2195 * this can be very bad when those apps are in the system like
2196 * the System Settings.
2197 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002198 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07002199 long bid = Binder.clearCallingIdentity();
2200 try {
2201 PackageManager pm = mContext.getPackageManager();
2202 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2203 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2204 if (PackageManager.SIGNATURE_MATCH !=
2205 pm.checkSignatures(authenticatorUid, targetUid)) {
2206 throw new SecurityException(
2207 "Activity to be started with KEY_INTENT must " +
2208 "share Authenticator's signatures");
2209 }
2210 } finally {
2211 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002212 }
2213 }
2214 if (result != null
2215 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002216 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2217 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002218 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2219 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002220 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2221 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002222 }
Fred Quintana60307342009-03-24 22:48:12 -07002223 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002224 IAccountManagerResponse response;
2225 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002226 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002227 response = mResponse;
2228 } else {
2229 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002230 }
Fred Quintana60307342009-03-24 22:48:12 -07002231 if (response != null) {
2232 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002233 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002234 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2235 Log.v(TAG, getClass().getSimpleName()
2236 + " calling onError() on response " + response);
2237 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002238 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002239 "null bundle returned");
2240 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002241 if (mStripAuthTokenFromResult) {
2242 result.remove(AccountManager.KEY_AUTHTOKEN);
2243 }
Fred Quintana56285a62010-12-02 14:20:51 -08002244 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2245 Log.v(TAG, getClass().getSimpleName()
2246 + " calling onResult() on response " + response);
2247 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002248 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
2249 (intent == null)) {
2250 // All AccountManager error codes are greater than 0
2251 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
2252 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2253 } else {
2254 response.onResult(result);
2255 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002256 }
Fred Quintana60307342009-03-24 22:48:12 -07002257 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002258 // if the caller is dead then there is no one to care about remote exceptions
2259 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2260 Log.v(TAG, "failure while notifying response", e);
2261 }
Fred Quintana60307342009-03-24 22:48:12 -07002262 }
2263 }
2264 }
Fred Quintana60307342009-03-24 22:48:12 -07002265
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002266 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002267 public void onRequestContinued() {
2268 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002269 }
2270
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002271 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002272 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002273 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002274 IAccountManagerResponse response = getResponseAndClose();
2275 if (response != null) {
2276 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002277 Log.v(TAG, getClass().getSimpleName()
2278 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002279 }
2280 try {
2281 response.onError(errorCode, errorMessage);
2282 } catch (RemoteException e) {
2283 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2284 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2285 }
2286 }
2287 } else {
2288 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2289 Log.v(TAG, "Session.onError: already closed");
2290 }
Fred Quintana60307342009-03-24 22:48:12 -07002291 }
2292 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002293
2294 /**
2295 * find the component name for the authenticator and initiate a bind
2296 * if no authenticator or the bind fails then return false, otherwise return true
2297 */
2298 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002299 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2300 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2301 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002302 if (authenticatorInfo == null) {
2303 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2304 Log.v(TAG, "there is no authenticator for " + authenticatorType
2305 + ", bailing out");
2306 }
2307 return false;
2308 }
2309
2310 Intent intent = new Intent();
2311 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2312 intent.setComponent(authenticatorInfo.componentName);
2313 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2314 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2315 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002316 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2317 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002318 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2319 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2320 }
2321 return false;
2322 }
2323
2324
2325 return true;
2326 }
Fred Quintana60307342009-03-24 22:48:12 -07002327 }
2328
2329 private class MessageHandler extends Handler {
2330 MessageHandler(Looper looper) {
2331 super(looper);
2332 }
Costin Manolache3348f142009-09-29 18:58:36 -07002333
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002334 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002335 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002336 switch (msg.what) {
2337 case MESSAGE_TIMED_OUT:
2338 Session session = (Session)msg.obj;
2339 session.onTimedOut();
2340 break;
2341
Amith Yamasani5be347b2013-03-31 17:44:31 -07002342 case MESSAGE_COPY_SHARED_ACCOUNT:
2343 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2344 break;
2345
Fred Quintana60307342009-03-24 22:48:12 -07002346 default:
2347 throw new IllegalStateException("unhandled message: " + msg.what);
2348 }
2349 }
2350 }
2351
Amith Yamasani04e0d262012-02-14 11:50:53 -08002352 private static String getDatabaseName(int userId) {
2353 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002354 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002355 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002356 // Migrate old file, if it exists, to the new location.
2357 // Make sure the new file doesn't already exist. A dummy file could have been
2358 // accidentally created in the old location, causing the new one to become corrupted
2359 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002360 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002361 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002362 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002363 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002364 if (!userDir.exists()) {
2365 if (!userDir.mkdirs()) {
2366 throw new IllegalStateException("User dir cannot be created: " + userDir);
2367 }
2368 }
2369 if (!oldFile.renameTo(databaseFile)) {
2370 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2371 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002372 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002373 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002374 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002375 }
2376
Amith Yamasani04e0d262012-02-14 11:50:53 -08002377 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002378
Amith Yamasani04e0d262012-02-14 11:50:53 -08002379 public DatabaseHelper(Context context, int userId) {
2380 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002381 }
2382
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002383 /**
2384 * This call needs to be made while the mCacheLock is held. The way to
2385 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2386 * @param db The database.
2387 */
Fred Quintana60307342009-03-24 22:48:12 -07002388 @Override
2389 public void onCreate(SQLiteDatabase db) {
2390 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2391 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2392 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2393 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2394 + ACCOUNTS_PASSWORD + " TEXT, "
2395 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2396
2397 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2398 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2399 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2400 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2401 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2402 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2403
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002404 createGrantsTable(db);
2405
Fred Quintana60307342009-03-24 22:48:12 -07002406 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2407 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2408 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2409 + EXTRAS_KEY + " TEXT NOT NULL, "
2410 + EXTRAS_VALUE + " TEXT, "
2411 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2412
2413 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2414 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2415 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002416
Amith Yamasani67df64b2012-12-14 12:09:36 -08002417 createSharedAccountsTable(db);
2418
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002419 createAccountsDeletionTrigger(db);
2420 }
2421
Amith Yamasani67df64b2012-12-14 12:09:36 -08002422 private void createSharedAccountsTable(SQLiteDatabase db) {
2423 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2424 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2425 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2426 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2427 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2428 }
2429
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002430 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002431 db.execSQL(""
2432 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2433 + " BEGIN"
2434 + " DELETE FROM " + TABLE_AUTHTOKENS
2435 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2436 + " DELETE FROM " + TABLE_EXTRAS
2437 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002438 + " DELETE FROM " + TABLE_GRANTS
2439 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002440 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002441 }
2442
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002443 private void createGrantsTable(SQLiteDatabase db) {
2444 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2445 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2446 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2447 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2448 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2449 + "," + GRANTS_GRANTEE_UID + "))");
2450 }
2451
Fred Quintana60307342009-03-24 22:48:12 -07002452 @Override
2453 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002454 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002455
Fred Quintanaa698f422009-04-08 19:14:54 -07002456 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002457 // no longer need to do anything since the work is done
2458 // when upgrading from version 2
2459 oldVersion++;
2460 }
2461
2462 if (oldVersion == 2) {
2463 createGrantsTable(db);
2464 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2465 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002466 oldVersion++;
2467 }
Costin Manolache3348f142009-09-29 18:58:36 -07002468
2469 if (oldVersion == 3) {
2470 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2471 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2472 oldVersion++;
2473 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002474
2475 if (oldVersion == 4) {
2476 createSharedAccountsTable(db);
2477 oldVersion++;
2478 }
2479
2480 if (oldVersion != newVersion) {
2481 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2482 }
Fred Quintana60307342009-03-24 22:48:12 -07002483 }
2484
2485 @Override
2486 public void onOpen(SQLiteDatabase db) {
2487 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2488 }
2489 }
2490
Fred Quintana60307342009-03-24 22:48:12 -07002491 public IBinder onBind(Intent intent) {
2492 return asBinder();
2493 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002494
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002495 /**
2496 * Searches array of arguments for the specified string
2497 * @param args array of argument strings
2498 * @param value value to search for
2499 * @return true if the value is contained in the array
2500 */
2501 private static boolean scanArgs(String[] args, String value) {
2502 if (args != null) {
2503 for (String arg : args) {
2504 if (value.equals(arg)) {
2505 return true;
2506 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002507 }
2508 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002509 return false;
2510 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002511
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002512 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002513 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002514 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2515 != PackageManager.PERMISSION_GRANTED) {
2516 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2517 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2518 + " without permission " + android.Manifest.permission.DUMP);
2519 return;
2520 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002521 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002522 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002523
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002524 final List<UserInfo> users = getUserManager().getUsers();
2525 for (UserInfo user : users) {
2526 ipw.println("User " + user + ":");
2527 ipw.increaseIndent();
2528 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2529 ipw.println();
2530 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002531 }
2532 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002533
Amith Yamasani04e0d262012-02-14 11:50:53 -08002534 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2535 String[] args, boolean isCheckinRequest) {
2536 synchronized (userAccounts.cacheLock) {
2537 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002538
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002539 if (isCheckinRequest) {
2540 // This is a checkin request. *Only* upload the account types and the count of each.
2541 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2542 null, null, ACCOUNTS_TYPE, null, null);
2543 try {
2544 while (cursor.moveToNext()) {
2545 // print type,count
2546 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2547 }
2548 } finally {
2549 if (cursor != null) {
2550 cursor.close();
2551 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002552 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002553 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002554 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002555 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002556 fout.println("Accounts: " + accounts.length);
2557 for (Account account : accounts) {
2558 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002559 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002560
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002561 fout.println();
2562 synchronized (mSessions) {
2563 final long now = SystemClock.elapsedRealtime();
2564 fout.println("Active Sessions: " + mSessions.size());
2565 for (Session session : mSessions.values()) {
2566 fout.println(" " + session.toDebugString(now));
2567 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002568 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002569
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002570 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002571 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002572 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002573 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002574 }
2575
Amith Yamasani04e0d262012-02-14 11:50:53 -08002576 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002577 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002578 long identityToken = clearCallingIdentity();
2579 try {
2580 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2581 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2582 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002583
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002584 if (intent.getComponent() != null &&
2585 GrantCredentialsPermissionActivity.class.getName().equals(
2586 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002587 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002588 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002589 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002590 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002591 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2592 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002593 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002594 final String notificationTitleFormat =
2595 mContext.getText(R.string.notification_title).toString();
2596 n.setLatestEventInfo(mContext,
2597 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002598 message, PendingIntent.getActivityAsUser(
2599 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002600 null, user));
2601 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002602 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002603 } finally {
2604 restoreCallingIdentity(identityToken);
2605 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002606 }
2607
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002608 protected void installNotification(final int notificationId, final Notification n,
2609 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002610 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002611 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002612 }
2613
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002614 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002615 long identityToken = clearCallingIdentity();
2616 try {
2617 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002618 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002619 } finally {
2620 restoreCallingIdentity(identityToken);
2621 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002622 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002623
Fred Quintanab38eb142010-02-24 13:40:54 -08002624 /** Succeeds if any of the specified permissions are granted. */
2625 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002626 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002627
2628 for (String perm : permissions) {
2629 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2630 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002631 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002632 }
2633 return;
2634 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002635 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002636
2637 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002638 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002639 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002640 }
2641
Amith Yamasani67df64b2012-12-14 12:09:36 -08002642 private int handleIncomingUser(int userId) {
2643 try {
2644 return ActivityManagerNative.getDefault().handleIncomingUser(
2645 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2646 } catch (RemoteException re) {
2647 // Shouldn't happen, local.
2648 }
2649 return userId;
2650 }
2651
Christopher Tateccbf84f2013-05-08 15:25:41 -07002652 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002653 final int callingUserId = UserHandle.getUserId(callingUid);
2654
2655 final PackageManager userPackageManager;
2656 try {
2657 userPackageManager = mContext.createPackageContextAsUser(
2658 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2659 } catch (NameNotFoundException e) {
2660 return false;
2661 }
2662
2663 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002664 for (String name : packages) {
2665 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002666 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002667 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07002668 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002669 return true;
2670 }
2671 } catch (PackageManager.NameNotFoundException e) {
2672 return false;
2673 }
2674 }
2675 return false;
2676 }
2677
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002678 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07002679 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002680 final boolean fromAuthenticator = account != null
2681 && hasAuthenticatorUid(account.type, callerUid);
2682 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002683 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002684 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2685 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002686 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002687 + ": is authenticator? " + fromAuthenticator
2688 + ", has explicit permission? " + hasExplicitGrants);
2689 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07002690 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002691 }
2692
Fred Quintana1a231912009-10-15 11:31:30 -07002693 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002694 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002695 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002696 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002697 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002698 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002699 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002700 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002701 }
2702 }
2703 return false;
2704 }
2705
Amith Yamasani04e0d262012-02-14 11:50:53 -08002706 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2707 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002708 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002709 return true;
2710 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002711 UserAccounts accounts = getUserAccountsForCaller();
2712 synchronized (accounts.cacheLock) {
2713 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2714 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002715 account.name, account.type};
2716 final boolean permissionGranted =
2717 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2718 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2719 // TODO: Skip this check when running automated tests. Replace this
2720 // with a more general solution.
2721 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002722 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002723 + " but ignoring since device is in test harness.");
2724 return true;
2725 }
2726 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002727 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002728 }
2729
2730 private void checkCallingUidAgainstAuthenticator(Account account) {
2731 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002732 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002733 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2734 Log.w(TAG, msg);
2735 throw new SecurityException(msg);
2736 }
2737 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2738 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2739 }
2740 }
2741
2742 private void checkAuthenticateAccountsPermission(Account account) {
2743 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2744 checkCallingUidAgainstAuthenticator(account);
2745 }
2746
2747 private void checkReadAccountsPermission() {
2748 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2749 }
2750
2751 private void checkManageAccountsPermission() {
2752 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2753 }
2754
Fred Quintanab38eb142010-02-24 13:40:54 -08002755 private void checkManageAccountsOrUseCredentialsPermissions() {
2756 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2757 Manifest.permission.USE_CREDENTIALS);
2758 }
2759
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002760 private boolean canUserModifyAccounts(int callingUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002761 if (callingUid != Process.myUid()) {
2762 if (getUserManager().getUserRestrictions(
2763 new UserHandle(UserHandle.getUserId(callingUid)))
2764 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002765 return false;
2766 }
2767 }
2768 return true;
2769 }
2770
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002771 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002772 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2773 throws RemoteException {
2774 final int callingUid = getCallingUid();
2775
Amith Yamasani27db4682013-03-30 17:07:47 -07002776 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002777 throw new SecurityException();
2778 }
2779
2780 if (value) {
2781 grantAppPermission(account, authTokenType, uid);
2782 } else {
2783 revokeAppPermission(account, authTokenType, uid);
2784 }
2785 }
2786
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002787 /**
2788 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2789 * <p>
2790 * Although this is public it can only be accessed via the AccountManagerService object
2791 * which is in the system. This means we don't need to protect it with permissions.
2792 * @hide
2793 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002794 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002795 if (account == null || authTokenType == null) {
2796 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002797 return;
2798 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002799 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002800 synchronized (accounts.cacheLock) {
2801 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002802 db.beginTransaction();
2803 try {
2804 long accountId = getAccountIdLocked(db, account);
2805 if (accountId >= 0) {
2806 ContentValues values = new ContentValues();
2807 values.put(GRANTS_ACCOUNTS_ID, accountId);
2808 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2809 values.put(GRANTS_GRANTEE_UID, uid);
2810 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2811 db.setTransactionSuccessful();
2812 }
2813 } finally {
2814 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002815 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002816 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2817 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002818 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002819 }
2820
2821 /**
2822 * Don't allow callers with the given uid permission to get credentials for
2823 * account/authTokenType.
2824 * <p>
2825 * Although this is public it can only be accessed via the AccountManagerService object
2826 * which is in the system. This means we don't need to protect it with permissions.
2827 * @hide
2828 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002829 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002830 if (account == null || authTokenType == null) {
2831 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002832 return;
2833 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002834 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002835 synchronized (accounts.cacheLock) {
2836 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002837 db.beginTransaction();
2838 try {
2839 long accountId = getAccountIdLocked(db, account);
2840 if (accountId >= 0) {
2841 db.delete(TABLE_GRANTS,
2842 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2843 + GRANTS_GRANTEE_UID + "=?",
2844 new String[]{String.valueOf(accountId), authTokenType,
2845 String.valueOf(uid)});
2846 db.setTransactionSuccessful();
2847 }
2848 } finally {
2849 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002850 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002851 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2852 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002853 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002854 }
Fred Quintana56285a62010-12-02 14:20:51 -08002855
2856 static final private String stringArrayToString(String[] value) {
2857 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2858 }
2859
Amith Yamasani04e0d262012-02-14 11:50:53 -08002860 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2861 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002862 if (oldAccountsForType != null) {
2863 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2864 for (Account curAccount : oldAccountsForType) {
2865 if (!curAccount.equals(account)) {
2866 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002867 }
2868 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002869 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002870 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002871 } else {
2872 Account[] newAccountsForType = new Account[newAccountsList.size()];
2873 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002874 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002875 }
Fred Quintana56285a62010-12-02 14:20:51 -08002876 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002877 accounts.userDataCache.remove(account);
2878 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002879 }
2880
2881 /**
2882 * This assumes that the caller has already checked that the account is not already present.
2883 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002884 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2885 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002886 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2887 Account[] newAccountsForType = new Account[oldLength + 1];
2888 if (accountsForType != null) {
2889 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002890 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002891 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002892 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002893 }
2894
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002895 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07002896 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002897 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07002898 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002899 return unfiltered;
2900 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002901 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
2902 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002903 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002904 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002905 // otherwise return non-shared accounts only.
2906 // This might be a temporary way to specify a whitelist
2907 String whiteList = mContext.getResources().getString(
2908 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2909 for (String packageName : packages) {
2910 if (whiteList.contains(";" + packageName + ";")) {
2911 return unfiltered;
2912 }
2913 }
2914 ArrayList<Account> allowed = new ArrayList<Account>();
2915 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2916 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002917 String requiredAccountType = "";
2918 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07002919 // If there's an explicit callingPackage specified, check if that package
2920 // opted in to see restricted accounts.
2921 if (callingPackage != null) {
2922 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002923 if (pi != null && pi.restrictedAccountType != null) {
2924 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07002925 }
2926 } else {
2927 // Otherwise check if the callingUid has a package that has opted in
2928 for (String packageName : packages) {
2929 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
2930 if (pi != null && pi.restrictedAccountType != null) {
2931 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07002932 break;
2933 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002934 }
2935 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002936 } catch (NameNotFoundException nnfe) {
2937 }
2938 for (Account account : unfiltered) {
2939 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002940 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002941 } else {
2942 boolean found = false;
2943 for (Account shared : sharedAccounts) {
2944 if (shared.equals(account)) {
2945 found = true;
2946 break;
2947 }
2948 }
2949 if (!found) {
2950 allowed.add(account);
2951 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002952 }
2953 }
2954 Account[] filtered = new Account[allowed.size()];
2955 allowed.toArray(filtered);
2956 return filtered;
2957 } else {
2958 return unfiltered;
2959 }
2960 }
2961
Amith Yamasani27db4682013-03-30 17:07:47 -07002962 /*
2963 * packageName can be null. If not null, it should be used to filter out restricted accounts
2964 * that the package is not allowed to access.
2965 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002966 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07002967 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002968 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002969 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002970 if (accounts == null) {
2971 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002972 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002973 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07002974 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002975 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002976 } else {
2977 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002978 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002979 totalLength += accounts.length;
2980 }
2981 if (totalLength == 0) {
2982 return EMPTY_ACCOUNT_ARRAY;
2983 }
2984 Account[] accounts = new Account[totalLength];
2985 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002986 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002987 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2988 accountsOfType.length);
2989 totalLength += accountsOfType.length;
2990 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002991 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002992 }
2993 }
2994
Amith Yamasani04e0d262012-02-14 11:50:53 -08002995 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2996 Account account, String key, String value) {
2997 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002998 if (userDataForAccount == null) {
2999 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003000 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003001 }
3002 if (value == null) {
3003 userDataForAccount.remove(key);
3004 } else {
3005 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003006 }
3007 }
3008
Amith Yamasani04e0d262012-02-14 11:50:53 -08003009 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3010 Account account, String key, String value) {
3011 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003012 if (authTokensForAccount == null) {
3013 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003014 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003015 }
3016 if (value == null) {
3017 authTokensForAccount.remove(key);
3018 } else {
3019 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003020 }
3021 }
3022
Amith Yamasani04e0d262012-02-14 11:50:53 -08003023 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
3024 String authTokenType) {
3025 synchronized (accounts.cacheLock) {
3026 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003027 if (authTokensForAccount == null) {
3028 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003029 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003030 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003031 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003032 }
3033 return authTokensForAccount.get(authTokenType);
3034 }
3035 }
3036
Amith Yamasani04e0d262012-02-14 11:50:53 -08003037 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
3038 synchronized (accounts.cacheLock) {
3039 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003040 if (userDataForAccount == null) {
3041 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003042 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003043 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003044 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003045 }
3046 return userDataForAccount.get(key);
3047 }
3048 }
3049
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003050 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3051 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003052 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003053 Cursor cursor = db.query(TABLE_EXTRAS,
3054 COLUMNS_EXTRAS_KEY_AND_VALUE,
3055 SELECTION_USERDATA_BY_ACCOUNT,
3056 new String[]{account.name, account.type},
3057 null, null, null);
3058 try {
3059 while (cursor.moveToNext()) {
3060 final String tmpkey = cursor.getString(0);
3061 final String value = cursor.getString(1);
3062 userDataForAccount.put(tmpkey, value);
3063 }
3064 } finally {
3065 cursor.close();
3066 }
3067 return userDataForAccount;
3068 }
3069
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003070 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3071 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003072 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003073 Cursor cursor = db.query(TABLE_AUTHTOKENS,
3074 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3075 SELECTION_AUTHTOKENS_BY_ACCOUNT,
3076 new String[]{account.name, account.type},
3077 null, null, null);
3078 try {
3079 while (cursor.moveToNext()) {
3080 final String type = cursor.getString(0);
3081 final String authToken = cursor.getString(1);
3082 authTokensForAccount.put(type, authToken);
3083 }
3084 } finally {
3085 cursor.close();
3086 }
3087 return authTokensForAccount;
3088 }
Fred Quintana60307342009-03-24 22:48:12 -07003089}