blob: 2a62c1788489cff73217fbfdd4a2f3c0840d8b4e [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()
1328 && Binder.getCallingUid() != android.os.Process.myUid()) {
1329 throw new SecurityException("User " + UserHandle.getCallingUserId()
1330 + " trying to confirm account credentials for " + userId);
1331 }
1332
Fred Quintana56285a62010-12-02 14:20:51 -08001333 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1334 Log.v(TAG, "confirmCredentials: " + account
1335 + ", response " + response
1336 + ", expectActivityLaunch " + expectActivityLaunch
1337 + ", caller's uid " + Binder.getCallingUid()
1338 + ", pid " + Binder.getCallingPid());
1339 }
Fred Quintana382601f2010-03-25 12:25:10 -07001340 if (response == null) throw new IllegalArgumentException("response is null");
1341 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001342 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001343 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001344 long identityToken = clearCallingIdentity();
1345 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001346 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001347 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001348 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001349 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001350 }
1351 protected String toDebugString(long now) {
1352 return super.toDebugString(now) + ", confirmCredentials"
1353 + ", " + account;
1354 }
1355 }.bind();
1356 } finally {
1357 restoreCallingIdentity(identityToken);
1358 }
Fred Quintana60307342009-03-24 22:48:12 -07001359 }
1360
Fred Quintanaa698f422009-04-08 19:14:54 -07001361 public void updateCredentials(IAccountManagerResponse response, final Account account,
1362 final String authTokenType, final boolean expectActivityLaunch,
1363 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001364 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1365 Log.v(TAG, "updateCredentials: " + account
1366 + ", response " + response
1367 + ", authTokenType " + authTokenType
1368 + ", expectActivityLaunch " + expectActivityLaunch
1369 + ", caller's uid " + Binder.getCallingUid()
1370 + ", pid " + Binder.getCallingPid());
1371 }
Fred Quintana382601f2010-03-25 12:25:10 -07001372 if (response == null) throw new IllegalArgumentException("response is null");
1373 if (account == null) throw new IllegalArgumentException("account is null");
1374 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001375 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001376 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001377 long identityToken = clearCallingIdentity();
1378 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001379 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001380 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001381 public void run() throws RemoteException {
1382 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1383 }
1384 protected String toDebugString(long now) {
1385 if (loginOptions != null) loginOptions.keySet();
1386 return super.toDebugString(now) + ", updateCredentials"
1387 + ", " + account
1388 + ", authTokenType " + authTokenType
1389 + ", loginOptions " + loginOptions;
1390 }
1391 }.bind();
1392 } finally {
1393 restoreCallingIdentity(identityToken);
1394 }
Fred Quintana60307342009-03-24 22:48:12 -07001395 }
1396
Fred Quintanaa698f422009-04-08 19:14:54 -07001397 public void editProperties(IAccountManagerResponse response, final String accountType,
1398 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001399 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1400 Log.v(TAG, "editProperties: accountType " + accountType
1401 + ", response " + response
1402 + ", expectActivityLaunch " + expectActivityLaunch
1403 + ", caller's uid " + Binder.getCallingUid()
1404 + ", pid " + Binder.getCallingPid());
1405 }
Fred Quintana382601f2010-03-25 12:25:10 -07001406 if (response == null) throw new IllegalArgumentException("response is null");
1407 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001408 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001409 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001410 long identityToken = clearCallingIdentity();
1411 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001412 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001413 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001414 public void run() throws RemoteException {
1415 mAuthenticator.editProperties(this, mAccountType);
1416 }
1417 protected String toDebugString(long now) {
1418 return super.toDebugString(now) + ", editProperties"
1419 + ", accountType " + accountType;
1420 }
1421 }.bind();
1422 } finally {
1423 restoreCallingIdentity(identityToken);
1424 }
Fred Quintana60307342009-03-24 22:48:12 -07001425 }
1426
Fred Quintana33269202009-04-20 16:05:10 -07001427 private class GetAccountsByTypeAndFeatureSession extends Session {
1428 private final String[] mFeatures;
1429 private volatile Account[] mAccountsOfType = null;
1430 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1431 private volatile int mCurrentAccount = 0;
1432
Amith Yamasani04e0d262012-02-14 11:50:53 -08001433 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
1434 IAccountManagerResponse response, String type, String[] features) {
1435 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001436 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001437 mFeatures = features;
1438 }
1439
1440 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001441 synchronized (mAccounts.cacheLock) {
1442 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001443 }
Fred Quintana33269202009-04-20 16:05:10 -07001444 // check whether each account matches the requested features
1445 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1446 mCurrentAccount = 0;
1447
1448 checkAccount();
1449 }
1450
1451 public void checkAccount() {
1452 if (mCurrentAccount >= mAccountsOfType.length) {
1453 sendResult();
1454 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001455 }
Fred Quintana33269202009-04-20 16:05:10 -07001456
Fred Quintana29e94b82010-03-10 12:11:51 -08001457 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1458 if (accountAuthenticator == null) {
1459 // It is possible that the authenticator has died, which is indicated by
1460 // mAuthenticator being set to null. If this happens then just abort.
1461 // There is no need to send back a result or error in this case since
1462 // that already happened when mAuthenticator was cleared.
1463 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1464 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1465 + " connected to the authenticator, " + toDebugString());
1466 }
1467 return;
1468 }
Fred Quintana33269202009-04-20 16:05:10 -07001469 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001470 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001471 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001472 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001473 }
1474 }
1475
1476 public void onResult(Bundle result) {
1477 mNumResults++;
1478 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001479 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001480 return;
1481 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001482 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001483 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1484 }
1485 mCurrentAccount++;
1486 checkAccount();
1487 }
1488
1489 public void sendResult() {
1490 IAccountManagerResponse response = getResponseAndClose();
1491 if (response != null) {
1492 try {
1493 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1494 for (int i = 0; i < accounts.length; i++) {
1495 accounts[i] = mAccountsWithFeatures.get(i);
1496 }
Fred Quintana56285a62010-12-02 14:20:51 -08001497 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1498 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1499 + response);
1500 }
Fred Quintana33269202009-04-20 16:05:10 -07001501 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001502 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001503 response.onResult(result);
1504 } catch (RemoteException e) {
1505 // if the caller is dead then there is no one to care about remote exceptions
1506 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1507 Log.v(TAG, "failure while notifying response", e);
1508 }
1509 }
1510 }
1511 }
1512
1513
1514 protected String toDebugString(long now) {
1515 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1516 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1517 }
1518 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001519
Amith Yamasani04e0d262012-02-14 11:50:53 -08001520 /**
1521 * Returns the accounts for a specific user
1522 * @hide
1523 */
1524 public Account[] getAccounts(int userId) {
1525 checkReadAccountsPermission();
1526 UserAccounts accounts = getUserAccounts(userId);
1527 long identityToken = clearCallingIdentity();
1528 try {
1529 synchronized (accounts.cacheLock) {
1530 return getAccountsFromCacheLocked(accounts, null);
1531 }
1532 } finally {
1533 restoreCallingIdentity(identityToken);
1534 }
1535 }
1536
Amith Yamasanif29f2362012-04-05 18:29:52 -07001537 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001538 * Returns accounts for all running users.
1539 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001540 * @hide
1541 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001542 public AccountAndUser[] getRunningAccounts() {
1543 final int[] runningUserIds;
1544 try {
1545 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1546 } catch (RemoteException e) {
1547 // Running in system_server; should never happen
1548 throw new RuntimeException(e);
1549 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001550 return getAccounts(runningUserIds);
1551 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001552
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001553 /** {@hide} */
1554 public AccountAndUser[] getAllAccounts() {
1555 final List<UserInfo> users = getUserManager().getUsers();
1556 final int[] userIds = new int[users.size()];
1557 for (int i = 0; i < userIds.length; i++) {
1558 userIds[i] = users.get(i).id;
1559 }
1560 return getAccounts(userIds);
1561 }
1562
1563 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001564 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1565 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001566 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001567 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001568 if (userAccounts == null) continue;
1569 synchronized (userAccounts.cacheLock) {
1570 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null);
1571 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001572 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001573 }
1574 }
1575 }
1576 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001577
1578 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1579 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001580 }
1581
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001582 @Override
1583 public Account[] getAccountsAsUser(String type, int userId) {
1584 // Only allow the system process to read accounts of other users
1585 if (userId != UserHandle.getCallingUserId()
1586 && Binder.getCallingUid() != android.os.Process.myUid()) {
1587 throw new SecurityException("User " + UserHandle.getCallingUserId()
1588 + " trying to get account for " + userId);
1589 }
1590
Fred Quintana56285a62010-12-02 14:20:51 -08001591 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1592 Log.v(TAG, "getAccounts: accountType " + type
1593 + ", caller's uid " + Binder.getCallingUid()
1594 + ", pid " + Binder.getCallingPid());
1595 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001596 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001597 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001598 long identityToken = clearCallingIdentity();
1599 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001600 synchronized (accounts.cacheLock) {
1601 return getAccountsFromCacheLocked(accounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001602 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001603 } finally {
1604 restoreCallingIdentity(identityToken);
1605 }
1606 }
1607
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001608 @Override
1609 public Account[] getAccounts(String type) {
1610 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1611 }
1612
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001613 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001614 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001615 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1616 Log.v(TAG, "getAccounts: accountType " + type
1617 + ", response " + response
1618 + ", features " + stringArrayToString(features)
1619 + ", caller's uid " + Binder.getCallingUid()
1620 + ", pid " + Binder.getCallingPid());
1621 }
Fred Quintana382601f2010-03-25 12:25:10 -07001622 if (response == null) throw new IllegalArgumentException("response is null");
1623 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001624 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001625 UserAccounts userAccounts = getUserAccountsForCaller();
Fred Quintana33269202009-04-20 16:05:10 -07001626 long identityToken = clearCallingIdentity();
1627 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001628 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001629 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001630 synchronized (userAccounts.cacheLock) {
1631 accounts = getAccountsFromCacheLocked(userAccounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001632 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001633 Bundle result = new Bundle();
1634 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1635 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001636 return;
1637 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001638 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001639 } finally {
1640 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001641 }
1642 }
1643
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001644 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001645 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001646 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001647 try {
1648 if (cursor.moveToNext()) {
1649 return cursor.getLong(0);
1650 }
1651 return -1;
1652 } finally {
1653 cursor.close();
1654 }
1655 }
1656
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001657 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001658 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1659 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1660 new String[]{key}, null, null, null);
1661 try {
1662 if (cursor.moveToNext()) {
1663 return cursor.getLong(0);
1664 }
1665 return -1;
1666 } finally {
1667 cursor.close();
1668 }
1669 }
1670
Fred Quintanaa698f422009-04-08 19:14:54 -07001671 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001672 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001673 IAccountManagerResponse mResponse;
1674 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001675 final boolean mExpectActivityLaunch;
1676 final long mCreationTime;
1677
Fred Quintana33269202009-04-20 16:05:10 -07001678 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001679 private int mNumRequestContinued = 0;
1680 private int mNumErrors = 0;
1681
Fred Quintana60307342009-03-24 22:48:12 -07001682
1683 IAccountAuthenticator mAuthenticator = null;
1684
Fred Quintana8570f742010-02-18 10:32:54 -08001685 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001686 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001687
Amith Yamasani04e0d262012-02-14 11:50:53 -08001688 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001689 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001690 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001691 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001692 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001693 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001694 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001695 mResponse = response;
1696 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001697 mExpectActivityLaunch = expectActivityLaunch;
1698 mCreationTime = SystemClock.elapsedRealtime();
1699 synchronized (mSessions) {
1700 mSessions.put(toString(), this);
1701 }
1702 try {
1703 response.asBinder().linkToDeath(this, 0 /* flags */);
1704 } catch (RemoteException e) {
1705 mResponse = null;
1706 binderDied();
1707 }
Fred Quintana60307342009-03-24 22:48:12 -07001708 }
1709
Fred Quintanaa698f422009-04-08 19:14:54 -07001710 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001711 if (mResponse == null) {
1712 // this session has already been closed
1713 return null;
1714 }
Fred Quintana60307342009-03-24 22:48:12 -07001715 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001716 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001717 return response;
1718 }
1719
Fred Quintanaa698f422009-04-08 19:14:54 -07001720 private void close() {
1721 synchronized (mSessions) {
1722 if (mSessions.remove(toString()) == null) {
1723 // the session was already closed, so bail out now
1724 return;
1725 }
1726 }
1727 if (mResponse != null) {
1728 // stop listening for response deaths
1729 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1730
1731 // clear this so that we don't accidentally send any further results
1732 mResponse = null;
1733 }
1734 cancelTimeout();
1735 unbind();
1736 }
1737
1738 public void binderDied() {
1739 mResponse = null;
1740 close();
1741 }
1742
1743 protected String toDebugString() {
1744 return toDebugString(SystemClock.elapsedRealtime());
1745 }
1746
1747 protected String toDebugString(long now) {
1748 return "Session: expectLaunch " + mExpectActivityLaunch
1749 + ", connected " + (mAuthenticator != null)
1750 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1751 + "/" + mNumErrors + ")"
1752 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1753 }
1754
Fred Quintana60307342009-03-24 22:48:12 -07001755 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001756 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1757 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1758 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001759 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001760 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001761 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001762 }
1763 }
1764
1765 private void unbind() {
1766 if (mAuthenticator != null) {
1767 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001768 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001769 }
1770 }
1771
1772 public void scheduleTimeout() {
1773 mMessageHandler.sendMessageDelayed(
1774 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1775 }
1776
1777 public void cancelTimeout() {
1778 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1779 }
1780
Fred Quintanab839afc2009-10-14 15:57:28 -07001781 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001782 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001783 try {
1784 run();
1785 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001786 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001787 "remote exception");
1788 }
Fred Quintana60307342009-03-24 22:48:12 -07001789 }
1790
Fred Quintanab839afc2009-10-14 15:57:28 -07001791 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001792 mAuthenticator = null;
1793 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001794 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001795 try {
1796 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1797 "disconnected");
1798 } catch (RemoteException e) {
1799 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1800 Log.v(TAG, "Session.onServiceDisconnected: "
1801 + "caught RemoteException while responding", e);
1802 }
1803 }
Fred Quintana60307342009-03-24 22:48:12 -07001804 }
1805 }
1806
Fred Quintanab839afc2009-10-14 15:57:28 -07001807 public abstract void run() throws RemoteException;
1808
Fred Quintana60307342009-03-24 22:48:12 -07001809 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001810 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001811 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001812 try {
1813 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1814 "timeout");
1815 } catch (RemoteException e) {
1816 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1817 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
1818 e);
1819 }
1820 }
Fred Quintana60307342009-03-24 22:48:12 -07001821 }
1822 }
1823
Fred Quintanaa698f422009-04-08 19:14:54 -07001824 public void onResult(Bundle result) {
1825 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001826 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1827 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1828 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001829 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1830 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001831 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
1832 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001833 }
Fred Quintana60307342009-03-24 22:48:12 -07001834 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001835 IAccountManagerResponse response;
1836 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001837 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001838 response = mResponse;
1839 } else {
1840 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001841 }
Fred Quintana60307342009-03-24 22:48:12 -07001842 if (response != null) {
1843 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001844 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001845 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1846 Log.v(TAG, getClass().getSimpleName()
1847 + " calling onError() on response " + response);
1848 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001849 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001850 "null bundle returned");
1851 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001852 if (mStripAuthTokenFromResult) {
1853 result.remove(AccountManager.KEY_AUTHTOKEN);
1854 }
Fred Quintana56285a62010-12-02 14:20:51 -08001855 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1856 Log.v(TAG, getClass().getSimpleName()
1857 + " calling onResult() on response " + response);
1858 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001859 response.onResult(result);
1860 }
Fred Quintana60307342009-03-24 22:48:12 -07001861 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001862 // if the caller is dead then there is no one to care about remote exceptions
1863 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1864 Log.v(TAG, "failure while notifying response", e);
1865 }
Fred Quintana60307342009-03-24 22:48:12 -07001866 }
1867 }
1868 }
Fred Quintana60307342009-03-24 22:48:12 -07001869
Fred Quintanaa698f422009-04-08 19:14:54 -07001870 public void onRequestContinued() {
1871 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001872 }
1873
1874 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001875 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001876 IAccountManagerResponse response = getResponseAndClose();
1877 if (response != null) {
1878 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001879 Log.v(TAG, getClass().getSimpleName()
1880 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001881 }
1882 try {
1883 response.onError(errorCode, errorMessage);
1884 } catch (RemoteException e) {
1885 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1886 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1887 }
1888 }
1889 } else {
1890 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1891 Log.v(TAG, "Session.onError: already closed");
1892 }
Fred Quintana60307342009-03-24 22:48:12 -07001893 }
1894 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001895
1896 /**
1897 * find the component name for the authenticator and initiate a bind
1898 * if no authenticator or the bind fails then return false, otherwise return true
1899 */
1900 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001901 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1902 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1903 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07001904 if (authenticatorInfo == null) {
1905 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1906 Log.v(TAG, "there is no authenticator for " + authenticatorType
1907 + ", bailing out");
1908 }
1909 return false;
1910 }
1911
1912 Intent intent = new Intent();
1913 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1914 intent.setComponent(authenticatorInfo.componentName);
1915 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1916 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1917 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08001918 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
1919 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001920 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1921 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1922 }
1923 return false;
1924 }
1925
1926
1927 return true;
1928 }
Fred Quintana60307342009-03-24 22:48:12 -07001929 }
1930
1931 private class MessageHandler extends Handler {
1932 MessageHandler(Looper looper) {
1933 super(looper);
1934 }
Costin Manolache3348f142009-09-29 18:58:36 -07001935
Fred Quintana60307342009-03-24 22:48:12 -07001936 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001937 switch (msg.what) {
1938 case MESSAGE_TIMED_OUT:
1939 Session session = (Session)msg.obj;
1940 session.onTimedOut();
1941 break;
1942
1943 default:
1944 throw new IllegalStateException("unhandled message: " + msg.what);
1945 }
1946 }
1947 }
1948
Amith Yamasani04e0d262012-02-14 11:50:53 -08001949 private static String getDatabaseName(int userId) {
1950 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07001951 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001952 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07001953 // Migrate old file, if it exists, to the new location.
1954 // Make sure the new file doesn't already exist. A dummy file could have been
1955 // accidentally created in the old location, causing the new one to become corrupted
1956 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08001957 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07001958 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07001959 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07001960 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07001961 if (!userDir.exists()) {
1962 if (!userDir.mkdirs()) {
1963 throw new IllegalStateException("User dir cannot be created: " + userDir);
1964 }
1965 }
1966 if (!oldFile.renameTo(databaseFile)) {
1967 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
1968 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001969 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08001970 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001971 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08001972 }
1973
Amith Yamasani04e0d262012-02-14 11:50:53 -08001974 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001975
Amith Yamasani04e0d262012-02-14 11:50:53 -08001976 public DatabaseHelper(Context context, int userId) {
1977 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001978 }
1979
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001980 /**
1981 * This call needs to be made while the mCacheLock is held. The way to
1982 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
1983 * @param db The database.
1984 */
Fred Quintana60307342009-03-24 22:48:12 -07001985 @Override
1986 public void onCreate(SQLiteDatabase db) {
1987 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1988 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1989 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1990 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1991 + ACCOUNTS_PASSWORD + " TEXT, "
1992 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1993
1994 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1995 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1996 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1997 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1998 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1999 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2000
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002001 createGrantsTable(db);
2002
Fred Quintana60307342009-03-24 22:48:12 -07002003 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2004 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2005 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2006 + EXTRAS_KEY + " TEXT NOT NULL, "
2007 + EXTRAS_VALUE + " TEXT, "
2008 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2009
2010 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2011 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2012 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002013
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002014 createAccountsDeletionTrigger(db);
2015 }
2016
2017 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002018 db.execSQL(""
2019 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2020 + " BEGIN"
2021 + " DELETE FROM " + TABLE_AUTHTOKENS
2022 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2023 + " DELETE FROM " + TABLE_EXTRAS
2024 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002025 + " DELETE FROM " + TABLE_GRANTS
2026 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002027 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002028 }
2029
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002030 private void createGrantsTable(SQLiteDatabase db) {
2031 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2032 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2033 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2034 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2035 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2036 + "," + GRANTS_GRANTEE_UID + "))");
2037 }
2038
Fred Quintana60307342009-03-24 22:48:12 -07002039 @Override
2040 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002041 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002042
Fred Quintanaa698f422009-04-08 19:14:54 -07002043 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002044 // no longer need to do anything since the work is done
2045 // when upgrading from version 2
2046 oldVersion++;
2047 }
2048
2049 if (oldVersion == 2) {
2050 createGrantsTable(db);
2051 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2052 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002053 oldVersion++;
2054 }
Costin Manolache3348f142009-09-29 18:58:36 -07002055
2056 if (oldVersion == 3) {
2057 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2058 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2059 oldVersion++;
2060 }
Fred Quintana60307342009-03-24 22:48:12 -07002061 }
2062
2063 @Override
2064 public void onOpen(SQLiteDatabase db) {
2065 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2066 }
2067 }
2068
Fred Quintana60307342009-03-24 22:48:12 -07002069 public IBinder onBind(Intent intent) {
2070 return asBinder();
2071 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002072
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002073 /**
2074 * Searches array of arguments for the specified string
2075 * @param args array of argument strings
2076 * @param value value to search for
2077 * @return true if the value is contained in the array
2078 */
2079 private static boolean scanArgs(String[] args, String value) {
2080 if (args != null) {
2081 for (String arg : args) {
2082 if (value.equals(arg)) {
2083 return true;
2084 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002085 }
2086 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002087 return false;
2088 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002089
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002090 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002091 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002092 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2093 != PackageManager.PERMISSION_GRANTED) {
2094 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2095 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2096 + " without permission " + android.Manifest.permission.DUMP);
2097 return;
2098 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002099 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002100 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002101
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002102 final List<UserInfo> users = getUserManager().getUsers();
2103 for (UserInfo user : users) {
2104 ipw.println("User " + user + ":");
2105 ipw.increaseIndent();
2106 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2107 ipw.println();
2108 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002109 }
2110 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002111
Amith Yamasani04e0d262012-02-14 11:50:53 -08002112 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2113 String[] args, boolean isCheckinRequest) {
2114 synchronized (userAccounts.cacheLock) {
2115 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002116
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002117 if (isCheckinRequest) {
2118 // This is a checkin request. *Only* upload the account types and the count of each.
2119 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2120 null, null, ACCOUNTS_TYPE, null, null);
2121 try {
2122 while (cursor.moveToNext()) {
2123 // print type,count
2124 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2125 }
2126 } finally {
2127 if (cursor != null) {
2128 cursor.close();
2129 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002130 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002131 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002132 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002133 fout.println("Accounts: " + accounts.length);
2134 for (Account account : accounts) {
2135 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002136 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002137
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002138 fout.println();
2139 synchronized (mSessions) {
2140 final long now = SystemClock.elapsedRealtime();
2141 fout.println("Active Sessions: " + mSessions.size());
2142 for (Session session : mSessions.values()) {
2143 fout.println(" " + session.toDebugString(now));
2144 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002145 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002146
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002147 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002148 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002149 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002150 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002151 }
2152
Amith Yamasani04e0d262012-02-14 11:50:53 -08002153 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002154 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002155 long identityToken = clearCallingIdentity();
2156 try {
2157 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2158 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2159 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002160
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002161 if (intent.getComponent() != null &&
2162 GrantCredentialsPermissionActivity.class.getName().equals(
2163 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002164 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002165 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002166 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002167 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002168 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2169 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002170 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002171 final String notificationTitleFormat =
2172 mContext.getText(R.string.notification_title).toString();
2173 n.setLatestEventInfo(mContext,
2174 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002175 message, PendingIntent.getActivityAsUser(
2176 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002177 null, user));
2178 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002179 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002180 } finally {
2181 restoreCallingIdentity(identityToken);
2182 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002183 }
2184
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002185 protected void installNotification(final int notificationId, final Notification n,
2186 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002187 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002188 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002189 }
2190
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002191 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002192 long identityToken = clearCallingIdentity();
2193 try {
2194 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002195 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002196 } finally {
2197 restoreCallingIdentity(identityToken);
2198 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002199 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002200
Fred Quintanab38eb142010-02-24 13:40:54 -08002201 /** Succeeds if any of the specified permissions are granted. */
2202 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002203 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002204
2205 for (String perm : permissions) {
2206 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2207 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002208 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002209 }
2210 return;
2211 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002212 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002213
2214 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002215 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002216 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002217 }
2218
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002219 private boolean inSystemImage(int callingUid) {
2220 final int callingUserId = UserHandle.getUserId(callingUid);
2221
2222 final PackageManager userPackageManager;
2223 try {
2224 userPackageManager = mContext.createPackageContextAsUser(
2225 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2226 } catch (NameNotFoundException e) {
2227 return false;
2228 }
2229
2230 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002231 for (String name : packages) {
2232 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002233 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002234 if (packageInfo != null
2235 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002236 return true;
2237 }
2238 } catch (PackageManager.NameNotFoundException e) {
2239 return false;
2240 }
2241 }
2242 return false;
2243 }
2244
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002245 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002246 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002247 final boolean fromAuthenticator = account != null
2248 && hasAuthenticatorUid(account.type, callerUid);
2249 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002250 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002251 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2252 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002253 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002254 + ": is authenticator? " + fromAuthenticator
2255 + ", has explicit permission? " + hasExplicitGrants);
2256 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002257 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002258 }
2259
Fred Quintana1a231912009-10-15 11:31:30 -07002260 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002261 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002262 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002263 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002264 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002265 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002266 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002267 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002268 }
2269 }
2270 return false;
2271 }
2272
Amith Yamasani04e0d262012-02-14 11:50:53 -08002273 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2274 int callerUid) {
2275 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002276 return true;
2277 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002278 UserAccounts accounts = getUserAccountsForCaller();
2279 synchronized (accounts.cacheLock) {
2280 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2281 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002282 account.name, account.type};
2283 final boolean permissionGranted =
2284 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2285 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2286 // TODO: Skip this check when running automated tests. Replace this
2287 // with a more general solution.
2288 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002289 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002290 + " but ignoring since device is in test harness.");
2291 return true;
2292 }
2293 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002294 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002295 }
2296
2297 private void checkCallingUidAgainstAuthenticator(Account account) {
2298 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002299 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002300 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2301 Log.w(TAG, msg);
2302 throw new SecurityException(msg);
2303 }
2304 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2305 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2306 }
2307 }
2308
2309 private void checkAuthenticateAccountsPermission(Account account) {
2310 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2311 checkCallingUidAgainstAuthenticator(account);
2312 }
2313
2314 private void checkReadAccountsPermission() {
2315 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2316 }
2317
2318 private void checkManageAccountsPermission() {
2319 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2320 }
2321
Fred Quintanab38eb142010-02-24 13:40:54 -08002322 private void checkManageAccountsOrUseCredentialsPermissions() {
2323 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2324 Manifest.permission.USE_CREDENTIALS);
2325 }
2326
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002327 private boolean canUserModifyAccounts(int callingUid) {
2328 if (callingUid != android.os.Process.myUid()) {
2329 Bundle restrictions = getUserManager().getUserRestrictions(
2330 new UserHandle(UserHandle.getUserId(callingUid)));
2331 if (!restrictions.getBoolean(UserManager.ALLOW_MODIFY_ACCOUNTS)) {
2332 return false;
2333 }
2334 }
2335 return true;
2336 }
2337
Fred Quintanad9640ec2012-05-23 12:37:00 -07002338 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2339 throws RemoteException {
2340 final int callingUid = getCallingUid();
2341
2342 if (callingUid != android.os.Process.SYSTEM_UID) {
2343 throw new SecurityException();
2344 }
2345
2346 if (value) {
2347 grantAppPermission(account, authTokenType, uid);
2348 } else {
2349 revokeAppPermission(account, authTokenType, uid);
2350 }
2351 }
2352
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002353 /**
2354 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2355 * <p>
2356 * Although this is public it can only be accessed via the AccountManagerService object
2357 * which is in the system. This means we don't need to protect it with permissions.
2358 * @hide
2359 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002360 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002361 if (account == null || authTokenType == null) {
2362 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002363 return;
2364 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002365 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002366 synchronized (accounts.cacheLock) {
2367 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002368 db.beginTransaction();
2369 try {
2370 long accountId = getAccountIdLocked(db, account);
2371 if (accountId >= 0) {
2372 ContentValues values = new ContentValues();
2373 values.put(GRANTS_ACCOUNTS_ID, accountId);
2374 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2375 values.put(GRANTS_GRANTEE_UID, uid);
2376 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2377 db.setTransactionSuccessful();
2378 }
2379 } finally {
2380 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002381 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002382 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2383 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002384 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002385 }
2386
2387 /**
2388 * Don't allow callers with the given uid permission to get credentials for
2389 * account/authTokenType.
2390 * <p>
2391 * Although this is public it can only be accessed via the AccountManagerService object
2392 * which is in the system. This means we don't need to protect it with permissions.
2393 * @hide
2394 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002395 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002396 if (account == null || authTokenType == null) {
2397 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002398 return;
2399 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002400 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002401 synchronized (accounts.cacheLock) {
2402 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002403 db.beginTransaction();
2404 try {
2405 long accountId = getAccountIdLocked(db, account);
2406 if (accountId >= 0) {
2407 db.delete(TABLE_GRANTS,
2408 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2409 + GRANTS_GRANTEE_UID + "=?",
2410 new String[]{String.valueOf(accountId), authTokenType,
2411 String.valueOf(uid)});
2412 db.setTransactionSuccessful();
2413 }
2414 } finally {
2415 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002416 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002417 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2418 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002419 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002420 }
Fred Quintana56285a62010-12-02 14:20:51 -08002421
2422 static final private String stringArrayToString(String[] value) {
2423 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2424 }
2425
Amith Yamasani04e0d262012-02-14 11:50:53 -08002426 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2427 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002428 if (oldAccountsForType != null) {
2429 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2430 for (Account curAccount : oldAccountsForType) {
2431 if (!curAccount.equals(account)) {
2432 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002433 }
2434 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002435 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002436 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002437 } else {
2438 Account[] newAccountsForType = new Account[newAccountsList.size()];
2439 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002440 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002441 }
Fred Quintana56285a62010-12-02 14:20:51 -08002442 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002443 accounts.userDataCache.remove(account);
2444 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002445 }
2446
2447 /**
2448 * This assumes that the caller has already checked that the account is not already present.
2449 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002450 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2451 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002452 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2453 Account[] newAccountsForType = new Account[oldLength + 1];
2454 if (accountsForType != null) {
2455 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002456 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002457 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002458 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002459 }
2460
Amith Yamasani04e0d262012-02-14 11:50:53 -08002461 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002462 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002463 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002464 if (accounts == null) {
2465 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002466 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002467 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002468 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002469 } else {
2470 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002471 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002472 totalLength += accounts.length;
2473 }
2474 if (totalLength == 0) {
2475 return EMPTY_ACCOUNT_ARRAY;
2476 }
2477 Account[] accounts = new Account[totalLength];
2478 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002479 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002480 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2481 accountsOfType.length);
2482 totalLength += accountsOfType.length;
2483 }
2484 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002485 }
2486 }
2487
Amith Yamasani04e0d262012-02-14 11:50:53 -08002488 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2489 Account account, String key, String value) {
2490 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002491 if (userDataForAccount == null) {
2492 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002493 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002494 }
2495 if (value == null) {
2496 userDataForAccount.remove(key);
2497 } else {
2498 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002499 }
2500 }
2501
Amith Yamasani04e0d262012-02-14 11:50:53 -08002502 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2503 Account account, String key, String value) {
2504 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002505 if (authTokensForAccount == null) {
2506 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002507 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002508 }
2509 if (value == null) {
2510 authTokensForAccount.remove(key);
2511 } else {
2512 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002513 }
2514 }
2515
Amith Yamasani04e0d262012-02-14 11:50:53 -08002516 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2517 String authTokenType) {
2518 synchronized (accounts.cacheLock) {
2519 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002520 if (authTokensForAccount == null) {
2521 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002522 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002523 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002524 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002525 }
2526 return authTokensForAccount.get(authTokenType);
2527 }
2528 }
2529
Amith Yamasani04e0d262012-02-14 11:50:53 -08002530 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2531 synchronized (accounts.cacheLock) {
2532 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002533 if (userDataForAccount == null) {
2534 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002535 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002536 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002537 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002538 }
2539 return userDataForAccount.get(key);
2540 }
2541 }
2542
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002543 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2544 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002545 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002546 Cursor cursor = db.query(TABLE_EXTRAS,
2547 COLUMNS_EXTRAS_KEY_AND_VALUE,
2548 SELECTION_USERDATA_BY_ACCOUNT,
2549 new String[]{account.name, account.type},
2550 null, null, null);
2551 try {
2552 while (cursor.moveToNext()) {
2553 final String tmpkey = cursor.getString(0);
2554 final String value = cursor.getString(1);
2555 userDataForAccount.put(tmpkey, value);
2556 }
2557 } finally {
2558 cursor.close();
2559 }
2560 return userDataForAccount;
2561 }
2562
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002563 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2564 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002565 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002566 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2567 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2568 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2569 new String[]{account.name, account.type},
2570 null, null, null);
2571 try {
2572 while (cursor.moveToNext()) {
2573 final String type = cursor.getString(0);
2574 final String authToken = cursor.getString(1);
2575 authTokensForAccount.put(type, authToken);
2576 }
2577 } finally {
2578 cursor.close();
2579 }
2580 return authTokensForAccount;
2581 }
Fred Quintana60307342009-03-24 22:48:12 -07002582}