blob: cc90b860d3380b01e3c8f9366191ec88ae29f9ec [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
17package android.accounts;
18
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080020import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070021import android.app.ActivityManagerNative;
Doug Zongker885cfc232009-10-21 16:52:44 -070022import android.app.Notification;
23import android.app.NotificationManager;
24import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070025import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070026import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070031import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070032import android.content.pm.ApplicationInfo;
33import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070034import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070035import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070036import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070037import android.content.pm.RegisteredServicesCacheListener;
Fred Quintana60307342009-03-24 22:48:12 -070038import android.database.Cursor;
39import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070040import android.database.sqlite.SQLiteDatabase;
41import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070042import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070043import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080044import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070045import android.os.Handler;
46import android.os.HandlerThread;
47import android.os.IBinder;
48import android.os.Looper;
49import android.os.Message;
50import android.os.RemoteException;
51import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070052import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070053import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070054import android.text.TextUtils;
55import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070056import android.util.Pair;
Amith Yamasani04e0d262012-02-14 11:50:53 -080057import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070058
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070059import com.android.internal.R;
Amith Yamasani04e0d262012-02-14 11:50:53 -080060import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070061import com.google.android.collect.Lists;
62import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070063
Oscar Montemayora8529f62009-11-18 10:14:20 -080064import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import java.io.FileDescriptor;
66import java.io.PrintWriter;
67import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080068import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070070import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070071import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080072import java.util.LinkedHashMap;
Andy McFadden2f362292012-01-20 14:43:38 -080073import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070074import java.util.concurrent.atomic.AtomicInteger;
75import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070076
Fred Quintana60307342009-03-24 22:48:12 -070077/**
78 * A system service that provides account, password, and authtoken management for all
79 * accounts on the device. Some of these calls are implemented with the help of the corresponding
80 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
81 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070082 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -070083 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070084 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070085public class AccountManagerService
86 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080087 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -070088 private static final String TAG = "AccountManagerService";
89
90 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
91 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070092 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070093
94 private final Context mContext;
95
Fred Quintana56285a62010-12-02 14:20:51 -080096 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070097 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -080098
Fred Quintana60307342009-03-24 22:48:12 -070099 private HandlerThread mMessageThread;
100 private final MessageHandler mMessageHandler;
101
102 // Messages that can be sent on mHandler
103 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700104
Fred Quintana56285a62010-12-02 14:20:51 -0800105 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700106
107 private static final String TABLE_ACCOUNTS = "accounts";
108 private static final String ACCOUNTS_ID = "_id";
109 private static final String ACCOUNTS_NAME = "name";
110 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700111 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700112 private static final String ACCOUNTS_PASSWORD = "password";
113
114 private static final String TABLE_AUTHTOKENS = "authtokens";
115 private static final String AUTHTOKENS_ID = "_id";
116 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
117 private static final String AUTHTOKENS_TYPE = "type";
118 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
119
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700120 private static final String TABLE_GRANTS = "grants";
121 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
122 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
123 private static final String GRANTS_GRANTEE_UID = "uid";
124
Fred Quintana60307342009-03-24 22:48:12 -0700125 private static final String TABLE_EXTRAS = "extras";
126 private static final String EXTRAS_ID = "_id";
127 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
128 private static final String EXTRAS_KEY = "key";
129 private static final String EXTRAS_VALUE = "value";
130
131 private static final String TABLE_META = "meta";
132 private static final String META_KEY = "key";
133 private static final String META_VALUE = "value";
134
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700135 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
136 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700137 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700138
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700139 private static final String COUNT_OF_MATCHING_GRANTS = ""
140 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
141 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
142 + " AND " + GRANTS_GRANTEE_UID + "=?"
143 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
144 + " AND " + ACCOUNTS_NAME + "=?"
145 + " AND " + ACCOUNTS_TYPE + "=?";
146
Fred Quintana56285a62010-12-02 14:20:51 -0800147 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
148 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
149 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
150 AUTHTOKENS_AUTHTOKEN};
151
152 private static final String SELECTION_USERDATA_BY_ACCOUNT =
153 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
154 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
155
Fred Quintanaa698f422009-04-08 19:14:54 -0700156 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700157 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
158
Amith Yamasani04e0d262012-02-14 11:50:53 -0800159 static class UserAccounts {
160 private final int userId;
161 private final DatabaseHelper openHelper;
162 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
163 credentialsPermissionNotificationIds =
164 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
165 private final HashMap<Account, Integer> signinRequiredNotificationIds =
166 new HashMap<Account, Integer>();
167 private final Object cacheLock = new Object();
168 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700169 private final HashMap<String, Account[]> accountCache =
170 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800171 /** protected by the {@link #cacheLock} */
172 private HashMap<Account, HashMap<String, String>> userDataCache =
173 new HashMap<Account, HashMap<String, String>>();
174 /** protected by the {@link #cacheLock} */
175 private HashMap<Account, HashMap<String, String>> authTokenCache =
176 new HashMap<Account, HashMap<String, String>>();
177
178 UserAccounts(Context context, int userId) {
179 this.userId = userId;
180 synchronized (cacheLock) {
181 openHelper = new DatabaseHelper(context, userId);
182 }
183 }
184 }
185
186 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
187
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700188 private static AtomicReference<AccountManagerService> sThis =
189 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700190 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700191
192 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700193 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700194 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
195 }
196
Fred Quintana56285a62010-12-02 14:20:51 -0800197
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700198 /**
199 * This should only be called by system code. One should only call this after the service
200 * has started.
201 * @return a reference to the AccountManagerService instance
202 * @hide
203 */
204 public static AccountManagerService getSingleton() {
205 return sThis.get();
206 }
Fred Quintana60307342009-03-24 22:48:12 -0700207
Fred Quintana56285a62010-12-02 14:20:51 -0800208 public AccountManagerService(Context context) {
209 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700210 }
211
Fred Quintana56285a62010-12-02 14:20:51 -0800212 public AccountManagerService(Context context, PackageManager packageManager,
213 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700214 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800215 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700216
Fred Quintana60307342009-03-24 22:48:12 -0700217 mMessageThread = new HandlerThread("AccountManagerService");
218 mMessageThread.start();
219 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
220
Fred Quintana56285a62010-12-02 14:20:51 -0800221 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800222 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700223
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700224 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800225
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800226 IntentFilter intentFilter = new IntentFilter();
227 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
228 intentFilter.addDataScheme("package");
229 mContext.registerReceiver(new BroadcastReceiver() {
230 @Override
231 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800232 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800233 }
234 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800235
Amith Yamasani13593602012-03-22 16:16:17 -0700236 IntentFilter userFilter = new IntentFilter();
237 userFilter.addAction(Intent.ACTION_USER_REMOVED);
238 mContext.registerReceiver(new BroadcastReceiver() {
239 @Override
240 public void onReceive(Context context, Intent intent) {
241 onUserRemoved(intent);
242 }
243 }, userFilter);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800244 }
245
Kenny Root26ff6622012-07-30 12:58:03 -0700246 public void systemReady() {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700247 initUser(UserHandle.USER_OWNER);
Kenny Root26ff6622012-07-30 12:58:03 -0700248 }
249
Amith Yamasani258848d2012-08-10 17:06:33 -0700250 private UserManager getUserManager() {
251 if (mUserManager == null) {
252 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
253 }
254 return mUserManager;
255 }
256
Amith Yamasani04e0d262012-02-14 11:50:53 -0800257 private UserAccounts initUser(int userId) {
258 synchronized (mUsers) {
259 UserAccounts accounts = mUsers.get(userId);
260 if (accounts == null) {
261 accounts = new UserAccounts(mContext, userId);
262 mUsers.append(userId, accounts);
263 purgeOldGrants(accounts);
264 validateAccountsAndPopulateCache(accounts);
265 }
266 return accounts;
267 }
268 }
269
270 private void purgeOldGrantsAll() {
271 synchronized (mUsers) {
272 for (int i = 0; i < mUsers.size(); i++) {
273 purgeOldGrants(mUsers.valueAt(i));
274 }
275 }
276 }
277
278 private void purgeOldGrants(UserAccounts accounts) {
279 synchronized (accounts.cacheLock) {
280 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800281 final Cursor cursor = db.query(TABLE_GRANTS,
282 new String[]{GRANTS_GRANTEE_UID},
283 null, null, GRANTS_GRANTEE_UID, null, null);
284 try {
285 while (cursor.moveToNext()) {
286 final int uid = cursor.getInt(0);
287 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
288 if (packageExists) {
289 continue;
290 }
291 Log.d(TAG, "deleting grants for UID " + uid
292 + " because its package is no longer installed");
293 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
294 new String[]{Integer.toString(uid)});
295 }
296 } finally {
297 cursor.close();
298 }
299 }
300 }
301
Amith Yamasani04e0d262012-02-14 11:50:53 -0800302 private void validateAccountsAndPopulateCache(UserAccounts accounts) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700303 mAuthenticatorCache.invalidateCache(accounts.userId);
304
305 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
306 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
307 mAuthenticatorCache.getAllServices(accounts.userId)) {
308 knownAuth.add(service.type);
309 }
310
Amith Yamasani04e0d262012-02-14 11:50:53 -0800311 synchronized (accounts.cacheLock) {
312 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800313 boolean accountDeleted = false;
314 Cursor cursor = db.query(TABLE_ACCOUNTS,
315 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
316 null, null, null, null, null);
317 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800318 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800319 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700320 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800321 while (cursor.moveToNext()) {
322 final long accountId = cursor.getLong(0);
323 final String accountType = cursor.getString(1);
324 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700325
326 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Fred Quintana56285a62010-12-02 14:20:51 -0800327 Log.d(TAG, "deleting account " + accountName + " because type "
328 + accountType + " no longer has a registered authenticator");
329 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
330 accountDeleted = true;
331 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800332 accounts.userDataCache.remove(account);
333 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800334 } else {
335 ArrayList<String> accountNames = accountNamesByType.get(accountType);
336 if (accountNames == null) {
337 accountNames = new ArrayList<String>();
338 accountNamesByType.put(accountType, accountNames);
339 }
340 accountNames.add(accountName);
341 }
342 }
Andy McFadden2f362292012-01-20 14:43:38 -0800343 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800344 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800345 final String accountType = cur.getKey();
346 final ArrayList<String> accountNames = cur.getValue();
347 final Account[] accountsForType = new Account[accountNames.size()];
348 int i = 0;
349 for (String accountName : accountNames) {
350 accountsForType[i] = new Account(accountName, accountType);
351 ++i;
352 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800353 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800354 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800355 } finally {
356 cursor.close();
357 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800358 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800359 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800360 }
361 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700362 }
363
Amith Yamasani04e0d262012-02-14 11:50:53 -0800364 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700365 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800366 }
367
368 protected UserAccounts getUserAccounts(int userId) {
369 synchronized (mUsers) {
370 UserAccounts accounts = mUsers.get(userId);
371 if (accounts == null) {
372 accounts = initUser(userId);
373 mUsers.append(userId, accounts);
374 }
375 return accounts;
376 }
377 }
378
Amith Yamasani13593602012-03-22 16:16:17 -0700379 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700380 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700381 if (userId < 1) return;
382
383 UserAccounts accounts;
384 synchronized (mUsers) {
385 accounts = mUsers.get(userId);
386 mUsers.remove(userId);
387 }
388 if (accounts == null) {
389 File dbFile = new File(getDatabaseName(userId));
390 dbFile.delete();
391 return;
392 }
393
394 synchronized (accounts.cacheLock) {
395 accounts.openHelper.close();
396 File dbFile = new File(getDatabaseName(userId));
397 dbFile.delete();
398 }
399 }
400
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700401 @Override
402 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
403 validateAccountsAndPopulateCache(getUserAccounts(userId));
Fred Quintana60307342009-03-24 22:48:12 -0700404 }
405
Fred Quintanaa698f422009-04-08 19:14:54 -0700406 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800407 if (Log.isLoggable(TAG, Log.VERBOSE)) {
408 Log.v(TAG, "getPassword: " + account
409 + ", caller's uid " + Binder.getCallingUid()
410 + ", pid " + Binder.getCallingPid());
411 }
Fred Quintana382601f2010-03-25 12:25:10 -0700412 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700413 checkAuthenticateAccountsPermission(account);
414
Amith Yamasani04e0d262012-02-14 11:50:53 -0800415 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700416 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700417 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800418 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700419 } finally {
420 restoreCallingIdentity(identityToken);
421 }
422 }
423
Amith Yamasani04e0d262012-02-14 11:50:53 -0800424 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700425 if (account == null) {
426 return null;
427 }
428
Amith Yamasani04e0d262012-02-14 11:50:53 -0800429 synchronized (accounts.cacheLock) {
430 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800431 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
432 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
433 new String[]{account.name, account.type}, null, null, null);
434 try {
435 if (cursor.moveToNext()) {
436 return cursor.getString(0);
437 }
438 return null;
439 } finally {
440 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700441 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700442 }
443 }
444
445 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800446 if (Log.isLoggable(TAG, Log.VERBOSE)) {
447 Log.v(TAG, "getUserData: " + account
448 + ", key " + key
449 + ", caller's uid " + Binder.getCallingUid()
450 + ", pid " + Binder.getCallingPid());
451 }
Fred Quintana382601f2010-03-25 12:25:10 -0700452 if (account == null) throw new IllegalArgumentException("account is null");
453 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700454 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800455 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700456 long identityToken = clearCallingIdentity();
457 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800458 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700459 } finally {
460 restoreCallingIdentity(identityToken);
461 }
462 }
463
Fred Quintana97889762009-06-15 12:29:24 -0700464 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800465 if (Log.isLoggable(TAG, Log.VERBOSE)) {
466 Log.v(TAG, "getAuthenticatorTypes: "
467 + "caller's uid " + Binder.getCallingUid()
468 + ", pid " + Binder.getCallingPid());
469 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700470 final int userId = UserHandle.getCallingUserId();
471 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700472 try {
Fred Quintana97889762009-06-15 12:29:24 -0700473 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700474 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700475 AuthenticatorDescription[] types =
476 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700477 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700478 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700479 : authenticatorCollection) {
480 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700481 i++;
482 }
483 return types;
484 } finally {
485 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700486 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700487 }
488
Fred Quintanaa698f422009-04-08 19:14:54 -0700489 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800490 if (Log.isLoggable(TAG, Log.VERBOSE)) {
491 Log.v(TAG, "addAccount: " + account
492 + ", caller's uid " + Binder.getCallingUid()
493 + ", pid " + Binder.getCallingPid());
494 }
Fred Quintana382601f2010-03-25 12:25:10 -0700495 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700496 checkAuthenticateAccountsPermission(account);
497
Amith Yamasani04e0d262012-02-14 11:50:53 -0800498 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700499 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700500 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700501 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800502 return addAccountInternal(accounts, account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700503 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700504 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700505 }
506 }
507
Amith Yamasani04e0d262012-02-14 11:50:53 -0800508 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
509 Bundle extras) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700510 if (account == null) {
511 return false;
512 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800513 synchronized (accounts.cacheLock) {
514 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800515 db.beginTransaction();
516 try {
517 long numMatches = DatabaseUtils.longForQuery(db,
518 "select count(*) from " + TABLE_ACCOUNTS
519 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
520 new String[]{account.name, account.type});
521 if (numMatches > 0) {
522 Log.w(TAG, "insertAccountIntoDatabase: " + account
523 + ", skipping since the account already exists");
524 return false;
525 }
526 ContentValues values = new ContentValues();
527 values.put(ACCOUNTS_NAME, account.name);
528 values.put(ACCOUNTS_TYPE, account.type);
529 values.put(ACCOUNTS_PASSWORD, password);
530 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
531 if (accountId < 0) {
532 Log.w(TAG, "insertAccountIntoDatabase: " + account
533 + ", skipping the DB insert failed");
534 return false;
535 }
536 if (extras != null) {
537 for (String key : extras.keySet()) {
538 final String value = extras.getString(key);
539 if (insertExtraLocked(db, accountId, key, value) < 0) {
540 Log.w(TAG, "insertAccountIntoDatabase: " + account
541 + ", skipping since insertExtra failed for key " + key);
542 return false;
543 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700544 }
545 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800546 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800547 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800548 } finally {
549 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700550 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800551 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800552 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700553 }
554 }
555
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800556 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700557 ContentValues values = new ContentValues();
558 values.put(EXTRAS_KEY, key);
559 values.put(EXTRAS_ACCOUNTS_ID, accountId);
560 values.put(EXTRAS_VALUE, value);
561 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
562 }
563
Fred Quintana3084a6f2010-01-14 18:02:03 -0800564 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800565 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800566 if (Log.isLoggable(TAG, Log.VERBOSE)) {
567 Log.v(TAG, "hasFeatures: " + account
568 + ", response " + response
569 + ", features " + stringArrayToString(features)
570 + ", caller's uid " + Binder.getCallingUid()
571 + ", pid " + Binder.getCallingPid());
572 }
Fred Quintana382601f2010-03-25 12:25:10 -0700573 if (response == null) throw new IllegalArgumentException("response is null");
574 if (account == null) throw new IllegalArgumentException("account is null");
575 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800576 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800577 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800578 long identityToken = clearCallingIdentity();
579 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800580 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800581 } finally {
582 restoreCallingIdentity(identityToken);
583 }
584 }
585
586 private class TestFeaturesSession extends Session {
587 private final String[] mFeatures;
588 private final Account mAccount;
589
Amith Yamasani04e0d262012-02-14 11:50:53 -0800590 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800591 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800592 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800593 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800594 mFeatures = features;
595 mAccount = account;
596 }
597
598 public void run() throws RemoteException {
599 try {
600 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
601 } catch (RemoteException e) {
602 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
603 }
604 }
605
606 public void onResult(Bundle result) {
607 IAccountManagerResponse response = getResponseAndClose();
608 if (response != null) {
609 try {
610 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700611 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800612 return;
613 }
Fred Quintana56285a62010-12-02 14:20:51 -0800614 if (Log.isLoggable(TAG, Log.VERBOSE)) {
615 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
616 + response);
617 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800618 final Bundle newResult = new Bundle();
619 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
620 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
621 response.onResult(newResult);
622 } catch (RemoteException e) {
623 // if the caller is dead then there is no one to care about remote exceptions
624 if (Log.isLoggable(TAG, Log.VERBOSE)) {
625 Log.v(TAG, "failure while notifying response", e);
626 }
627 }
628 }
629 }
630
631 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800632 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800633 + ", " + mAccount
634 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
635 }
636 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800637
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700638 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800639 if (Log.isLoggable(TAG, Log.VERBOSE)) {
640 Log.v(TAG, "removeAccount: " + account
641 + ", response " + response
642 + ", caller's uid " + Binder.getCallingUid()
643 + ", pid " + Binder.getCallingPid());
644 }
Fred Quintana382601f2010-03-25 12:25:10 -0700645 if (response == null) throw new IllegalArgumentException("response is null");
646 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700647 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700648 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800649 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700650 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800651
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700652 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800653 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800654 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800655 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800656 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800657 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700658 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800659 }
660 }
661 }
662
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700663 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800664 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700665 } finally {
666 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700667 }
Fred Quintana60307342009-03-24 22:48:12 -0700668 }
669
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700670 private class RemoveAccountSession extends Session {
671 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800672 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
673 Account account) {
674 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800675 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700676 mAccount = account;
677 }
678
679 protected String toDebugString(long now) {
680 return super.toDebugString(now) + ", removeAccount"
681 + ", account " + mAccount;
682 }
683
684 public void run() throws RemoteException {
685 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
686 }
687
688 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700689 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
690 && !result.containsKey(AccountManager.KEY_INTENT)) {
691 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700692 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800693 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700694 }
695 IAccountManagerResponse response = getResponseAndClose();
696 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800697 if (Log.isLoggable(TAG, Log.VERBOSE)) {
698 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
699 + response);
700 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700701 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700702 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700703 try {
704 response.onResult(result2);
705 } catch (RemoteException e) {
706 // ignore
707 }
708 }
709 }
710 super.onResult(result);
711 }
712 }
713
Amith Yamasani04e0d262012-02-14 11:50:53 -0800714 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800715 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800716 removeAccountInternal(getUserAccountsForCaller(), account);
717 }
718
719 private void removeAccountInternal(UserAccounts accounts, Account account) {
720 synchronized (accounts.cacheLock) {
721 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800722 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
723 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800724 removeAccountFromCacheLocked(accounts, account);
725 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800726 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700727 }
728
Fred Quintanaa698f422009-04-08 19:14:54 -0700729 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800730 if (Log.isLoggable(TAG, Log.VERBOSE)) {
731 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
732 + ", caller's uid " + Binder.getCallingUid()
733 + ", pid " + Binder.getCallingPid());
734 }
Fred Quintana382601f2010-03-25 12:25:10 -0700735 if (accountType == null) throw new IllegalArgumentException("accountType is null");
736 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800737 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800738 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700739 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700740 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800741 synchronized (accounts.cacheLock) {
742 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800743 db.beginTransaction();
744 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800745 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800746 db.setTransactionSuccessful();
747 } finally {
748 db.endTransaction();
749 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700750 }
Fred Quintana60307342009-03-24 22:48:12 -0700751 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700752 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700753 }
754 }
755
Amith Yamasani04e0d262012-02-14 11:50:53 -0800756 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
757 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700758 if (authToken == null || accountType == null) {
759 return;
760 }
Fred Quintana33269202009-04-20 16:05:10 -0700761 Cursor cursor = db.rawQuery(
762 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
763 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
764 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
765 + " FROM " + TABLE_ACCOUNTS
766 + " JOIN " + TABLE_AUTHTOKENS
767 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
768 + " = " + AUTHTOKENS_ACCOUNTS_ID
769 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
770 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
771 new String[]{authToken, accountType});
772 try {
773 while (cursor.moveToNext()) {
774 long authTokenId = cursor.getLong(0);
775 String accountName = cursor.getString(1);
776 String authTokenType = cursor.getString(2);
777 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800778 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800779 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700780 }
Fred Quintana33269202009-04-20 16:05:10 -0700781 } finally {
782 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700783 }
784 }
785
Amith Yamasani04e0d262012-02-14 11:50:53 -0800786 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
787 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700788 if (account == null || type == null) {
789 return false;
790 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700791 cancelNotification(getSigninRequiredNotificationId(accounts, account),
792 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800793 synchronized (accounts.cacheLock) {
794 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800795 db.beginTransaction();
796 try {
797 long accountId = getAccountIdLocked(db, account);
798 if (accountId < 0) {
799 return false;
800 }
801 db.delete(TABLE_AUTHTOKENS,
802 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
803 new String[]{type});
804 ContentValues values = new ContentValues();
805 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
806 values.put(AUTHTOKENS_TYPE, type);
807 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
808 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
809 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800810 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800811 return true;
812 }
Fred Quintana33269202009-04-20 16:05:10 -0700813 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800814 } finally {
815 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -0700816 }
Fred Quintana60307342009-03-24 22:48:12 -0700817 }
818 }
819
Fred Quintanaa698f422009-04-08 19:14:54 -0700820 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800821 if (Log.isLoggable(TAG, Log.VERBOSE)) {
822 Log.v(TAG, "peekAuthToken: " + account
823 + ", authTokenType " + authTokenType
824 + ", caller's uid " + Binder.getCallingUid()
825 + ", pid " + Binder.getCallingPid());
826 }
Fred Quintana382601f2010-03-25 12:25:10 -0700827 if (account == null) throw new IllegalArgumentException("account is null");
828 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700829 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800830 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700831 long identityToken = clearCallingIdentity();
832 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800833 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700834 } finally {
835 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700836 }
Fred Quintana60307342009-03-24 22:48:12 -0700837 }
838
Fred Quintanaa698f422009-04-08 19:14:54 -0700839 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800840 if (Log.isLoggable(TAG, Log.VERBOSE)) {
841 Log.v(TAG, "setAuthToken: " + account
842 + ", authTokenType " + authTokenType
843 + ", caller's uid " + Binder.getCallingUid()
844 + ", pid " + Binder.getCallingPid());
845 }
Fred Quintana382601f2010-03-25 12:25:10 -0700846 if (account == null) throw new IllegalArgumentException("account is null");
847 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700848 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800849 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700850 long identityToken = clearCallingIdentity();
851 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800852 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700853 } finally {
854 restoreCallingIdentity(identityToken);
855 }
Fred Quintana60307342009-03-24 22:48:12 -0700856 }
857
Fred Quintanaa698f422009-04-08 19:14:54 -0700858 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -0800859 if (Log.isLoggable(TAG, Log.VERBOSE)) {
860 Log.v(TAG, "setAuthToken: " + account
861 + ", caller's uid " + Binder.getCallingUid()
862 + ", pid " + Binder.getCallingPid());
863 }
Fred Quintana382601f2010-03-25 12:25:10 -0700864 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700865 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800866 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700867 long identityToken = clearCallingIdentity();
868 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800869 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700870 } finally {
871 restoreCallingIdentity(identityToken);
872 }
Fred Quintana60307342009-03-24 22:48:12 -0700873 }
874
Amith Yamasani04e0d262012-02-14 11:50:53 -0800875 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700876 if (account == null) {
877 return;
878 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800879 synchronized (accounts.cacheLock) {
880 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800881 db.beginTransaction();
882 try {
883 final ContentValues values = new ContentValues();
884 values.put(ACCOUNTS_PASSWORD, password);
885 final long accountId = getAccountIdLocked(db, account);
886 if (accountId >= 0) {
887 final String[] argsAccountId = {String.valueOf(accountId)};
888 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
889 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800890 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800891 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -0800892 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800893 } finally {
894 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800895 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800896 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800897 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700898 }
899
Amith Yamasani04e0d262012-02-14 11:50:53 -0800900 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800901 Log.i(TAG, "the accounts changed, sending broadcast of "
902 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700903 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -0700904 }
905
Fred Quintanaa698f422009-04-08 19:14:54 -0700906 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800907 if (Log.isLoggable(TAG, Log.VERBOSE)) {
908 Log.v(TAG, "clearPassword: " + account
909 + ", caller's uid " + Binder.getCallingUid()
910 + ", pid " + Binder.getCallingPid());
911 }
Fred Quintana382601f2010-03-25 12:25:10 -0700912 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700913 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800914 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700915 long identityToken = clearCallingIdentity();
916 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800917 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700918 } finally {
919 restoreCallingIdentity(identityToken);
920 }
Fred Quintana60307342009-03-24 22:48:12 -0700921 }
922
Fred Quintanaa698f422009-04-08 19:14:54 -0700923 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -0800924 if (Log.isLoggable(TAG, Log.VERBOSE)) {
925 Log.v(TAG, "setUserData: " + account
926 + ", key " + key
927 + ", caller's uid " + Binder.getCallingUid()
928 + ", pid " + Binder.getCallingPid());
929 }
Fred Quintana382601f2010-03-25 12:25:10 -0700930 if (key == null) throw new IllegalArgumentException("key is null");
931 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700932 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800933 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700934 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700935 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800936 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700937 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700938 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700939 }
940 }
941
Amith Yamasani04e0d262012-02-14 11:50:53 -0800942 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
943 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700944 if (account == null || key == null) {
945 return;
946 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800947 synchronized (accounts.cacheLock) {
948 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800949 db.beginTransaction();
950 try {
951 long accountId = getAccountIdLocked(db, account);
952 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700953 return;
954 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800955 long extrasId = getExtrasIdLocked(db, accountId, key);
956 if (extrasId < 0 ) {
957 extrasId = insertExtraLocked(db, accountId, key, value);
958 if (extrasId < 0) {
959 return;
960 }
961 } else {
962 ContentValues values = new ContentValues();
963 values.put(EXTRAS_VALUE, value);
964 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
965 return;
966 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700967
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800968 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800969 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800970 db.setTransactionSuccessful();
971 } finally {
972 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700973 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700974 }
975 }
976
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700977 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -0800978 if (result == null) {
979 Log.e(TAG, "the result is unexpectedly null", new Exception());
980 }
981 if (Log.isLoggable(TAG, Log.VERBOSE)) {
982 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
983 + response);
984 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700985 try {
986 response.onResult(result);
987 } catch (RemoteException e) {
988 // if the caller is dead then there is no one to care about remote
989 // exceptions
990 if (Log.isLoggable(TAG, Log.VERBOSE)) {
991 Log.v(TAG, "failure while notifying response", e);
992 }
993 }
994 }
995
Fred Quintanad9640ec2012-05-23 12:37:00 -0700996 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
997 final String authTokenType)
998 throws RemoteException {
999 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001000 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1001
Fred Quintanad9640ec2012-05-23 12:37:00 -07001002 final int callingUid = getCallingUid();
1003 clearCallingIdentity();
1004 if (callingUid != android.os.Process.SYSTEM_UID) {
1005 throw new SecurityException("can only call from system");
1006 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001007 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001008 long identityToken = clearCallingIdentity();
1009 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001010 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001011 false /* stripAuthTokenFromResult */) {
1012 protected String toDebugString(long now) {
1013 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001014 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001015 + ", authTokenType " + authTokenType;
1016 }
1017
1018 public void run() throws RemoteException {
1019 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1020 }
1021
1022 public void onResult(Bundle result) {
1023 if (result != null) {
1024 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1025 Bundle bundle = new Bundle();
1026 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1027 super.onResult(bundle);
1028 return;
1029 } else {
1030 super.onResult(result);
1031 }
1032 }
1033 }.bind();
1034 } finally {
1035 restoreCallingIdentity(identityToken);
1036 }
1037 }
1038
Fred Quintanaa698f422009-04-08 19:14:54 -07001039 public void getAuthToken(IAccountManagerResponse response, final Account account,
1040 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001041 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001042 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1043 Log.v(TAG, "getAuthToken: " + account
1044 + ", response " + response
1045 + ", authTokenType " + authTokenType
1046 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1047 + ", expectActivityLaunch " + expectActivityLaunch
1048 + ", caller's uid " + Binder.getCallingUid()
1049 + ", pid " + Binder.getCallingPid());
1050 }
Fred Quintana382601f2010-03-25 12:25:10 -07001051 if (response == null) throw new IllegalArgumentException("response is null");
1052 if (account == null) throw new IllegalArgumentException("account is null");
1053 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001054 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001055 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001056 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1057 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1058 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001059 final boolean customTokens =
1060 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1061
1062 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001063 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001064 final boolean permissionGranted = customTokens ||
1065 permissionIsGranted(account, authTokenType, callerUid);
1066
Costin Manolachec6684f92011-01-14 11:25:39 -08001067 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1068 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001069 // let authenticator know the identity of the caller
1070 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1071 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1072 if (notifyOnAuthFailure) {
1073 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001074 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001075
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001076 long identityToken = clearCallingIdentity();
1077 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001078 // if the caller has permission, do the peek. otherwise go the more expensive
1079 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001080 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001081 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001082 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001083 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001084 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1085 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1086 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001087 onResult(response, result);
1088 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001089 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001090 }
1091
Amith Yamasani04e0d262012-02-14 11:50:53 -08001092 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001093 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001094 protected String toDebugString(long now) {
1095 if (loginOptions != null) loginOptions.keySet();
1096 return super.toDebugString(now) + ", getAuthToken"
1097 + ", " + account
1098 + ", authTokenType " + authTokenType
1099 + ", loginOptions " + loginOptions
1100 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1101 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001102
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001103 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001104 // If the caller doesn't have permission then create and return the
1105 // "grant permission" intent instead of the "getAuthToken" intent.
1106 if (!permissionGranted) {
1107 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1108 } else {
1109 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1110 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001111 }
1112
1113 public void onResult(Bundle result) {
1114 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001115 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001116 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1117 new AccountAuthenticatorResponse(this),
1118 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001119 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001120 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001121 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001122 onResult(bundle);
1123 return;
1124 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001125 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001126 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001127 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1128 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001129 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001130 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001131 "the type and name should not be empty");
1132 return;
1133 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001134 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001135 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001136 authTokenType, authToken);
1137 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001138 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001139
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001140 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001141 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001142 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001143 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001144 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001145 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001146 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001147 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001148 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001149 }.bind();
1150 } finally {
1151 restoreCallingIdentity(identityToken);
1152 }
Fred Quintana60307342009-03-24 22:48:12 -07001153 }
1154
Dianne Hackborn41203752012-08-31 14:05:51 -07001155 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1156 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001157 int uid = intent.getIntExtra(
1158 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1159 String authTokenType = intent.getStringExtra(
1160 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1161 String authTokenLabel = intent.getStringExtra(
1162 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1163
1164 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1165 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001166 final String titleAndSubtitle =
1167 mContext.getString(R.string.permission_request_notification_with_subtitle,
1168 account.name);
1169 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001170 String title = titleAndSubtitle;
1171 String subtitle = "";
1172 if (index > 0) {
1173 title = titleAndSubtitle.substring(0, index);
1174 subtitle = titleAndSubtitle.substring(index + 1);
1175 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001176 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001177 n.setLatestEventInfo(mContext, title, subtitle,
1178 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001179 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1180 installNotification(getCredentialPermissionNotificationId(
1181 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001182 }
1183
Costin Manolache5f383ad92010-12-02 16:44:46 -08001184 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1185 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001186
1187 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001188 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001189 // Since it was set in Eclair+ we can't change it without breaking apps using
1190 // the intent from a non-Activity context.
1191 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001192 intent.addCategory(
1193 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001194
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001195 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001196 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1197 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001198 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001199
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001200 return intent;
1201 }
1202
1203 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1204 int uid) {
1205 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001206 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001207 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001208 final Pair<Pair<Account, String>, Integer> key =
1209 new Pair<Pair<Account, String>, Integer>(
1210 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001211 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001212 if (id == null) {
1213 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001214 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001215 }
1216 }
1217 return id;
1218 }
1219
Amith Yamasani04e0d262012-02-14 11:50:53 -08001220 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001221 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001222 synchronized (accounts.signinRequiredNotificationIds) {
1223 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001224 if (id == null) {
1225 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001226 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001227 }
1228 }
1229 return id;
1230 }
1231
Fred Quintana33269202009-04-20 16:05:10 -07001232 public void addAcount(final IAccountManagerResponse response, final String accountType,
1233 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001234 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001235 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1236 Log.v(TAG, "addAccount: accountType " + accountType
1237 + ", response " + response
1238 + ", authTokenType " + authTokenType
1239 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1240 + ", expectActivityLaunch " + expectActivityLaunch
1241 + ", caller's uid " + Binder.getCallingUid()
1242 + ", pid " + Binder.getCallingPid());
1243 }
Fred Quintana382601f2010-03-25 12:25:10 -07001244 if (response == null) throw new IllegalArgumentException("response is null");
1245 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001246 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001247
Amith Yamasani04e0d262012-02-14 11:50:53 -08001248 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001249 final int pid = Binder.getCallingPid();
1250 final int uid = Binder.getCallingUid();
1251 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1252 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1253 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1254
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001255 long identityToken = clearCallingIdentity();
1256 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001257 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001258 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001259 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001260 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001261 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001262 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001263
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001264 protected String toDebugString(long now) {
1265 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001266 + ", accountType " + accountType
1267 + ", requiredFeatures "
1268 + (requiredFeatures != null
1269 ? TextUtils.join(",", requiredFeatures)
1270 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001271 }
1272 }.bind();
1273 } finally {
1274 restoreCallingIdentity(identityToken);
1275 }
Fred Quintana60307342009-03-24 22:48:12 -07001276 }
1277
Fred Quintanaa698f422009-04-08 19:14:54 -07001278 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001279 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001280 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1281 Log.v(TAG, "confirmCredentials: " + account
1282 + ", response " + response
1283 + ", expectActivityLaunch " + expectActivityLaunch
1284 + ", caller's uid " + Binder.getCallingUid()
1285 + ", pid " + Binder.getCallingPid());
1286 }
Fred Quintana382601f2010-03-25 12:25:10 -07001287 if (response == null) throw new IllegalArgumentException("response is null");
1288 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001289 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001290 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001291 long identityToken = clearCallingIdentity();
1292 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001293 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001294 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001295 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001296 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001297 }
1298 protected String toDebugString(long now) {
1299 return super.toDebugString(now) + ", confirmCredentials"
1300 + ", " + account;
1301 }
1302 }.bind();
1303 } finally {
1304 restoreCallingIdentity(identityToken);
1305 }
Fred Quintana60307342009-03-24 22:48:12 -07001306 }
1307
Fred Quintanaa698f422009-04-08 19:14:54 -07001308 public void updateCredentials(IAccountManagerResponse response, final Account account,
1309 final String authTokenType, final boolean expectActivityLaunch,
1310 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001311 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1312 Log.v(TAG, "updateCredentials: " + account
1313 + ", response " + response
1314 + ", authTokenType " + authTokenType
1315 + ", expectActivityLaunch " + expectActivityLaunch
1316 + ", caller's uid " + Binder.getCallingUid()
1317 + ", pid " + Binder.getCallingPid());
1318 }
Fred Quintana382601f2010-03-25 12:25:10 -07001319 if (response == null) throw new IllegalArgumentException("response is null");
1320 if (account == null) throw new IllegalArgumentException("account is null");
1321 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001322 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001323 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001324 long identityToken = clearCallingIdentity();
1325 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001326 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001327 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001328 public void run() throws RemoteException {
1329 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1330 }
1331 protected String toDebugString(long now) {
1332 if (loginOptions != null) loginOptions.keySet();
1333 return super.toDebugString(now) + ", updateCredentials"
1334 + ", " + account
1335 + ", authTokenType " + authTokenType
1336 + ", loginOptions " + loginOptions;
1337 }
1338 }.bind();
1339 } finally {
1340 restoreCallingIdentity(identityToken);
1341 }
Fred Quintana60307342009-03-24 22:48:12 -07001342 }
1343
Fred Quintanaa698f422009-04-08 19:14:54 -07001344 public void editProperties(IAccountManagerResponse response, final String accountType,
1345 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001346 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1347 Log.v(TAG, "editProperties: accountType " + accountType
1348 + ", response " + response
1349 + ", expectActivityLaunch " + expectActivityLaunch
1350 + ", caller's uid " + Binder.getCallingUid()
1351 + ", pid " + Binder.getCallingPid());
1352 }
Fred Quintana382601f2010-03-25 12:25:10 -07001353 if (response == null) throw new IllegalArgumentException("response is null");
1354 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001355 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001356 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001357 long identityToken = clearCallingIdentity();
1358 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001359 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001360 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001361 public void run() throws RemoteException {
1362 mAuthenticator.editProperties(this, mAccountType);
1363 }
1364 protected String toDebugString(long now) {
1365 return super.toDebugString(now) + ", editProperties"
1366 + ", accountType " + accountType;
1367 }
1368 }.bind();
1369 } finally {
1370 restoreCallingIdentity(identityToken);
1371 }
Fred Quintana60307342009-03-24 22:48:12 -07001372 }
1373
Fred Quintana33269202009-04-20 16:05:10 -07001374 private class GetAccountsByTypeAndFeatureSession extends Session {
1375 private final String[] mFeatures;
1376 private volatile Account[] mAccountsOfType = null;
1377 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1378 private volatile int mCurrentAccount = 0;
1379
Amith Yamasani04e0d262012-02-14 11:50:53 -08001380 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
1381 IAccountManagerResponse response, String type, String[] features) {
1382 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001383 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001384 mFeatures = features;
1385 }
1386
1387 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001388 synchronized (mAccounts.cacheLock) {
1389 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001390 }
Fred Quintana33269202009-04-20 16:05:10 -07001391 // check whether each account matches the requested features
1392 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1393 mCurrentAccount = 0;
1394
1395 checkAccount();
1396 }
1397
1398 public void checkAccount() {
1399 if (mCurrentAccount >= mAccountsOfType.length) {
1400 sendResult();
1401 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001402 }
Fred Quintana33269202009-04-20 16:05:10 -07001403
Fred Quintana29e94b82010-03-10 12:11:51 -08001404 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1405 if (accountAuthenticator == null) {
1406 // It is possible that the authenticator has died, which is indicated by
1407 // mAuthenticator being set to null. If this happens then just abort.
1408 // There is no need to send back a result or error in this case since
1409 // that already happened when mAuthenticator was cleared.
1410 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1411 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1412 + " connected to the authenticator, " + toDebugString());
1413 }
1414 return;
1415 }
Fred Quintana33269202009-04-20 16:05:10 -07001416 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001417 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001418 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001419 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001420 }
1421 }
1422
1423 public void onResult(Bundle result) {
1424 mNumResults++;
1425 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001426 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001427 return;
1428 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001429 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001430 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1431 }
1432 mCurrentAccount++;
1433 checkAccount();
1434 }
1435
1436 public void sendResult() {
1437 IAccountManagerResponse response = getResponseAndClose();
1438 if (response != null) {
1439 try {
1440 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1441 for (int i = 0; i < accounts.length; i++) {
1442 accounts[i] = mAccountsWithFeatures.get(i);
1443 }
Fred Quintana56285a62010-12-02 14:20:51 -08001444 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1445 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1446 + response);
1447 }
Fred Quintana33269202009-04-20 16:05:10 -07001448 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001449 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001450 response.onResult(result);
1451 } catch (RemoteException e) {
1452 // if the caller is dead then there is no one to care about remote exceptions
1453 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1454 Log.v(TAG, "failure while notifying response", e);
1455 }
1456 }
1457 }
1458 }
1459
1460
1461 protected String toDebugString(long now) {
1462 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1463 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1464 }
1465 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001466
Amith Yamasani04e0d262012-02-14 11:50:53 -08001467 /**
1468 * Returns the accounts for a specific user
1469 * @hide
1470 */
1471 public Account[] getAccounts(int userId) {
1472 checkReadAccountsPermission();
1473 UserAccounts accounts = getUserAccounts(userId);
1474 long identityToken = clearCallingIdentity();
1475 try {
1476 synchronized (accounts.cacheLock) {
1477 return getAccountsFromCacheLocked(accounts, null);
1478 }
1479 } finally {
1480 restoreCallingIdentity(identityToken);
1481 }
1482 }
1483
Amith Yamasanif29f2362012-04-05 18:29:52 -07001484 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001485 * Returns accounts for all running users.
1486 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001487 * @hide
1488 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001489 public AccountAndUser[] getRunningAccounts() {
1490 final int[] runningUserIds;
1491 try {
1492 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1493 } catch (RemoteException e) {
1494 // Running in system_server; should never happen
1495 throw new RuntimeException(e);
1496 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001497
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001498 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1499 synchronized (mUsers) {
1500 for (int userId : runningUserIds) {
1501 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001502 if (userAccounts == null) continue;
1503 synchronized (userAccounts.cacheLock) {
1504 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null);
1505 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001506 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001507 }
1508 }
1509 }
1510 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001511
1512 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1513 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001514 }
1515
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001516 public Account[] getAccounts(String type) {
Fred Quintana56285a62010-12-02 14:20:51 -08001517 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1518 Log.v(TAG, "getAccounts: accountType " + type
1519 + ", caller's uid " + Binder.getCallingUid()
1520 + ", pid " + Binder.getCallingPid());
1521 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001522 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001523 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001524 long identityToken = clearCallingIdentity();
1525 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001526 synchronized (accounts.cacheLock) {
1527 return getAccountsFromCacheLocked(accounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001528 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001529 } finally {
1530 restoreCallingIdentity(identityToken);
1531 }
1532 }
1533
1534 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001535 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001536 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1537 Log.v(TAG, "getAccounts: accountType " + type
1538 + ", response " + response
1539 + ", features " + stringArrayToString(features)
1540 + ", caller's uid " + Binder.getCallingUid()
1541 + ", pid " + Binder.getCallingPid());
1542 }
Fred Quintana382601f2010-03-25 12:25:10 -07001543 if (response == null) throw new IllegalArgumentException("response is null");
1544 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001545 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001546 UserAccounts userAccounts = getUserAccountsForCaller();
Fred Quintana33269202009-04-20 16:05:10 -07001547 long identityToken = clearCallingIdentity();
1548 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001549 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001550 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001551 synchronized (userAccounts.cacheLock) {
1552 accounts = getAccountsFromCacheLocked(userAccounts, type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001553 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001554 Bundle result = new Bundle();
1555 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1556 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001557 return;
1558 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001559 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001560 } finally {
1561 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001562 }
1563 }
1564
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001565 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001566 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001567 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001568 try {
1569 if (cursor.moveToNext()) {
1570 return cursor.getLong(0);
1571 }
1572 return -1;
1573 } finally {
1574 cursor.close();
1575 }
1576 }
1577
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001578 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001579 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1580 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1581 new String[]{key}, null, null, null);
1582 try {
1583 if (cursor.moveToNext()) {
1584 return cursor.getLong(0);
1585 }
1586 return -1;
1587 } finally {
1588 cursor.close();
1589 }
1590 }
1591
Fred Quintanaa698f422009-04-08 19:14:54 -07001592 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001593 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001594 IAccountManagerResponse mResponse;
1595 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001596 final boolean mExpectActivityLaunch;
1597 final long mCreationTime;
1598
Fred Quintana33269202009-04-20 16:05:10 -07001599 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001600 private int mNumRequestContinued = 0;
1601 private int mNumErrors = 0;
1602
Fred Quintana60307342009-03-24 22:48:12 -07001603
1604 IAccountAuthenticator mAuthenticator = null;
1605
Fred Quintana8570f742010-02-18 10:32:54 -08001606 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001607 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001608
Amith Yamasani04e0d262012-02-14 11:50:53 -08001609 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001610 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001611 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001612 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001613 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001614 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001615 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001616 mResponse = response;
1617 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001618 mExpectActivityLaunch = expectActivityLaunch;
1619 mCreationTime = SystemClock.elapsedRealtime();
1620 synchronized (mSessions) {
1621 mSessions.put(toString(), this);
1622 }
1623 try {
1624 response.asBinder().linkToDeath(this, 0 /* flags */);
1625 } catch (RemoteException e) {
1626 mResponse = null;
1627 binderDied();
1628 }
Fred Quintana60307342009-03-24 22:48:12 -07001629 }
1630
Fred Quintanaa698f422009-04-08 19:14:54 -07001631 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001632 if (mResponse == null) {
1633 // this session has already been closed
1634 return null;
1635 }
Fred Quintana60307342009-03-24 22:48:12 -07001636 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001637 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001638 return response;
1639 }
1640
Fred Quintanaa698f422009-04-08 19:14:54 -07001641 private void close() {
1642 synchronized (mSessions) {
1643 if (mSessions.remove(toString()) == null) {
1644 // the session was already closed, so bail out now
1645 return;
1646 }
1647 }
1648 if (mResponse != null) {
1649 // stop listening for response deaths
1650 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1651
1652 // clear this so that we don't accidentally send any further results
1653 mResponse = null;
1654 }
1655 cancelTimeout();
1656 unbind();
1657 }
1658
1659 public void binderDied() {
1660 mResponse = null;
1661 close();
1662 }
1663
1664 protected String toDebugString() {
1665 return toDebugString(SystemClock.elapsedRealtime());
1666 }
1667
1668 protected String toDebugString(long now) {
1669 return "Session: expectLaunch " + mExpectActivityLaunch
1670 + ", connected " + (mAuthenticator != null)
1671 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1672 + "/" + mNumErrors + ")"
1673 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1674 }
1675
Fred Quintana60307342009-03-24 22:48:12 -07001676 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001677 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1678 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1679 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001680 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001681 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001682 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001683 }
1684 }
1685
1686 private void unbind() {
1687 if (mAuthenticator != null) {
1688 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001689 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001690 }
1691 }
1692
1693 public void scheduleTimeout() {
1694 mMessageHandler.sendMessageDelayed(
1695 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1696 }
1697
1698 public void cancelTimeout() {
1699 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1700 }
1701
Fred Quintanab839afc2009-10-14 15:57:28 -07001702 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001703 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001704 try {
1705 run();
1706 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001707 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001708 "remote exception");
1709 }
Fred Quintana60307342009-03-24 22:48:12 -07001710 }
1711
Fred Quintanab839afc2009-10-14 15:57:28 -07001712 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001713 mAuthenticator = null;
1714 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001715 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001716 try {
1717 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1718 "disconnected");
1719 } catch (RemoteException e) {
1720 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1721 Log.v(TAG, "Session.onServiceDisconnected: "
1722 + "caught RemoteException while responding", e);
1723 }
1724 }
Fred Quintana60307342009-03-24 22:48:12 -07001725 }
1726 }
1727
Fred Quintanab839afc2009-10-14 15:57:28 -07001728 public abstract void run() throws RemoteException;
1729
Fred Quintana60307342009-03-24 22:48:12 -07001730 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001731 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001732 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001733 try {
1734 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
1735 "timeout");
1736 } catch (RemoteException e) {
1737 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1738 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
1739 e);
1740 }
1741 }
Fred Quintana60307342009-03-24 22:48:12 -07001742 }
1743 }
1744
Fred Quintanaa698f422009-04-08 19:14:54 -07001745 public void onResult(Bundle result) {
1746 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001747 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1748 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1749 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001750 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1751 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001752 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
1753 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001754 }
Fred Quintana60307342009-03-24 22:48:12 -07001755 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001756 IAccountManagerResponse response;
1757 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001758 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001759 response = mResponse;
1760 } else {
1761 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001762 }
Fred Quintana60307342009-03-24 22:48:12 -07001763 if (response != null) {
1764 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001765 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001766 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1767 Log.v(TAG, getClass().getSimpleName()
1768 + " calling onError() on response " + response);
1769 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001770 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001771 "null bundle returned");
1772 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001773 if (mStripAuthTokenFromResult) {
1774 result.remove(AccountManager.KEY_AUTHTOKEN);
1775 }
Fred Quintana56285a62010-12-02 14:20:51 -08001776 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1777 Log.v(TAG, getClass().getSimpleName()
1778 + " calling onResult() on response " + response);
1779 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001780 response.onResult(result);
1781 }
Fred Quintana60307342009-03-24 22:48:12 -07001782 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001783 // if the caller is dead then there is no one to care about remote exceptions
1784 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1785 Log.v(TAG, "failure while notifying response", e);
1786 }
Fred Quintana60307342009-03-24 22:48:12 -07001787 }
1788 }
1789 }
Fred Quintana60307342009-03-24 22:48:12 -07001790
Fred Quintanaa698f422009-04-08 19:14:54 -07001791 public void onRequestContinued() {
1792 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001793 }
1794
1795 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001796 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001797 IAccountManagerResponse response = getResponseAndClose();
1798 if (response != null) {
1799 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001800 Log.v(TAG, getClass().getSimpleName()
1801 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001802 }
1803 try {
1804 response.onError(errorCode, errorMessage);
1805 } catch (RemoteException e) {
1806 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1807 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1808 }
1809 }
1810 } else {
1811 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1812 Log.v(TAG, "Session.onError: already closed");
1813 }
Fred Quintana60307342009-03-24 22:48:12 -07001814 }
1815 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001816
1817 /**
1818 * find the component name for the authenticator and initiate a bind
1819 * if no authenticator or the bind fails then return false, otherwise return true
1820 */
1821 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001822 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1823 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1824 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07001825 if (authenticatorInfo == null) {
1826 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1827 Log.v(TAG, "there is no authenticator for " + authenticatorType
1828 + ", bailing out");
1829 }
1830 return false;
1831 }
1832
1833 Intent intent = new Intent();
1834 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1835 intent.setComponent(authenticatorInfo.componentName);
1836 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1837 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1838 }
Amith Yamasani34daa752012-03-19 16:14:23 -07001839 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE, mAccounts.userId)) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001840 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1841 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1842 }
1843 return false;
1844 }
1845
1846
1847 return true;
1848 }
Fred Quintana60307342009-03-24 22:48:12 -07001849 }
1850
1851 private class MessageHandler extends Handler {
1852 MessageHandler(Looper looper) {
1853 super(looper);
1854 }
Costin Manolache3348f142009-09-29 18:58:36 -07001855
Fred Quintana60307342009-03-24 22:48:12 -07001856 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001857 switch (msg.what) {
1858 case MESSAGE_TIMED_OUT:
1859 Session session = (Session)msg.obj;
1860 session.onTimedOut();
1861 break;
1862
1863 default:
1864 throw new IllegalStateException("unhandled message: " + msg.what);
1865 }
1866 }
1867 }
1868
Amith Yamasani04e0d262012-02-14 11:50:53 -08001869 private static String getDatabaseName(int userId) {
1870 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07001871 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001872 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07001873 // Migrate old file, if it exists, to the new location.
1874 // Make sure the new file doesn't already exist. A dummy file could have been
1875 // accidentally created in the old location, causing the new one to become corrupted
1876 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08001877 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07001878 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07001879 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07001880 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07001881 if (!userDir.exists()) {
1882 if (!userDir.mkdirs()) {
1883 throw new IllegalStateException("User dir cannot be created: " + userDir);
1884 }
1885 }
1886 if (!oldFile.renameTo(databaseFile)) {
1887 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
1888 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001889 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08001890 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001891 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08001892 }
1893
Amith Yamasani04e0d262012-02-14 11:50:53 -08001894 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001895
Amith Yamasani04e0d262012-02-14 11:50:53 -08001896 public DatabaseHelper(Context context, int userId) {
1897 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001898 }
1899
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001900 /**
1901 * This call needs to be made while the mCacheLock is held. The way to
1902 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
1903 * @param db The database.
1904 */
Fred Quintana60307342009-03-24 22:48:12 -07001905 @Override
1906 public void onCreate(SQLiteDatabase db) {
1907 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1908 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1909 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1910 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1911 + ACCOUNTS_PASSWORD + " TEXT, "
1912 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1913
1914 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1915 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1916 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1917 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1918 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1919 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1920
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001921 createGrantsTable(db);
1922
Fred Quintana60307342009-03-24 22:48:12 -07001923 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1924 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1925 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1926 + EXTRAS_KEY + " TEXT NOT NULL, "
1927 + EXTRAS_VALUE + " TEXT, "
1928 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1929
1930 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1931 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1932 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001933
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001934 createAccountsDeletionTrigger(db);
1935 }
1936
1937 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001938 db.execSQL(""
1939 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1940 + " BEGIN"
1941 + " DELETE FROM " + TABLE_AUTHTOKENS
1942 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1943 + " DELETE FROM " + TABLE_EXTRAS
1944 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001945 + " DELETE FROM " + TABLE_GRANTS
1946 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001947 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001948 }
1949
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001950 private void createGrantsTable(SQLiteDatabase db) {
1951 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1952 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1953 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1954 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1955 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1956 + "," + GRANTS_GRANTEE_UID + "))");
1957 }
1958
Fred Quintana60307342009-03-24 22:48:12 -07001959 @Override
1960 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001961 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001962
Fred Quintanaa698f422009-04-08 19:14:54 -07001963 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001964 // no longer need to do anything since the work is done
1965 // when upgrading from version 2
1966 oldVersion++;
1967 }
1968
1969 if (oldVersion == 2) {
1970 createGrantsTable(db);
1971 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1972 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001973 oldVersion++;
1974 }
Costin Manolache3348f142009-09-29 18:58:36 -07001975
1976 if (oldVersion == 3) {
1977 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1978 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1979 oldVersion++;
1980 }
Fred Quintana60307342009-03-24 22:48:12 -07001981 }
1982
1983 @Override
1984 public void onOpen(SQLiteDatabase db) {
1985 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1986 }
1987 }
1988
Fred Quintana60307342009-03-24 22:48:12 -07001989 public IBinder onBind(Intent intent) {
1990 return asBinder();
1991 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001992
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001993 /**
1994 * Searches array of arguments for the specified string
1995 * @param args array of argument strings
1996 * @param value value to search for
1997 * @return true if the value is contained in the array
1998 */
1999 private static boolean scanArgs(String[] args, String value) {
2000 if (args != null) {
2001 for (String arg : args) {
2002 if (value.equals(arg)) {
2003 return true;
2004 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002005 }
2006 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002007 return false;
2008 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002009
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002010 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002011 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2012 != PackageManager.PERMISSION_GRANTED) {
2013 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2014 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2015 + " without permission " + android.Manifest.permission.DUMP);
2016 return;
2017 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002018 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Kenny Root3abd75b2011-09-29 11:00:41 -07002019
Amith Yamasani04e0d262012-02-14 11:50:53 -08002020 fout = new IndentingPrintWriter(fout, " ");
2021 int size = mUsers.size();
2022 for (int i = 0; i < size; i++) {
2023 fout.println("User " + mUsers.keyAt(i) + ":");
2024 ((IndentingPrintWriter) fout).increaseIndent();
2025 dumpUser(mUsers.valueAt(i), fd, fout, args, isCheckinRequest);
2026 ((IndentingPrintWriter) fout).decreaseIndent();
2027 if (i < size - 1) {
2028 fout.println();
2029 }
2030 }
2031 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002032
Amith Yamasani04e0d262012-02-14 11:50:53 -08002033 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2034 String[] args, boolean isCheckinRequest) {
2035 synchronized (userAccounts.cacheLock) {
2036 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002037
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002038 if (isCheckinRequest) {
2039 // This is a checkin request. *Only* upload the account types and the count of each.
2040 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2041 null, null, ACCOUNTS_TYPE, null, null);
2042 try {
2043 while (cursor.moveToNext()) {
2044 // print type,count
2045 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2046 }
2047 } finally {
2048 if (cursor != null) {
2049 cursor.close();
2050 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002051 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002052 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002053 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002054 fout.println("Accounts: " + accounts.length);
2055 for (Account account : accounts) {
2056 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002057 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002058
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002059 fout.println();
2060 synchronized (mSessions) {
2061 final long now = SystemClock.elapsedRealtime();
2062 fout.println("Active Sessions: " + mSessions.size());
2063 for (Session session : mSessions.values()) {
2064 fout.println(" " + session.toDebugString(now));
2065 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002066 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002067
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002068 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002069 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002070 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002071 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002072 }
2073
Amith Yamasani04e0d262012-02-14 11:50:53 -08002074 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002075 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002076 long identityToken = clearCallingIdentity();
2077 try {
2078 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2079 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2080 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002081
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002082 if (intent.getComponent() != null &&
2083 GrantCredentialsPermissionActivity.class.getName().equals(
2084 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002085 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002086 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002087 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002088 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002089 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2090 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002091 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002092 final String notificationTitleFormat =
2093 mContext.getText(R.string.notification_title).toString();
2094 n.setLatestEventInfo(mContext,
2095 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002096 message, PendingIntent.getActivityAsUser(
2097 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002098 null, user));
2099 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002100 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002101 } finally {
2102 restoreCallingIdentity(identityToken);
2103 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002104 }
2105
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002106 protected void installNotification(final int notificationId, final Notification n,
2107 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002108 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002109 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002110 }
2111
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002112 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002113 long identityToken = clearCallingIdentity();
2114 try {
2115 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002116 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002117 } finally {
2118 restoreCallingIdentity(identityToken);
2119 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002120 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002121
Fred Quintanab38eb142010-02-24 13:40:54 -08002122 /** Succeeds if any of the specified permissions are granted. */
2123 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002124 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002125
2126 for (String perm : permissions) {
2127 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2128 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002129 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002130 }
2131 return;
2132 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002133 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002134
2135 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002136 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002137 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002138 }
2139
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002140 private boolean inSystemImage(int callingUid) {
2141 final int callingUserId = UserHandle.getUserId(callingUid);
2142
2143 final PackageManager userPackageManager;
2144 try {
2145 userPackageManager = mContext.createPackageContextAsUser(
2146 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2147 } catch (NameNotFoundException e) {
2148 return false;
2149 }
2150
2151 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002152 for (String name : packages) {
2153 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002154 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002155 if (packageInfo != null
2156 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002157 return true;
2158 }
2159 } catch (PackageManager.NameNotFoundException e) {
2160 return false;
2161 }
2162 }
2163 return false;
2164 }
2165
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002166 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002167 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002168 final boolean fromAuthenticator = account != null
2169 && hasAuthenticatorUid(account.type, callerUid);
2170 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002171 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002172 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2173 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002174 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002175 + ": is authenticator? " + fromAuthenticator
2176 + ", has explicit permission? " + hasExplicitGrants);
2177 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002178 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002179 }
2180
Fred Quintana1a231912009-10-15 11:31:30 -07002181 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002182 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002183 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002184 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002185 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002186 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002187 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002188 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002189 }
2190 }
2191 return false;
2192 }
2193
Amith Yamasani04e0d262012-02-14 11:50:53 -08002194 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2195 int callerUid) {
2196 if (callerUid == android.os.Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002197 return true;
2198 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002199 UserAccounts accounts = getUserAccountsForCaller();
2200 synchronized (accounts.cacheLock) {
2201 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2202 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002203 account.name, account.type};
2204 final boolean permissionGranted =
2205 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2206 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2207 // TODO: Skip this check when running automated tests. Replace this
2208 // with a more general solution.
2209 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002210 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002211 + " but ignoring since device is in test harness.");
2212 return true;
2213 }
2214 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002215 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002216 }
2217
2218 private void checkCallingUidAgainstAuthenticator(Account account) {
2219 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002220 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002221 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2222 Log.w(TAG, msg);
2223 throw new SecurityException(msg);
2224 }
2225 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2226 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2227 }
2228 }
2229
2230 private void checkAuthenticateAccountsPermission(Account account) {
2231 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2232 checkCallingUidAgainstAuthenticator(account);
2233 }
2234
2235 private void checkReadAccountsPermission() {
2236 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2237 }
2238
2239 private void checkManageAccountsPermission() {
2240 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2241 }
2242
Fred Quintanab38eb142010-02-24 13:40:54 -08002243 private void checkManageAccountsOrUseCredentialsPermissions() {
2244 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2245 Manifest.permission.USE_CREDENTIALS);
2246 }
2247
Fred Quintanad9640ec2012-05-23 12:37:00 -07002248 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2249 throws RemoteException {
2250 final int callingUid = getCallingUid();
2251
2252 if (callingUid != android.os.Process.SYSTEM_UID) {
2253 throw new SecurityException();
2254 }
2255
2256 if (value) {
2257 grantAppPermission(account, authTokenType, uid);
2258 } else {
2259 revokeAppPermission(account, authTokenType, uid);
2260 }
2261 }
2262
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002263 /**
2264 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2265 * <p>
2266 * Although this is public it can only be accessed via the AccountManagerService object
2267 * which is in the system. This means we don't need to protect it with permissions.
2268 * @hide
2269 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002270 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002271 if (account == null || authTokenType == null) {
2272 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002273 return;
2274 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002275 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002276 synchronized (accounts.cacheLock) {
2277 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002278 db.beginTransaction();
2279 try {
2280 long accountId = getAccountIdLocked(db, account);
2281 if (accountId >= 0) {
2282 ContentValues values = new ContentValues();
2283 values.put(GRANTS_ACCOUNTS_ID, accountId);
2284 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2285 values.put(GRANTS_GRANTEE_UID, uid);
2286 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2287 db.setTransactionSuccessful();
2288 }
2289 } finally {
2290 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002291 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002292 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2293 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002294 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002295 }
2296
2297 /**
2298 * Don't allow callers with the given uid permission to get credentials for
2299 * account/authTokenType.
2300 * <p>
2301 * Although this is public it can only be accessed via the AccountManagerService object
2302 * which is in the system. This means we don't need to protect it with permissions.
2303 * @hide
2304 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002305 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002306 if (account == null || authTokenType == null) {
2307 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002308 return;
2309 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002310 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002311 synchronized (accounts.cacheLock) {
2312 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002313 db.beginTransaction();
2314 try {
2315 long accountId = getAccountIdLocked(db, account);
2316 if (accountId >= 0) {
2317 db.delete(TABLE_GRANTS,
2318 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2319 + GRANTS_GRANTEE_UID + "=?",
2320 new String[]{String.valueOf(accountId), authTokenType,
2321 String.valueOf(uid)});
2322 db.setTransactionSuccessful();
2323 }
2324 } finally {
2325 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002326 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002327 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2328 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002329 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002330 }
Fred Quintana56285a62010-12-02 14:20:51 -08002331
2332 static final private String stringArrayToString(String[] value) {
2333 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2334 }
2335
Amith Yamasani04e0d262012-02-14 11:50:53 -08002336 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2337 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002338 if (oldAccountsForType != null) {
2339 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2340 for (Account curAccount : oldAccountsForType) {
2341 if (!curAccount.equals(account)) {
2342 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002343 }
2344 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002345 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002346 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002347 } else {
2348 Account[] newAccountsForType = new Account[newAccountsList.size()];
2349 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002350 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002351 }
Fred Quintana56285a62010-12-02 14:20:51 -08002352 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002353 accounts.userDataCache.remove(account);
2354 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002355 }
2356
2357 /**
2358 * This assumes that the caller has already checked that the account is not already present.
2359 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002360 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2361 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002362 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2363 Account[] newAccountsForType = new Account[oldLength + 1];
2364 if (accountsForType != null) {
2365 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002366 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002367 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002368 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002369 }
2370
Amith Yamasani04e0d262012-02-14 11:50:53 -08002371 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002372 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002373 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002374 if (accounts == null) {
2375 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002376 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002377 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002378 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002379 } else {
2380 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002381 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002382 totalLength += accounts.length;
2383 }
2384 if (totalLength == 0) {
2385 return EMPTY_ACCOUNT_ARRAY;
2386 }
2387 Account[] accounts = new Account[totalLength];
2388 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002389 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002390 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2391 accountsOfType.length);
2392 totalLength += accountsOfType.length;
2393 }
2394 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002395 }
2396 }
2397
Amith Yamasani04e0d262012-02-14 11:50:53 -08002398 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2399 Account account, String key, String value) {
2400 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002401 if (userDataForAccount == null) {
2402 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002403 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002404 }
2405 if (value == null) {
2406 userDataForAccount.remove(key);
2407 } else {
2408 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002409 }
2410 }
2411
Amith Yamasani04e0d262012-02-14 11:50:53 -08002412 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2413 Account account, String key, String value) {
2414 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002415 if (authTokensForAccount == null) {
2416 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002417 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002418 }
2419 if (value == null) {
2420 authTokensForAccount.remove(key);
2421 } else {
2422 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002423 }
2424 }
2425
Amith Yamasani04e0d262012-02-14 11:50:53 -08002426 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2427 String authTokenType) {
2428 synchronized (accounts.cacheLock) {
2429 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002430 if (authTokensForAccount == null) {
2431 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002432 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002433 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002434 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002435 }
2436 return authTokensForAccount.get(authTokenType);
2437 }
2438 }
2439
Amith Yamasani04e0d262012-02-14 11:50:53 -08002440 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2441 synchronized (accounts.cacheLock) {
2442 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002443 if (userDataForAccount == null) {
2444 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002445 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002446 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002447 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002448 }
2449 return userDataForAccount.get(key);
2450 }
2451 }
2452
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002453 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2454 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002455 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002456 Cursor cursor = db.query(TABLE_EXTRAS,
2457 COLUMNS_EXTRAS_KEY_AND_VALUE,
2458 SELECTION_USERDATA_BY_ACCOUNT,
2459 new String[]{account.name, account.type},
2460 null, null, null);
2461 try {
2462 while (cursor.moveToNext()) {
2463 final String tmpkey = cursor.getString(0);
2464 final String value = cursor.getString(1);
2465 userDataForAccount.put(tmpkey, value);
2466 }
2467 } finally {
2468 cursor.close();
2469 }
2470 return userDataForAccount;
2471 }
2472
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002473 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2474 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002475 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002476 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2477 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2478 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2479 new String[]{account.name, account.type},
2480 null, null, null);
2481 try {
2482 while (cursor.moveToNext()) {
2483 final String type = cursor.getString(0);
2484 final String authToken = cursor.getString(1);
2485 authTokensForAccount.put(type, authToken);
2486 }
2487 } finally {
2488 cursor.close();
2489 }
2490 return authTokensForAccount;
2491 }
Fred Quintana60307342009-03-24 22:48:12 -07002492}