blob: 26c6ccbe1c9f6c0c999bd43369cf9c54ff6b4305 [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;
Amith Yamasanie4cf7342012-12-17 11:12:09 -080024import android.accounts.AccountManagerResponse;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080025import android.accounts.AuthenticatorDescription;
26import 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;
Doug Zongker885cfc232009-10-21 16:52:44 -070033import android.app.Notification;
34import android.app.NotificationManager;
35import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070036import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070037import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070038import android.content.ContentValues;
39import android.content.Context;
40import android.content.Intent;
41import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070042import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070043import android.content.pm.ApplicationInfo;
44import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070045import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070046import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070047import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070048import android.content.pm.RegisteredServicesCacheListener;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070049import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070050import android.database.Cursor;
51import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070052import android.database.sqlite.SQLiteDatabase;
53import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070054import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070055import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080056import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070057import android.os.Handler;
58import android.os.HandlerThread;
59import android.os.IBinder;
60import android.os.Looper;
61import android.os.Message;
62import android.os.RemoteException;
63import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070064import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070065import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import android.text.TextUtils;
67import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070068import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070069import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080070import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070071
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070072import com.android.internal.R;
Amith Yamasani04e0d262012-02-14 11:50:53 -080073import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070074import com.google.android.collect.Lists;
75import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070076
Oscar Montemayora8529f62009-11-18 10:14:20 -080077import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070078import java.io.FileDescriptor;
79import java.io.PrintWriter;
80import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080081import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070082import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070083import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070084import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080085import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070086import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080087import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070088import java.util.concurrent.atomic.AtomicInteger;
89import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070090
Fred Quintana60307342009-03-24 22:48:12 -070091/**
92 * A system service that provides account, password, and authtoken management for all
93 * accounts on the device. Some of these calls are implemented with the help of the corresponding
94 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
95 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070096 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -070097 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070098 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070099public class AccountManagerService
100 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800101 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700102 private static final String TAG = "AccountManagerService";
103
104 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
105 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -0700106 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700107
108 private final Context mContext;
109
Fred Quintana56285a62010-12-02 14:20:51 -0800110 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700111 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800112
Fred Quintana60307342009-03-24 22:48:12 -0700113 private HandlerThread mMessageThread;
114 private final MessageHandler mMessageHandler;
115
116 // Messages that can be sent on mHandler
117 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700118
Fred Quintana56285a62010-12-02 14:20:51 -0800119 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700120
121 private static final String TABLE_ACCOUNTS = "accounts";
122 private static final String ACCOUNTS_ID = "_id";
123 private static final String ACCOUNTS_NAME = "name";
124 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700125 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700126 private static final String ACCOUNTS_PASSWORD = "password";
127
128 private static final String TABLE_AUTHTOKENS = "authtokens";
129 private static final String AUTHTOKENS_ID = "_id";
130 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
131 private static final String AUTHTOKENS_TYPE = "type";
132 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
133
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700134 private static final String TABLE_GRANTS = "grants";
135 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
136 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
137 private static final String GRANTS_GRANTEE_UID = "uid";
138
Fred Quintana60307342009-03-24 22:48:12 -0700139 private static final String TABLE_EXTRAS = "extras";
140 private static final String EXTRAS_ID = "_id";
141 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
142 private static final String EXTRAS_KEY = "key";
143 private static final String EXTRAS_VALUE = "value";
144
145 private static final String TABLE_META = "meta";
146 private static final String META_KEY = "key";
147 private static final String META_VALUE = "value";
148
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700149 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
150 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700151 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700152
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700153 private static final String COUNT_OF_MATCHING_GRANTS = ""
154 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
155 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
156 + " AND " + GRANTS_GRANTEE_UID + "=?"
157 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
158 + " AND " + ACCOUNTS_NAME + "=?"
159 + " AND " + ACCOUNTS_TYPE + "=?";
160
Fred Quintana56285a62010-12-02 14:20:51 -0800161 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
162 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
163 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
164 AUTHTOKENS_AUTHTOKEN};
165
166 private static final String SELECTION_USERDATA_BY_ACCOUNT =
167 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
168 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
169
Fred Quintanaa698f422009-04-08 19:14:54 -0700170 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700171 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
172
Amith Yamasani04e0d262012-02-14 11:50:53 -0800173 static class UserAccounts {
174 private final int userId;
175 private final DatabaseHelper openHelper;
176 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
177 credentialsPermissionNotificationIds =
178 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
179 private final HashMap<Account, Integer> signinRequiredNotificationIds =
180 new HashMap<Account, Integer>();
181 private final Object cacheLock = new Object();
182 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700183 private final HashMap<String, Account[]> accountCache =
184 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800185 /** protected by the {@link #cacheLock} */
186 private HashMap<Account, HashMap<String, String>> userDataCache =
187 new HashMap<Account, HashMap<String, String>>();
188 /** protected by the {@link #cacheLock} */
189 private HashMap<Account, HashMap<String, String>> authTokenCache =
190 new HashMap<Account, HashMap<String, String>>();
191
192 UserAccounts(Context context, int userId) {
193 this.userId = userId;
194 synchronized (cacheLock) {
195 openHelper = new DatabaseHelper(context, userId);
196 }
197 }
198 }
199
200 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
201
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700202 private static AtomicReference<AccountManagerService> sThis =
203 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700204 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700205
206 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700207 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700208 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
209 }
210
Fred Quintana56285a62010-12-02 14:20:51 -0800211
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700212 /**
213 * This should only be called by system code. One should only call this after the service
214 * has started.
215 * @return a reference to the AccountManagerService instance
216 * @hide
217 */
218 public static AccountManagerService getSingleton() {
219 return sThis.get();
220 }
Fred Quintana60307342009-03-24 22:48:12 -0700221
Fred Quintana56285a62010-12-02 14:20:51 -0800222 public AccountManagerService(Context context) {
223 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700224 }
225
Fred Quintana56285a62010-12-02 14:20:51 -0800226 public AccountManagerService(Context context, PackageManager packageManager,
227 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700228 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800229 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700230
Fred Quintana60307342009-03-24 22:48:12 -0700231 mMessageThread = new HandlerThread("AccountManagerService");
232 mMessageThread.start();
233 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
234
Fred Quintana56285a62010-12-02 14:20:51 -0800235 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800236 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700237
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700238 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800239
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800240 IntentFilter intentFilter = new IntentFilter();
241 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
242 intentFilter.addDataScheme("package");
243 mContext.registerReceiver(new BroadcastReceiver() {
244 @Override
245 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800246 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800247 }
248 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800249
Amith Yamasani13593602012-03-22 16:16:17 -0700250 IntentFilter userFilter = new IntentFilter();
251 userFilter.addAction(Intent.ACTION_USER_REMOVED);
252 mContext.registerReceiver(new BroadcastReceiver() {
253 @Override
254 public void onReceive(Context context, Intent intent) {
255 onUserRemoved(intent);
256 }
257 }, userFilter);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800258 }
259
Kenny Root26ff6622012-07-30 12:58:03 -0700260 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700261 }
262
Amith Yamasani258848d2012-08-10 17:06:33 -0700263 private UserManager getUserManager() {
264 if (mUserManager == null) {
265 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
266 }
267 return mUserManager;
268 }
269
Amith Yamasani04e0d262012-02-14 11:50:53 -0800270 private UserAccounts initUser(int userId) {
271 synchronized (mUsers) {
272 UserAccounts accounts = mUsers.get(userId);
273 if (accounts == null) {
274 accounts = new UserAccounts(mContext, userId);
275 mUsers.append(userId, accounts);
276 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700277 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800278 }
279 return accounts;
280 }
281 }
282
283 private void purgeOldGrantsAll() {
284 synchronized (mUsers) {
285 for (int i = 0; i < mUsers.size(); i++) {
286 purgeOldGrants(mUsers.valueAt(i));
287 }
288 }
289 }
290
291 private void purgeOldGrants(UserAccounts accounts) {
292 synchronized (accounts.cacheLock) {
293 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800294 final Cursor cursor = db.query(TABLE_GRANTS,
295 new String[]{GRANTS_GRANTEE_UID},
296 null, null, GRANTS_GRANTEE_UID, null, null);
297 try {
298 while (cursor.moveToNext()) {
299 final int uid = cursor.getInt(0);
300 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
301 if (packageExists) {
302 continue;
303 }
304 Log.d(TAG, "deleting grants for UID " + uid
305 + " because its package is no longer installed");
306 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
307 new String[]{Integer.toString(uid)});
308 }
309 } finally {
310 cursor.close();
311 }
312 }
313 }
314
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700315 /**
316 * Validate internal set of accounts against installed authenticators for
317 * given user. Clears cached authenticators before validating.
318 */
319 public void validateAccounts(int userId) {
320 final UserAccounts accounts = getUserAccounts(userId);
321
322 // Invalidate user-specific cache to make sure we catch any
323 // removed authenticators.
324 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
325 }
326
327 /**
328 * Validate internal set of accounts against installed authenticators for
329 * given user. Clear cached authenticators before validating when requested.
330 */
331 private void validateAccountsInternal(
332 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
333 if (invalidateAuthenticatorCache) {
334 mAuthenticatorCache.invalidateCache(accounts.userId);
335 }
336
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700337 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
338 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
339 mAuthenticatorCache.getAllServices(accounts.userId)) {
340 knownAuth.add(service.type);
341 }
342
Amith Yamasani04e0d262012-02-14 11:50:53 -0800343 synchronized (accounts.cacheLock) {
344 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800345 boolean accountDeleted = false;
346 Cursor cursor = db.query(TABLE_ACCOUNTS,
347 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
348 null, null, null, null, null);
349 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800350 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800351 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700352 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800353 while (cursor.moveToNext()) {
354 final long accountId = cursor.getLong(0);
355 final String accountType = cursor.getString(1);
356 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700357
358 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700359 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800360 + accountType + " no longer has a registered authenticator");
361 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
362 accountDeleted = true;
363 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800364 accounts.userDataCache.remove(account);
365 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800366 } else {
367 ArrayList<String> accountNames = accountNamesByType.get(accountType);
368 if (accountNames == null) {
369 accountNames = new ArrayList<String>();
370 accountNamesByType.put(accountType, accountNames);
371 }
372 accountNames.add(accountName);
373 }
374 }
Andy McFadden2f362292012-01-20 14:43:38 -0800375 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800376 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800377 final String accountType = cur.getKey();
378 final ArrayList<String> accountNames = cur.getValue();
379 final Account[] accountsForType = new Account[accountNames.size()];
380 int i = 0;
381 for (String accountName : accountNames) {
382 accountsForType[i] = new Account(accountName, accountType);
383 ++i;
384 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800385 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800386 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800387 } finally {
388 cursor.close();
389 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800390 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800391 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800392 }
393 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700394 }
395
Amith Yamasani04e0d262012-02-14 11:50:53 -0800396 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700397 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800398 }
399
400 protected UserAccounts getUserAccounts(int userId) {
401 synchronized (mUsers) {
402 UserAccounts accounts = mUsers.get(userId);
403 if (accounts == null) {
404 accounts = initUser(userId);
405 mUsers.append(userId, accounts);
406 }
407 return accounts;
408 }
409 }
410
Amith Yamasani13593602012-03-22 16:16:17 -0700411 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700412 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700413 if (userId < 1) return;
414
415 UserAccounts accounts;
416 synchronized (mUsers) {
417 accounts = mUsers.get(userId);
418 mUsers.remove(userId);
419 }
420 if (accounts == null) {
421 File dbFile = new File(getDatabaseName(userId));
422 dbFile.delete();
423 return;
424 }
425
426 synchronized (accounts.cacheLock) {
427 accounts.openHelper.close();
428 File dbFile = new File(getDatabaseName(userId));
429 dbFile.delete();
430 }
431 }
432
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700433 @Override
434 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700435 Slog.d(TAG, "onServiceChanged() for userId " + userId);
436 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700437 }
438
Fred Quintanaa698f422009-04-08 19:14:54 -0700439 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800440 if (Log.isLoggable(TAG, Log.VERBOSE)) {
441 Log.v(TAG, "getPassword: " + account
442 + ", caller's uid " + Binder.getCallingUid()
443 + ", pid " + Binder.getCallingPid());
444 }
Fred Quintana382601f2010-03-25 12:25:10 -0700445 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700446 checkAuthenticateAccountsPermission(account);
447
Amith Yamasani04e0d262012-02-14 11:50:53 -0800448 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700449 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700450 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800451 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700452 } finally {
453 restoreCallingIdentity(identityToken);
454 }
455 }
456
Amith Yamasani04e0d262012-02-14 11:50:53 -0800457 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700458 if (account == null) {
459 return null;
460 }
461
Amith Yamasani04e0d262012-02-14 11:50:53 -0800462 synchronized (accounts.cacheLock) {
463 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800464 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
465 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
466 new String[]{account.name, account.type}, null, null, null);
467 try {
468 if (cursor.moveToNext()) {
469 return cursor.getString(0);
470 }
471 return null;
472 } finally {
473 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700474 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700475 }
476 }
477
478 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800479 if (Log.isLoggable(TAG, Log.VERBOSE)) {
480 Log.v(TAG, "getUserData: " + account
481 + ", key " + key
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");
486 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700487 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800488 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700489 long identityToken = clearCallingIdentity();
490 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800491 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700492 } finally {
493 restoreCallingIdentity(identityToken);
494 }
495 }
496
Fred Quintana97889762009-06-15 12:29:24 -0700497 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800498 if (Log.isLoggable(TAG, Log.VERBOSE)) {
499 Log.v(TAG, "getAuthenticatorTypes: "
500 + "caller's uid " + Binder.getCallingUid()
501 + ", pid " + Binder.getCallingPid());
502 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700503 final int userId = UserHandle.getCallingUserId();
504 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700505 try {
Fred Quintana97889762009-06-15 12:29:24 -0700506 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700507 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700508 AuthenticatorDescription[] types =
509 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700510 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700511 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700512 : authenticatorCollection) {
513 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700514 i++;
515 }
516 return types;
517 } finally {
518 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700519 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700520 }
521
Fred Quintanaa698f422009-04-08 19:14:54 -0700522 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800523 if (Log.isLoggable(TAG, Log.VERBOSE)) {
524 Log.v(TAG, "addAccount: " + account
525 + ", caller's uid " + Binder.getCallingUid()
526 + ", pid " + Binder.getCallingPid());
527 }
Fred Quintana382601f2010-03-25 12:25:10 -0700528 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700529 checkAuthenticateAccountsPermission(account);
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800530 if (!canUserModifyAccounts(Binder.getCallingUid())) {
531 return false;
532 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700533
Amith Yamasani04e0d262012-02-14 11:50:53 -0800534 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700535 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700536 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700537 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800538 return addAccountInternal(accounts, account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700539 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700540 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700541 }
542 }
543
Amith Yamasani04e0d262012-02-14 11:50:53 -0800544 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
545 Bundle extras) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700546 if (account == null) {
547 return false;
548 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800549 synchronized (accounts.cacheLock) {
550 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800551 db.beginTransaction();
552 try {
553 long numMatches = DatabaseUtils.longForQuery(db,
554 "select count(*) from " + TABLE_ACCOUNTS
555 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
556 new String[]{account.name, account.type});
557 if (numMatches > 0) {
558 Log.w(TAG, "insertAccountIntoDatabase: " + account
559 + ", skipping since the account already exists");
560 return false;
561 }
562 ContentValues values = new ContentValues();
563 values.put(ACCOUNTS_NAME, account.name);
564 values.put(ACCOUNTS_TYPE, account.type);
565 values.put(ACCOUNTS_PASSWORD, password);
566 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
567 if (accountId < 0) {
568 Log.w(TAG, "insertAccountIntoDatabase: " + account
569 + ", skipping the DB insert failed");
570 return false;
571 }
572 if (extras != null) {
573 for (String key : extras.keySet()) {
574 final String value = extras.getString(key);
575 if (insertExtraLocked(db, accountId, key, value) < 0) {
576 Log.w(TAG, "insertAccountIntoDatabase: " + account
577 + ", skipping since insertExtra failed for key " + key);
578 return false;
579 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700580 }
581 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800582 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800583 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800584 } finally {
585 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700586 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800587 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800588 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700589 }
590 }
591
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800592 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700593 ContentValues values = new ContentValues();
594 values.put(EXTRAS_KEY, key);
595 values.put(EXTRAS_ACCOUNTS_ID, accountId);
596 values.put(EXTRAS_VALUE, value);
597 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
598 }
599
Fred Quintana3084a6f2010-01-14 18:02:03 -0800600 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800601 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800602 if (Log.isLoggable(TAG, Log.VERBOSE)) {
603 Log.v(TAG, "hasFeatures: " + account
604 + ", response " + response
605 + ", features " + stringArrayToString(features)
606 + ", caller's uid " + Binder.getCallingUid()
607 + ", pid " + Binder.getCallingPid());
608 }
Fred Quintana382601f2010-03-25 12:25:10 -0700609 if (response == null) throw new IllegalArgumentException("response is null");
610 if (account == null) throw new IllegalArgumentException("account is null");
611 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800612 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800613 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800614 long identityToken = clearCallingIdentity();
615 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800616 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800617 } finally {
618 restoreCallingIdentity(identityToken);
619 }
620 }
621
622 private class TestFeaturesSession extends Session {
623 private final String[] mFeatures;
624 private final Account mAccount;
625
Amith Yamasani04e0d262012-02-14 11:50:53 -0800626 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800627 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800628 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800629 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800630 mFeatures = features;
631 mAccount = account;
632 }
633
634 public void run() throws RemoteException {
635 try {
636 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
637 } catch (RemoteException e) {
638 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
639 }
640 }
641
642 public void onResult(Bundle result) {
643 IAccountManagerResponse response = getResponseAndClose();
644 if (response != null) {
645 try {
646 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700647 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800648 return;
649 }
Fred Quintana56285a62010-12-02 14:20:51 -0800650 if (Log.isLoggable(TAG, Log.VERBOSE)) {
651 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
652 + response);
653 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800654 final Bundle newResult = new Bundle();
655 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
656 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
657 response.onResult(newResult);
658 } catch (RemoteException e) {
659 // if the caller is dead then there is no one to care about remote exceptions
660 if (Log.isLoggable(TAG, Log.VERBOSE)) {
661 Log.v(TAG, "failure while notifying response", e);
662 }
663 }
664 }
665 }
666
667 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800668 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800669 + ", " + mAccount
670 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
671 }
672 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800673
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700674 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800675 if (Log.isLoggable(TAG, Log.VERBOSE)) {
676 Log.v(TAG, "removeAccount: " + account
677 + ", response " + response
678 + ", caller's uid " + Binder.getCallingUid()
679 + ", pid " + Binder.getCallingPid());
680 }
Fred Quintana382601f2010-03-25 12:25:10 -0700681 if (response == null) throw new IllegalArgumentException("response is null");
682 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700683 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700684 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800685 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800686 if (!canUserModifyAccounts(Binder.getCallingUid())) {
687 try {
688 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
689 "User cannot modify accounts");
690 } catch (RemoteException re) {
691 }
692 }
693
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700694 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800695
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700696 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800697 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800698 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800699 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800700 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800701 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700702 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800703 }
704 }
705 }
706
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700707 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800708 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700709 } finally {
710 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700711 }
Fred Quintana60307342009-03-24 22:48:12 -0700712 }
713
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700714 private class RemoveAccountSession extends Session {
715 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800716 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
717 Account account) {
718 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800719 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700720 mAccount = account;
721 }
722
723 protected String toDebugString(long now) {
724 return super.toDebugString(now) + ", removeAccount"
725 + ", account " + mAccount;
726 }
727
728 public void run() throws RemoteException {
729 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
730 }
731
732 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700733 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
734 && !result.containsKey(AccountManager.KEY_INTENT)) {
735 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700736 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800737 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700738 }
739 IAccountManagerResponse response = getResponseAndClose();
740 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800741 if (Log.isLoggable(TAG, Log.VERBOSE)) {
742 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
743 + response);
744 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700745 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700746 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700747 try {
748 response.onResult(result2);
749 } catch (RemoteException e) {
750 // ignore
751 }
752 }
753 }
754 super.onResult(result);
755 }
756 }
757
Amith Yamasani04e0d262012-02-14 11:50:53 -0800758 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800759 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800760 removeAccountInternal(getUserAccountsForCaller(), account);
761 }
762
763 private void removeAccountInternal(UserAccounts accounts, Account account) {
764 synchronized (accounts.cacheLock) {
765 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800766 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
767 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800768 removeAccountFromCacheLocked(accounts, account);
769 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800770 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700771 }
772
Fred Quintanaa698f422009-04-08 19:14:54 -0700773 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800774 if (Log.isLoggable(TAG, Log.VERBOSE)) {
775 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
776 + ", caller's uid " + Binder.getCallingUid()
777 + ", pid " + Binder.getCallingPid());
778 }
Fred Quintana382601f2010-03-25 12:25:10 -0700779 if (accountType == null) throw new IllegalArgumentException("accountType is null");
780 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800781 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800782 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700783 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700784 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800785 synchronized (accounts.cacheLock) {
786 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800787 db.beginTransaction();
788 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800789 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800790 db.setTransactionSuccessful();
791 } finally {
792 db.endTransaction();
793 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700794 }
Fred Quintana60307342009-03-24 22:48:12 -0700795 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700796 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700797 }
798 }
799
Amith Yamasani04e0d262012-02-14 11:50:53 -0800800 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
801 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700802 if (authToken == null || accountType == null) {
803 return;
804 }
Fred Quintana33269202009-04-20 16:05:10 -0700805 Cursor cursor = db.rawQuery(
806 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
807 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
808 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
809 + " FROM " + TABLE_ACCOUNTS
810 + " JOIN " + TABLE_AUTHTOKENS
811 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
812 + " = " + AUTHTOKENS_ACCOUNTS_ID
813 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
814 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
815 new String[]{authToken, accountType});
816 try {
817 while (cursor.moveToNext()) {
818 long authTokenId = cursor.getLong(0);
819 String accountName = cursor.getString(1);
820 String authTokenType = cursor.getString(2);
821 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800822 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800823 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700824 }
Fred Quintana33269202009-04-20 16:05:10 -0700825 } finally {
826 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700827 }
828 }
829
Amith Yamasani04e0d262012-02-14 11:50:53 -0800830 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
831 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700832 if (account == null || type == null) {
833 return false;
834 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700835 cancelNotification(getSigninRequiredNotificationId(accounts, account),
836 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800837 synchronized (accounts.cacheLock) {
838 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800839 db.beginTransaction();
840 try {
841 long accountId = getAccountIdLocked(db, account);
842 if (accountId < 0) {
843 return false;
844 }
845 db.delete(TABLE_AUTHTOKENS,
846 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
847 new String[]{type});
848 ContentValues values = new ContentValues();
849 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
850 values.put(AUTHTOKENS_TYPE, type);
851 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
852 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
853 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800854 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800855 return true;
856 }
Fred Quintana33269202009-04-20 16:05:10 -0700857 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800858 } finally {
859 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -0700860 }
Fred Quintana60307342009-03-24 22:48:12 -0700861 }
862 }
863
Fred Quintanaa698f422009-04-08 19:14:54 -0700864 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800865 if (Log.isLoggable(TAG, Log.VERBOSE)) {
866 Log.v(TAG, "peekAuthToken: " + account
867 + ", authTokenType " + authTokenType
868 + ", caller's uid " + Binder.getCallingUid()
869 + ", pid " + Binder.getCallingPid());
870 }
Fred Quintana382601f2010-03-25 12:25:10 -0700871 if (account == null) throw new IllegalArgumentException("account is null");
872 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700873 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800874 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700875 long identityToken = clearCallingIdentity();
876 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800877 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700878 } finally {
879 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700880 }
Fred Quintana60307342009-03-24 22:48:12 -0700881 }
882
Fred Quintanaa698f422009-04-08 19:14:54 -0700883 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800884 if (Log.isLoggable(TAG, Log.VERBOSE)) {
885 Log.v(TAG, "setAuthToken: " + account
886 + ", authTokenType " + authTokenType
887 + ", caller's uid " + Binder.getCallingUid()
888 + ", pid " + Binder.getCallingPid());
889 }
Fred Quintana382601f2010-03-25 12:25:10 -0700890 if (account == null) throw new IllegalArgumentException("account is null");
891 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700892 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800893 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700894 long identityToken = clearCallingIdentity();
895 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800896 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700897 } finally {
898 restoreCallingIdentity(identityToken);
899 }
Fred Quintana60307342009-03-24 22:48:12 -0700900 }
901
Fred Quintanaa698f422009-04-08 19:14:54 -0700902 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -0800903 if (Log.isLoggable(TAG, Log.VERBOSE)) {
904 Log.v(TAG, "setAuthToken: " + account
905 + ", caller's uid " + Binder.getCallingUid()
906 + ", pid " + Binder.getCallingPid());
907 }
Fred Quintana382601f2010-03-25 12:25:10 -0700908 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700909 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800910 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700911 long identityToken = clearCallingIdentity();
912 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800913 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700914 } finally {
915 restoreCallingIdentity(identityToken);
916 }
Fred Quintana60307342009-03-24 22:48:12 -0700917 }
918
Amith Yamasani04e0d262012-02-14 11:50:53 -0800919 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700920 if (account == null) {
921 return;
922 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800923 synchronized (accounts.cacheLock) {
924 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800925 db.beginTransaction();
926 try {
927 final ContentValues values = new ContentValues();
928 values.put(ACCOUNTS_PASSWORD, password);
929 final long accountId = getAccountIdLocked(db, account);
930 if (accountId >= 0) {
931 final String[] argsAccountId = {String.valueOf(accountId)};
932 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
933 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800934 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800935 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -0800936 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800937 } finally {
938 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800939 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800940 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800941 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700942 }
943
Amith Yamasani04e0d262012-02-14 11:50:53 -0800944 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800945 Log.i(TAG, "the accounts changed, sending broadcast of "
946 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700947 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -0700948 }
949
Fred Quintanaa698f422009-04-08 19:14:54 -0700950 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800951 if (Log.isLoggable(TAG, Log.VERBOSE)) {
952 Log.v(TAG, "clearPassword: " + account
953 + ", caller's uid " + Binder.getCallingUid()
954 + ", pid " + Binder.getCallingPid());
955 }
Fred Quintana382601f2010-03-25 12:25:10 -0700956 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700957 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800958 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700959 long identityToken = clearCallingIdentity();
960 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800961 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700962 } finally {
963 restoreCallingIdentity(identityToken);
964 }
Fred Quintana60307342009-03-24 22:48:12 -0700965 }
966
Fred Quintanaa698f422009-04-08 19:14:54 -0700967 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -0800968 if (Log.isLoggable(TAG, Log.VERBOSE)) {
969 Log.v(TAG, "setUserData: " + account
970 + ", key " + key
971 + ", caller's uid " + Binder.getCallingUid()
972 + ", pid " + Binder.getCallingPid());
973 }
Fred Quintana382601f2010-03-25 12:25:10 -0700974 if (key == null) throw new IllegalArgumentException("key is null");
975 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700976 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800977 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700978 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700979 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800980 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700981 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700982 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700983 }
984 }
985
Amith Yamasani04e0d262012-02-14 11:50:53 -0800986 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
987 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700988 if (account == null || key == null) {
989 return;
990 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800991 synchronized (accounts.cacheLock) {
992 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800993 db.beginTransaction();
994 try {
995 long accountId = getAccountIdLocked(db, account);
996 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700997 return;
998 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800999 long extrasId = getExtrasIdLocked(db, accountId, key);
1000 if (extrasId < 0 ) {
1001 extrasId = insertExtraLocked(db, accountId, key, value);
1002 if (extrasId < 0) {
1003 return;
1004 }
1005 } else {
1006 ContentValues values = new ContentValues();
1007 values.put(EXTRAS_VALUE, value);
1008 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1009 return;
1010 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001011
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001012 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001013 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001014 db.setTransactionSuccessful();
1015 } finally {
1016 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001017 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001018 }
1019 }
1020
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001021 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001022 if (result == null) {
1023 Log.e(TAG, "the result is unexpectedly null", new Exception());
1024 }
1025 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1026 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1027 + response);
1028 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001029 try {
1030 response.onResult(result);
1031 } catch (RemoteException e) {
1032 // if the caller is dead then there is no one to care about remote
1033 // exceptions
1034 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1035 Log.v(TAG, "failure while notifying response", e);
1036 }
1037 }
1038 }
1039
Fred Quintanad9640ec2012-05-23 12:37:00 -07001040 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1041 final String authTokenType)
1042 throws RemoteException {
1043 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001044 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1045
Fred Quintanad9640ec2012-05-23 12:37:00 -07001046 final int callingUid = getCallingUid();
1047 clearCallingIdentity();
1048 if (callingUid != android.os.Process.SYSTEM_UID) {
1049 throw new SecurityException("can only call from system");
1050 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001051 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001052 long identityToken = clearCallingIdentity();
1053 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001054 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001055 false /* stripAuthTokenFromResult */) {
1056 protected String toDebugString(long now) {
1057 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001058 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001059 + ", authTokenType " + authTokenType;
1060 }
1061
1062 public void run() throws RemoteException {
1063 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1064 }
1065
1066 public void onResult(Bundle result) {
1067 if (result != null) {
1068 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1069 Bundle bundle = new Bundle();
1070 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1071 super.onResult(bundle);
1072 return;
1073 } else {
1074 super.onResult(result);
1075 }
1076 }
1077 }.bind();
1078 } finally {
1079 restoreCallingIdentity(identityToken);
1080 }
1081 }
1082
Fred Quintanaa698f422009-04-08 19:14:54 -07001083 public void getAuthToken(IAccountManagerResponse response, final Account account,
1084 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001085 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001086 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1087 Log.v(TAG, "getAuthToken: " + account
1088 + ", response " + response
1089 + ", authTokenType " + authTokenType
1090 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1091 + ", expectActivityLaunch " + expectActivityLaunch
1092 + ", caller's uid " + Binder.getCallingUid()
1093 + ", pid " + Binder.getCallingPid());
1094 }
Fred Quintana382601f2010-03-25 12:25:10 -07001095 if (response == null) throw new IllegalArgumentException("response is null");
1096 if (account == null) throw new IllegalArgumentException("account is null");
1097 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001098 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001099 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001100 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1101 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1102 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001103 final boolean customTokens =
1104 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1105
1106 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001107 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001108 final boolean permissionGranted = customTokens ||
1109 permissionIsGranted(account, authTokenType, callerUid);
1110
Costin Manolachec6684f92011-01-14 11:25:39 -08001111 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1112 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001113 // let authenticator know the identity of the caller
1114 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1115 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1116 if (notifyOnAuthFailure) {
1117 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001118 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001119
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001120 long identityToken = clearCallingIdentity();
1121 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001122 // if the caller has permission, do the peek. otherwise go the more expensive
1123 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001124 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001125 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001126 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001127 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001128 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1129 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1130 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001131 onResult(response, result);
1132 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001133 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001134 }
1135
Amith Yamasani04e0d262012-02-14 11:50:53 -08001136 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001137 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001138 protected String toDebugString(long now) {
1139 if (loginOptions != null) loginOptions.keySet();
1140 return super.toDebugString(now) + ", getAuthToken"
1141 + ", " + account
1142 + ", authTokenType " + authTokenType
1143 + ", loginOptions " + loginOptions
1144 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1145 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001146
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001147 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001148 // If the caller doesn't have permission then create and return the
1149 // "grant permission" intent instead of the "getAuthToken" intent.
1150 if (!permissionGranted) {
1151 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1152 } else {
1153 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1154 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001155 }
1156
1157 public void onResult(Bundle result) {
1158 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001159 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001160 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1161 new AccountAuthenticatorResponse(this),
1162 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001163 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001164 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001165 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001166 onResult(bundle);
1167 return;
1168 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001169 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001170 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001171 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1172 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001173 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001174 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001175 "the type and name should not be empty");
1176 return;
1177 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001178 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001179 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001180 authTokenType, authToken);
1181 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001182 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001183
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001184 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001185 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001186 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001187 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001188 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001189 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001190 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001191 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001192 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001193 }.bind();
1194 } finally {
1195 restoreCallingIdentity(identityToken);
1196 }
Fred Quintana60307342009-03-24 22:48:12 -07001197 }
1198
Dianne Hackborn41203752012-08-31 14:05:51 -07001199 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1200 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001201 int uid = intent.getIntExtra(
1202 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1203 String authTokenType = intent.getStringExtra(
1204 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1205 String authTokenLabel = intent.getStringExtra(
1206 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1207
1208 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1209 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001210 final String titleAndSubtitle =
1211 mContext.getString(R.string.permission_request_notification_with_subtitle,
1212 account.name);
1213 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001214 String title = titleAndSubtitle;
1215 String subtitle = "";
1216 if (index > 0) {
1217 title = titleAndSubtitle.substring(0, index);
1218 subtitle = titleAndSubtitle.substring(index + 1);
1219 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001220 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001221 n.setLatestEventInfo(mContext, title, subtitle,
1222 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001223 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1224 installNotification(getCredentialPermissionNotificationId(
1225 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001226 }
1227
Costin Manolache5f383ad92010-12-02 16:44:46 -08001228 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1229 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001230
1231 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001232 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001233 // Since it was set in Eclair+ we can't change it without breaking apps using
1234 // the intent from a non-Activity context.
1235 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001236 intent.addCategory(
1237 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001238
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001239 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001240 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1241 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001242 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001243
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001244 return intent;
1245 }
1246
1247 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1248 int uid) {
1249 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001250 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001251 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001252 final Pair<Pair<Account, String>, Integer> key =
1253 new Pair<Pair<Account, String>, Integer>(
1254 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001255 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001256 if (id == null) {
1257 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001258 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001259 }
1260 }
1261 return id;
1262 }
1263
Amith Yamasani04e0d262012-02-14 11:50:53 -08001264 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001265 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001266 synchronized (accounts.signinRequiredNotificationIds) {
1267 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001268 if (id == null) {
1269 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001270 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001271 }
1272 }
1273 return id;
1274 }
1275
Fred Quintana33269202009-04-20 16:05:10 -07001276 public void addAcount(final IAccountManagerResponse response, final String accountType,
1277 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001278 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001279 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1280 Log.v(TAG, "addAccount: accountType " + accountType
1281 + ", response " + response
1282 + ", authTokenType " + authTokenType
1283 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1284 + ", expectActivityLaunch " + expectActivityLaunch
1285 + ", caller's uid " + Binder.getCallingUid()
1286 + ", pid " + Binder.getCallingPid());
1287 }
Fred Quintana382601f2010-03-25 12:25:10 -07001288 if (response == null) throw new IllegalArgumentException("response is null");
1289 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001290 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001291
Amith Yamasani04e0d262012-02-14 11:50:53 -08001292 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001293 final int pid = Binder.getCallingPid();
1294 final int uid = Binder.getCallingUid();
1295 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1296 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1297 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1298
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001299 long identityToken = clearCallingIdentity();
1300 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001301 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001302 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001303 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001304 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001305 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001306 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001307
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001308 protected String toDebugString(long now) {
1309 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001310 + ", accountType " + accountType
1311 + ", requiredFeatures "
1312 + (requiredFeatures != null
1313 ? TextUtils.join(",", requiredFeatures)
1314 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001315 }
1316 }.bind();
1317 } finally {
1318 restoreCallingIdentity(identityToken);
1319 }
Fred Quintana60307342009-03-24 22:48:12 -07001320 }
1321
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001322 @Override
1323 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1324 final Account account, final Bundle options, final boolean expectActivityLaunch,
1325 int userId) {
1326 // Only allow the system process to read accounts of other users
1327 if (userId != UserHandle.getCallingUserId()
Jim Miller464f5302013-02-27 18:33:25 -08001328 && Binder.getCallingUid() != android.os.Process.myUid()
1329 && mContext.checkCallingOrSelfPermission(
1330 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1331 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001332 throw new SecurityException("User " + UserHandle.getCallingUserId()
1333 + " trying to confirm account credentials for " + userId);
1334 }
1335
Fred Quintana56285a62010-12-02 14:20:51 -08001336 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1337 Log.v(TAG, "confirmCredentials: " + account
1338 + ", response " + response
1339 + ", expectActivityLaunch " + expectActivityLaunch
1340 + ", caller's uid " + Binder.getCallingUid()
1341 + ", pid " + Binder.getCallingPid());
1342 }
Fred Quintana382601f2010-03-25 12:25:10 -07001343 if (response == null) throw new IllegalArgumentException("response is null");
1344 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001345 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001346 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001347 long identityToken = clearCallingIdentity();
1348 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001349 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001350 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001351 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001352 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001353 }
1354 protected String toDebugString(long now) {
1355 return super.toDebugString(now) + ", confirmCredentials"
1356 + ", " + account;
1357 }
1358 }.bind();
1359 } finally {
1360 restoreCallingIdentity(identityToken);
1361 }
Fred Quintana60307342009-03-24 22:48:12 -07001362 }
1363
Fred Quintanaa698f422009-04-08 19:14:54 -07001364 public void updateCredentials(IAccountManagerResponse response, final Account account,
1365 final String authTokenType, final boolean expectActivityLaunch,
1366 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001367 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1368 Log.v(TAG, "updateCredentials: " + account
1369 + ", response " + response
1370 + ", authTokenType " + authTokenType
1371 + ", expectActivityLaunch " + expectActivityLaunch
1372 + ", caller's uid " + Binder.getCallingUid()
1373 + ", pid " + Binder.getCallingPid());
1374 }
Fred Quintana382601f2010-03-25 12:25:10 -07001375 if (response == null) throw new IllegalArgumentException("response is null");
1376 if (account == null) throw new IllegalArgumentException("account is null");
1377 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001378 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001379 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001380 long identityToken = clearCallingIdentity();
1381 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001382 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001383 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001384 public void run() throws RemoteException {
1385 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1386 }
1387 protected String toDebugString(long now) {
1388 if (loginOptions != null) loginOptions.keySet();
1389 return super.toDebugString(now) + ", updateCredentials"
1390 + ", " + account
1391 + ", authTokenType " + authTokenType
1392 + ", loginOptions " + loginOptions;
1393 }
1394 }.bind();
1395 } finally {
1396 restoreCallingIdentity(identityToken);
1397 }
Fred Quintana60307342009-03-24 22:48:12 -07001398 }
1399
Fred Quintanaa698f422009-04-08 19:14:54 -07001400 public void editProperties(IAccountManagerResponse response, final String accountType,
1401 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001402 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1403 Log.v(TAG, "editProperties: accountType " + accountType
1404 + ", response " + response
1405 + ", expectActivityLaunch " + expectActivityLaunch
1406 + ", caller's uid " + Binder.getCallingUid()
1407 + ", pid " + Binder.getCallingPid());
1408 }
Fred Quintana382601f2010-03-25 12:25:10 -07001409 if (response == null) throw new IllegalArgumentException("response is null");
1410 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001411 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001412 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001413 long identityToken = clearCallingIdentity();
1414 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001415 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001416 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001417 public void run() throws RemoteException {
1418 mAuthenticator.editProperties(this, mAccountType);
1419 }
1420 protected String toDebugString(long now) {
1421 return super.toDebugString(now) + ", editProperties"
1422 + ", accountType " + accountType;
1423 }
1424 }.bind();
1425 } finally {
1426 restoreCallingIdentity(identityToken);
1427 }
Fred Quintana60307342009-03-24 22:48:12 -07001428 }
1429
Fred Quintana33269202009-04-20 16:05:10 -07001430 private class GetAccountsByTypeAndFeatureSession extends Session {
1431 private final String[] mFeatures;
1432 private volatile Account[] mAccountsOfType = null;
1433 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1434 private volatile int mCurrentAccount = 0;
1435
Amith Yamasani04e0d262012-02-14 11:50:53 -08001436 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
1437 IAccountManagerResponse response, String type, String[] features) {
1438 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001439 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001440 mFeatures = features;
1441 }
1442
1443 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001444 synchronized (mAccounts.cacheLock) {
1445 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001446 }
Fred Quintana33269202009-04-20 16:05:10 -07001447 // check whether each account matches the requested features
1448 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1449 mCurrentAccount = 0;
1450
1451 checkAccount();
1452 }
1453
1454 public void checkAccount() {
1455 if (mCurrentAccount >= mAccountsOfType.length) {
1456 sendResult();
1457 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001458 }
Fred Quintana33269202009-04-20 16:05:10 -07001459
Fred Quintana29e94b82010-03-10 12:11:51 -08001460 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1461 if (accountAuthenticator == null) {
1462 // It is possible that the authenticator has died, which is indicated by
1463 // mAuthenticator being set to null. If this happens then just abort.
1464 // There is no need to send back a result or error in this case since
1465 // that already happened when mAuthenticator was cleared.
1466 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1467 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1468 + " connected to the authenticator, " + toDebugString());
1469 }
1470 return;
1471 }
Fred Quintana33269202009-04-20 16:05:10 -07001472 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001473 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001474 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001475 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001476 }
1477 }
1478
1479 public void onResult(Bundle result) {
1480 mNumResults++;
1481 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001482 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001483 return;
1484 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001485 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001486 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1487 }
1488 mCurrentAccount++;
1489 checkAccount();
1490 }
1491
1492 public void sendResult() {
1493 IAccountManagerResponse response = getResponseAndClose();
1494 if (response != null) {
1495 try {
1496 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1497 for (int i = 0; i < accounts.length; i++) {
1498 accounts[i] = mAccountsWithFeatures.get(i);
1499 }
Fred Quintana56285a62010-12-02 14:20:51 -08001500 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1501 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1502 + response);
1503 }
Fred Quintana33269202009-04-20 16:05:10 -07001504 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001505 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001506 response.onResult(result);
1507 } catch (RemoteException e) {
1508 // if the caller is dead then there is no one to care about remote exceptions
1509 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1510 Log.v(TAG, "failure while notifying response", e);
1511 }
1512 }
1513 }
1514 }
1515
1516
1517 protected String toDebugString(long now) {
1518 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1519 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1520 }
1521 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001522
Amith Yamasani04e0d262012-02-14 11:50:53 -08001523 /**
1524 * Returns the accounts for a specific user
1525 * @hide
1526 */
1527 public Account[] getAccounts(int userId) {
1528 checkReadAccountsPermission();
1529 UserAccounts accounts = getUserAccounts(userId);
1530 long identityToken = clearCallingIdentity();
1531 try {
1532 synchronized (accounts.cacheLock) {
1533 return getAccountsFromCacheLocked(accounts, null);
1534 }
1535 } finally {
1536 restoreCallingIdentity(identityToken);
1537 }
1538 }
1539
Amith Yamasanif29f2362012-04-05 18:29:52 -07001540 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001541 * Returns accounts for all running users.
1542 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001543 * @hide
1544 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001545 public AccountAndUser[] getRunningAccounts() {
1546 final int[] runningUserIds;
1547 try {
1548 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1549 } catch (RemoteException e) {
1550 // Running in system_server; should never happen
1551 throw new RuntimeException(e);
1552 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001553 return getAccounts(runningUserIds);
1554 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001555
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001556 /** {@hide} */
1557 public AccountAndUser[] getAllAccounts() {
1558 final List<UserInfo> users = getUserManager().getUsers();
1559 final int[] userIds = new int[users.size()];
1560 for (int i = 0; i < userIds.length; i++) {
1561 userIds[i] = users.get(i).id;
1562 }
1563 return getAccounts(userIds);
1564 }
1565
1566 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001567 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1568 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001569 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001570 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001571 if (userAccounts == null) continue;
1572 synchronized (userAccounts.cacheLock) {
1573 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null);
1574 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001575 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001576 }
1577 }
1578 }
1579 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001580
1581 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1582 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001583 }
1584
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001585 @Override
1586 public Account[] getAccountsAsUser(String type, int userId) {
1587 // Only allow the system process to read accounts of other users
1588 if (userId != UserHandle.getCallingUserId()
Jim Miller464f5302013-02-27 18:33:25 -08001589 && Binder.getCallingUid() != android.os.Process.myUid()
1590 && mContext.checkCallingOrSelfPermission(
1591 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1592 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001593 throw new SecurityException("User " + UserHandle.getCallingUserId()
1594 + " trying to get account for " + userId);
1595 }
1596
Fred Quintana56285a62010-12-02 14:20:51 -08001597 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1598 Log.v(TAG, "getAccounts: accountType " + type
1599 + ", caller's uid " + Binder.getCallingUid()
1600 + ", pid " + Binder.getCallingPid());
1601 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001602 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001603 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001604 long identityToken = clearCallingIdentity();
1605 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001606 synchronized (accounts.cacheLock) {
1607 return getAccountsFromCacheLocked(accounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001608 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001609 } finally {
1610 restoreCallingIdentity(identityToken);
1611 }
1612 }
1613
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001614 @Override
1615 public Account[] getAccounts(String type) {
1616 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1617 }
1618
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001619 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001620 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001621 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1622 Log.v(TAG, "getAccounts: accountType " + type
1623 + ", response " + response
1624 + ", features " + stringArrayToString(features)
1625 + ", caller's uid " + Binder.getCallingUid()
1626 + ", pid " + Binder.getCallingPid());
1627 }
Fred Quintana382601f2010-03-25 12:25:10 -07001628 if (response == null) throw new IllegalArgumentException("response is null");
1629 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001630 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001631 UserAccounts userAccounts = getUserAccountsForCaller();
Fred Quintana33269202009-04-20 16:05:10 -07001632 long identityToken = clearCallingIdentity();
1633 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001634 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001635 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001636 synchronized (userAccounts.cacheLock) {
1637 accounts = getAccountsFromCacheLocked(userAccounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001638 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001639 Bundle result = new Bundle();
1640 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1641 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001642 return;
1643 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001644 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001645 } finally {
1646 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001647 }
1648 }
1649
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001650 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001651 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001652 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001653 try {
1654 if (cursor.moveToNext()) {
1655 return cursor.getLong(0);
1656 }
1657 return -1;
1658 } finally {
1659 cursor.close();
1660 }
1661 }
1662
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001663 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001664 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1665 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1666 new String[]{key}, null, null, null);
1667 try {
1668 if (cursor.moveToNext()) {
1669 return cursor.getLong(0);
1670 }
1671 return -1;
1672 } finally {
1673 cursor.close();
1674 }
1675 }
1676
Fred Quintanaa698f422009-04-08 19:14:54 -07001677 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001678 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001679 IAccountManagerResponse mResponse;
1680 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001681 final boolean mExpectActivityLaunch;
1682 final long mCreationTime;
1683
Fred Quintana33269202009-04-20 16:05:10 -07001684 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001685 private int mNumRequestContinued = 0;
1686 private int mNumErrors = 0;
1687
Fred Quintana60307342009-03-24 22:48:12 -07001688
1689 IAccountAuthenticator mAuthenticator = null;
1690
Fred Quintana8570f742010-02-18 10:32:54 -08001691 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001692 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001693
Amith Yamasani04e0d262012-02-14 11:50:53 -08001694 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001695 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001696 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001697 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001698 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001699 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001700 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001701 mResponse = response;
1702 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001703 mExpectActivityLaunch = expectActivityLaunch;
1704 mCreationTime = SystemClock.elapsedRealtime();
1705 synchronized (mSessions) {
1706 mSessions.put(toString(), this);
1707 }
1708 try {
1709 response.asBinder().linkToDeath(this, 0 /* flags */);
1710 } catch (RemoteException e) {
1711 mResponse = null;
1712 binderDied();
1713 }
Fred Quintana60307342009-03-24 22:48:12 -07001714 }
1715
Fred Quintanaa698f422009-04-08 19:14:54 -07001716 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001717 if (mResponse == null) {
1718 // this session has already been closed
1719 return null;
1720 }
Fred Quintana60307342009-03-24 22:48:12 -07001721 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001722 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001723 return response;
1724 }
1725
Fred Quintanaa698f422009-04-08 19:14:54 -07001726 private void close() {
1727 synchronized (mSessions) {
1728 if (mSessions.remove(toString()) == null) {
1729 // the session was already closed, so bail out now
1730 return;
1731 }
1732 }
1733 if (mResponse != null) {
1734 // stop listening for response deaths
1735 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1736
1737 // clear this so that we don't accidentally send any further results
1738 mResponse = null;
1739 }
1740 cancelTimeout();
1741 unbind();
1742 }
1743
1744 public void binderDied() {
1745 mResponse = null;
1746 close();
1747 }
1748
1749 protected String toDebugString() {
1750 return toDebugString(SystemClock.elapsedRealtime());
1751 }
1752
1753 protected String toDebugString(long now) {
1754 return "Session: expectLaunch " + mExpectActivityLaunch
1755 + ", connected " + (mAuthenticator != null)
1756 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1757 + "/" + mNumErrors + ")"
1758 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1759 }
1760
Fred Quintana60307342009-03-24 22:48:12 -07001761 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001762 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1763 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1764 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001765 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001766 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001767 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001768 }
1769 }
1770
1771 private void unbind() {
1772 if (mAuthenticator != null) {
1773 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001774 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001775 }
1776 }
1777
1778 public void scheduleTimeout() {
1779 mMessageHandler.sendMessageDelayed(
1780 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1781 }
1782
1783 public void cancelTimeout() {
1784 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1785 }
1786
Fred Quintanab839afc2009-10-14 15:57:28 -07001787 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001788 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001789 try {
1790 run();
1791 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001792 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001793 "remote exception");
1794 }
Fred Quintana60307342009-03-24 22:48:12 -07001795 }
1796
Fred Quintanab839afc2009-10-14 15:57:28 -07001797 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001798 mAuthenticator = null;
1799 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001800 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001801 try {
1802 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1803 "disconnected");
1804 } catch (RemoteException e) {
1805 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1806 Log.v(TAG, "Session.onServiceDisconnected: "
1807 + "caught RemoteException while responding", e);
1808 }
1809 }
Fred Quintana60307342009-03-24 22:48:12 -07001810 }
1811 }
1812
Fred Quintanab839afc2009-10-14 15:57:28 -07001813 public abstract void run() throws RemoteException;
1814
Fred Quintana60307342009-03-24 22:48:12 -07001815 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001816 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001817 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001818 try {
1819 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1820 "timeout");
1821 } catch (RemoteException e) {
1822 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1823 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
1824 e);
1825 }
1826 }
Fred Quintana60307342009-03-24 22:48:12 -07001827 }
1828 }
1829
Fred Quintanaa698f422009-04-08 19:14:54 -07001830 public void onResult(Bundle result) {
1831 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001832 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1833 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1834 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001835 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1836 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001837 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
1838 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001839 }
Fred Quintana60307342009-03-24 22:48:12 -07001840 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001841 IAccountManagerResponse response;
1842 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001843 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001844 response = mResponse;
1845 } else {
1846 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001847 }
Fred Quintana60307342009-03-24 22:48:12 -07001848 if (response != null) {
1849 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001850 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001851 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1852 Log.v(TAG, getClass().getSimpleName()
1853 + " calling onError() on response " + response);
1854 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001855 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001856 "null bundle returned");
1857 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001858 if (mStripAuthTokenFromResult) {
1859 result.remove(AccountManager.KEY_AUTHTOKEN);
1860 }
Fred Quintana56285a62010-12-02 14:20:51 -08001861 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1862 Log.v(TAG, getClass().getSimpleName()
1863 + " calling onResult() on response " + response);
1864 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001865 response.onResult(result);
1866 }
Fred Quintana60307342009-03-24 22:48:12 -07001867 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001868 // if the caller is dead then there is no one to care about remote exceptions
1869 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1870 Log.v(TAG, "failure while notifying response", e);
1871 }
Fred Quintana60307342009-03-24 22:48:12 -07001872 }
1873 }
1874 }
Fred Quintana60307342009-03-24 22:48:12 -07001875
Fred Quintanaa698f422009-04-08 19:14:54 -07001876 public void onRequestContinued() {
1877 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001878 }
1879
1880 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001881 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001882 IAccountManagerResponse response = getResponseAndClose();
1883 if (response != null) {
1884 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001885 Log.v(TAG, getClass().getSimpleName()
1886 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001887 }
1888 try {
1889 response.onError(errorCode, errorMessage);
1890 } catch (RemoteException e) {
1891 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1892 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1893 }
1894 }
1895 } else {
1896 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1897 Log.v(TAG, "Session.onError: already closed");
1898 }
Fred Quintana60307342009-03-24 22:48:12 -07001899 }
1900 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001901
1902 /**
1903 * find the component name for the authenticator and initiate a bind
1904 * if no authenticator or the bind fails then return false, otherwise return true
1905 */
1906 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001907 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1908 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1909 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07001910 if (authenticatorInfo == null) {
1911 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1912 Log.v(TAG, "there is no authenticator for " + authenticatorType
1913 + ", bailing out");
1914 }
1915 return false;
1916 }
1917
1918 Intent intent = new Intent();
1919 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1920 intent.setComponent(authenticatorInfo.componentName);
1921 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1922 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1923 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08001924 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
1925 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001926 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1927 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1928 }
1929 return false;
1930 }
1931
1932
1933 return true;
1934 }
Fred Quintana60307342009-03-24 22:48:12 -07001935 }
1936
1937 private class MessageHandler extends Handler {
1938 MessageHandler(Looper looper) {
1939 super(looper);
1940 }
Costin Manolache3348f142009-09-29 18:58:36 -07001941
Fred Quintana60307342009-03-24 22:48:12 -07001942 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001943 switch (msg.what) {
1944 case MESSAGE_TIMED_OUT:
1945 Session session = (Session)msg.obj;
1946 session.onTimedOut();
1947 break;
1948
1949 default:
1950 throw new IllegalStateException("unhandled message: " + msg.what);
1951 }
1952 }
1953 }
1954
Amith Yamasani04e0d262012-02-14 11:50:53 -08001955 private static String getDatabaseName(int userId) {
1956 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07001957 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001958 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07001959 // Migrate old file, if it exists, to the new location.
1960 // Make sure the new file doesn't already exist. A dummy file could have been
1961 // accidentally created in the old location, causing the new one to become corrupted
1962 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08001963 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07001964 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07001965 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07001966 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07001967 if (!userDir.exists()) {
1968 if (!userDir.mkdirs()) {
1969 throw new IllegalStateException("User dir cannot be created: " + userDir);
1970 }
1971 }
1972 if (!oldFile.renameTo(databaseFile)) {
1973 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
1974 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001975 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08001976 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001977 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08001978 }
1979
Amith Yamasani04e0d262012-02-14 11:50:53 -08001980 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001981
Amith Yamasani04e0d262012-02-14 11:50:53 -08001982 public DatabaseHelper(Context context, int userId) {
1983 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001984 }
1985
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001986 /**
1987 * This call needs to be made while the mCacheLock is held. The way to
1988 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
1989 * @param db The database.
1990 */
Fred Quintana60307342009-03-24 22:48:12 -07001991 @Override
1992 public void onCreate(SQLiteDatabase db) {
1993 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1994 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1995 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1996 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1997 + ACCOUNTS_PASSWORD + " TEXT, "
1998 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1999
2000 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2001 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2002 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2003 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2004 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2005 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2006
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002007 createGrantsTable(db);
2008
Fred Quintana60307342009-03-24 22:48:12 -07002009 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2010 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2011 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2012 + EXTRAS_KEY + " TEXT NOT NULL, "
2013 + EXTRAS_VALUE + " TEXT, "
2014 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2015
2016 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2017 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2018 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002019
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002020 createAccountsDeletionTrigger(db);
2021 }
2022
2023 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002024 db.execSQL(""
2025 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2026 + " BEGIN"
2027 + " DELETE FROM " + TABLE_AUTHTOKENS
2028 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2029 + " DELETE FROM " + TABLE_EXTRAS
2030 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002031 + " DELETE FROM " + TABLE_GRANTS
2032 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002033 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002034 }
2035
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002036 private void createGrantsTable(SQLiteDatabase db) {
2037 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2038 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2039 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2040 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2041 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2042 + "," + GRANTS_GRANTEE_UID + "))");
2043 }
2044
Fred Quintana60307342009-03-24 22:48:12 -07002045 @Override
2046 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002047 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002048
Fred Quintanaa698f422009-04-08 19:14:54 -07002049 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002050 // no longer need to do anything since the work is done
2051 // when upgrading from version 2
2052 oldVersion++;
2053 }
2054
2055 if (oldVersion == 2) {
2056 createGrantsTable(db);
2057 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2058 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002059 oldVersion++;
2060 }
Costin Manolache3348f142009-09-29 18:58:36 -07002061
2062 if (oldVersion == 3) {
2063 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2064 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2065 oldVersion++;
2066 }
Fred Quintana60307342009-03-24 22:48:12 -07002067 }
2068
2069 @Override
2070 public void onOpen(SQLiteDatabase db) {
2071 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2072 }
2073 }
2074
Fred Quintana60307342009-03-24 22:48:12 -07002075 public IBinder onBind(Intent intent) {
2076 return asBinder();
2077 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002078
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002079 /**
2080 * Searches array of arguments for the specified string
2081 * @param args array of argument strings
2082 * @param value value to search for
2083 * @return true if the value is contained in the array
2084 */
2085 private static boolean scanArgs(String[] args, String value) {
2086 if (args != null) {
2087 for (String arg : args) {
2088 if (value.equals(arg)) {
2089 return true;
2090 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002091 }
2092 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002093 return false;
2094 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002095
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002096 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002097 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002098 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2099 != PackageManager.PERMISSION_GRANTED) {
2100 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2101 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2102 + " without permission " + android.Manifest.permission.DUMP);
2103 return;
2104 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002105 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002106 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002107
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002108 final List<UserInfo> users = getUserManager().getUsers();
2109 for (UserInfo user : users) {
2110 ipw.println("User " + user + ":");
2111 ipw.increaseIndent();
2112 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2113 ipw.println();
2114 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002115 }
2116 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002117
Amith Yamasani04e0d262012-02-14 11:50:53 -08002118 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2119 String[] args, boolean isCheckinRequest) {
2120 synchronized (userAccounts.cacheLock) {
2121 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002122
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002123 if (isCheckinRequest) {
2124 // This is a checkin request. *Only* upload the account types and the count of each.
2125 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2126 null, null, ACCOUNTS_TYPE, null, null);
2127 try {
2128 while (cursor.moveToNext()) {
2129 // print type,count
2130 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2131 }
2132 } finally {
2133 if (cursor != null) {
2134 cursor.close();
2135 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002136 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002137 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002138 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002139 fout.println("Accounts: " + accounts.length);
2140 for (Account account : accounts) {
2141 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002142 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002143
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002144 fout.println();
2145 synchronized (mSessions) {
2146 final long now = SystemClock.elapsedRealtime();
2147 fout.println("Active Sessions: " + mSessions.size());
2148 for (Session session : mSessions.values()) {
2149 fout.println(" " + session.toDebugString(now));
2150 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002151 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002152
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002153 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002154 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002155 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002156 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002157 }
2158
Amith Yamasani04e0d262012-02-14 11:50:53 -08002159 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002160 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002161 long identityToken = clearCallingIdentity();
2162 try {
2163 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2164 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2165 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002166
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002167 if (intent.getComponent() != null &&
2168 GrantCredentialsPermissionActivity.class.getName().equals(
2169 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002170 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002171 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002172 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002173 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002174 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2175 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002176 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002177 final String notificationTitleFormat =
2178 mContext.getText(R.string.notification_title).toString();
2179 n.setLatestEventInfo(mContext,
2180 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002181 message, PendingIntent.getActivityAsUser(
2182 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002183 null, user));
2184 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002185 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002186 } finally {
2187 restoreCallingIdentity(identityToken);
2188 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002189 }
2190
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002191 protected void installNotification(final int notificationId, final Notification n,
2192 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002193 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002194 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002195 }
2196
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002197 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002198 long identityToken = clearCallingIdentity();
2199 try {
2200 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002201 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002202 } finally {
2203 restoreCallingIdentity(identityToken);
2204 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002205 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002206
Fred Quintanab38eb142010-02-24 13:40:54 -08002207 /** Succeeds if any of the specified permissions are granted. */
2208 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002209 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002210
2211 for (String perm : permissions) {
2212 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2213 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002214 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002215 }
2216 return;
2217 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002218 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002219
2220 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002221 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002222 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002223 }
2224
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002225 private boolean inSystemImage(int callingUid) {
2226 final int callingUserId = UserHandle.getUserId(callingUid);
2227
2228 final PackageManager userPackageManager;
2229 try {
2230 userPackageManager = mContext.createPackageContextAsUser(
2231 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2232 } catch (NameNotFoundException e) {
2233 return false;
2234 }
2235
2236 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002237 for (String name : packages) {
2238 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002239 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002240 if (packageInfo != null
2241 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002242 return true;
2243 }
2244 } catch (PackageManager.NameNotFoundException e) {
2245 return false;
2246 }
2247 }
2248 return false;
2249 }
2250
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002251 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002252 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002253 final boolean fromAuthenticator = account != null
2254 && hasAuthenticatorUid(account.type, callerUid);
2255 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002256 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002257 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2258 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002259 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002260 + ": is authenticator? " + fromAuthenticator
2261 + ", has explicit permission? " + hasExplicitGrants);
2262 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002263 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002264 }
2265
Fred Quintana1a231912009-10-15 11:31:30 -07002266 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002267 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002268 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002269 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002270 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002271 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002272 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002273 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002274 }
2275 }
2276 return false;
2277 }
2278
Amith Yamasani04e0d262012-02-14 11:50:53 -08002279 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2280 int callerUid) {
2281 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002282 return true;
2283 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002284 UserAccounts accounts = getUserAccountsForCaller();
2285 synchronized (accounts.cacheLock) {
2286 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2287 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002288 account.name, account.type};
2289 final boolean permissionGranted =
2290 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2291 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2292 // TODO: Skip this check when running automated tests. Replace this
2293 // with a more general solution.
2294 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002295 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002296 + " but ignoring since device is in test harness.");
2297 return true;
2298 }
2299 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002300 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002301 }
2302
2303 private void checkCallingUidAgainstAuthenticator(Account account) {
2304 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002305 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002306 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2307 Log.w(TAG, msg);
2308 throw new SecurityException(msg);
2309 }
2310 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2311 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2312 }
2313 }
2314
2315 private void checkAuthenticateAccountsPermission(Account account) {
2316 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2317 checkCallingUidAgainstAuthenticator(account);
2318 }
2319
2320 private void checkReadAccountsPermission() {
2321 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2322 }
2323
2324 private void checkManageAccountsPermission() {
2325 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2326 }
2327
Fred Quintanab38eb142010-02-24 13:40:54 -08002328 private void checkManageAccountsOrUseCredentialsPermissions() {
2329 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2330 Manifest.permission.USE_CREDENTIALS);
2331 }
2332
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002333 private boolean canUserModifyAccounts(int callingUid) {
2334 if (callingUid != android.os.Process.myUid()) {
2335 Bundle restrictions = getUserManager().getUserRestrictions(
2336 new UserHandle(UserHandle.getUserId(callingUid)));
2337 if (!restrictions.getBoolean(UserManager.ALLOW_MODIFY_ACCOUNTS)) {
2338 return false;
2339 }
2340 }
2341 return true;
2342 }
2343
Fred Quintanad9640ec2012-05-23 12:37:00 -07002344 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2345 throws RemoteException {
2346 final int callingUid = getCallingUid();
2347
2348 if (callingUid != android.os.Process.SYSTEM_UID) {
2349 throw new SecurityException();
2350 }
2351
2352 if (value) {
2353 grantAppPermission(account, authTokenType, uid);
2354 } else {
2355 revokeAppPermission(account, authTokenType, uid);
2356 }
2357 }
2358
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002359 /**
2360 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2361 * <p>
2362 * Although this is public it can only be accessed via the AccountManagerService object
2363 * which is in the system. This means we don't need to protect it with permissions.
2364 * @hide
2365 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002366 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002367 if (account == null || authTokenType == null) {
2368 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002369 return;
2370 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002371 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002372 synchronized (accounts.cacheLock) {
2373 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002374 db.beginTransaction();
2375 try {
2376 long accountId = getAccountIdLocked(db, account);
2377 if (accountId >= 0) {
2378 ContentValues values = new ContentValues();
2379 values.put(GRANTS_ACCOUNTS_ID, accountId);
2380 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2381 values.put(GRANTS_GRANTEE_UID, uid);
2382 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2383 db.setTransactionSuccessful();
2384 }
2385 } finally {
2386 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002387 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002388 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2389 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002390 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002391 }
2392
2393 /**
2394 * Don't allow callers with the given uid permission to get credentials for
2395 * account/authTokenType.
2396 * <p>
2397 * Although this is public it can only be accessed via the AccountManagerService object
2398 * which is in the system. This means we don't need to protect it with permissions.
2399 * @hide
2400 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002401 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002402 if (account == null || authTokenType == null) {
2403 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002404 return;
2405 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002406 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002407 synchronized (accounts.cacheLock) {
2408 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002409 db.beginTransaction();
2410 try {
2411 long accountId = getAccountIdLocked(db, account);
2412 if (accountId >= 0) {
2413 db.delete(TABLE_GRANTS,
2414 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2415 + GRANTS_GRANTEE_UID + "=?",
2416 new String[]{String.valueOf(accountId), authTokenType,
2417 String.valueOf(uid)});
2418 db.setTransactionSuccessful();
2419 }
2420 } finally {
2421 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002422 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002423 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2424 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002425 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002426 }
Fred Quintana56285a62010-12-02 14:20:51 -08002427
2428 static final private String stringArrayToString(String[] value) {
2429 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2430 }
2431
Amith Yamasani04e0d262012-02-14 11:50:53 -08002432 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2433 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002434 if (oldAccountsForType != null) {
2435 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2436 for (Account curAccount : oldAccountsForType) {
2437 if (!curAccount.equals(account)) {
2438 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002439 }
2440 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002441 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002442 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002443 } else {
2444 Account[] newAccountsForType = new Account[newAccountsList.size()];
2445 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002446 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002447 }
Fred Quintana56285a62010-12-02 14:20:51 -08002448 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002449 accounts.userDataCache.remove(account);
2450 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002451 }
2452
2453 /**
2454 * This assumes that the caller has already checked that the account is not already present.
2455 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002456 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2457 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002458 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2459 Account[] newAccountsForType = new Account[oldLength + 1];
2460 if (accountsForType != null) {
2461 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002462 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002463 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002464 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002465 }
2466
Amith Yamasani04e0d262012-02-14 11:50:53 -08002467 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002468 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002469 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002470 if (accounts == null) {
2471 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002472 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002473 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002474 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002475 } else {
2476 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002477 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002478 totalLength += accounts.length;
2479 }
2480 if (totalLength == 0) {
2481 return EMPTY_ACCOUNT_ARRAY;
2482 }
2483 Account[] accounts = new Account[totalLength];
2484 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002485 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002486 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2487 accountsOfType.length);
2488 totalLength += accountsOfType.length;
2489 }
2490 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002491 }
2492 }
2493
Amith Yamasani04e0d262012-02-14 11:50:53 -08002494 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2495 Account account, String key, String value) {
2496 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002497 if (userDataForAccount == null) {
2498 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002499 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002500 }
2501 if (value == null) {
2502 userDataForAccount.remove(key);
2503 } else {
2504 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002505 }
2506 }
2507
Amith Yamasani04e0d262012-02-14 11:50:53 -08002508 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2509 Account account, String key, String value) {
2510 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002511 if (authTokensForAccount == null) {
2512 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002513 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002514 }
2515 if (value == null) {
2516 authTokensForAccount.remove(key);
2517 } else {
2518 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002519 }
2520 }
2521
Amith Yamasani04e0d262012-02-14 11:50:53 -08002522 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2523 String authTokenType) {
2524 synchronized (accounts.cacheLock) {
2525 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002526 if (authTokensForAccount == null) {
2527 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002528 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002529 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002530 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002531 }
2532 return authTokensForAccount.get(authTokenType);
2533 }
2534 }
2535
Amith Yamasani04e0d262012-02-14 11:50:53 -08002536 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2537 synchronized (accounts.cacheLock) {
2538 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002539 if (userDataForAccount == null) {
2540 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002541 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002542 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002543 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002544 }
2545 return userDataForAccount.get(key);
2546 }
2547 }
2548
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002549 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2550 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002551 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002552 Cursor cursor = db.query(TABLE_EXTRAS,
2553 COLUMNS_EXTRAS_KEY_AND_VALUE,
2554 SELECTION_USERDATA_BY_ACCOUNT,
2555 new String[]{account.name, account.type},
2556 null, null, null);
2557 try {
2558 while (cursor.moveToNext()) {
2559 final String tmpkey = cursor.getString(0);
2560 final String value = cursor.getString(1);
2561 userDataForAccount.put(tmpkey, value);
2562 }
2563 } finally {
2564 cursor.close();
2565 }
2566 return userDataForAccount;
2567 }
2568
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002569 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2570 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002571 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002572 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2573 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2574 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2575 new String[]{account.name, account.type},
2576 null, null, null);
2577 try {
2578 while (cursor.moveToNext()) {
2579 final String type = cursor.getString(0);
2580 final String authToken = cursor.getString(1);
2581 authTokensForAccount.put(type, authToken);
2582 }
2583 } finally {
2584 cursor.close();
2585 }
2586 return authTokensForAccount;
2587 }
Fred Quintana60307342009-03-24 22:48:12 -07002588}