blob: 0bdcc1df1c77abd34cc6917c42e0da5fc213c520 [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
Fred Quintanaa698f422009-04-08 19:14:54 -070019import android.content.BroadcastReceiver;
20import android.content.ContentValues;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070024import android.content.pm.PackageManager;
25import android.content.pm.RegisteredServicesCache;
Fred Quintana7be59642009-08-24 18:29:25 -070026import android.content.pm.PackageInfo;
27import android.content.pm.ApplicationInfo;
Fred Quintana60307342009-03-24 22:48:12 -070028import android.database.Cursor;
29import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070030import android.database.sqlite.SQLiteDatabase;
31import android.database.sqlite.SQLiteOpenHelper;
32import android.os.Bundle;
33import android.os.Handler;
34import android.os.HandlerThread;
35import android.os.IBinder;
36import android.os.Looper;
37import android.os.Message;
38import android.os.RemoteException;
39import android.os.SystemClock;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070040import android.os.Binder;
41import android.os.SystemProperties;
Fred Quintana60307342009-03-24 22:48:12 -070042import android.telephony.TelephonyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070043import android.text.TextUtils;
44import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070045import android.util.Pair;
Fred Quintana26fc5eb2009-04-09 15:05:50 -070046import android.app.PendingIntent;
47import android.app.NotificationManager;
48import android.app.Notification;
Fred Quintana7be59642009-08-24 18:29:25 -070049import android.app.Activity;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070050import android.Manifest;
Fred Quintana60307342009-03-24 22:48:12 -070051
Fred Quintanaa698f422009-04-08 19:14:54 -070052import java.io.FileDescriptor;
53import java.io.PrintWriter;
54import java.util.ArrayList;
55import java.util.Collection;
Fred Quintanaa698f422009-04-08 19:14:54 -070056import java.util.LinkedHashMap;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070057import java.util.HashMap;
58import java.util.concurrent.atomic.AtomicInteger;
59import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070060
Fred Quintana60307342009-03-24 22:48:12 -070061import com.android.internal.telephony.TelephonyIntents;
Fred Quintana26fc5eb2009-04-09 15:05:50 -070062import com.android.internal.R;
Fred Quintana60307342009-03-24 22:48:12 -070063
64/**
65 * A system service that provides account, password, and authtoken management for all
66 * accounts on the device. Some of these calls are implemented with the help of the corresponding
67 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
68 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
69 * AccountManager accountManager =
70 * (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE)
Fred Quintana33269202009-04-20 16:05:10 -070071 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070072 */
73public class AccountManagerService extends IAccountManager.Stub {
74 private static final String TAG = "AccountManagerService";
75
76 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
77 private static final String DATABASE_NAME = "accounts.db";
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070078 private static final int DATABASE_VERSION = 3;
Fred Quintana60307342009-03-24 22:48:12 -070079
80 private final Context mContext;
81
82 private HandlerThread mMessageThread;
83 private final MessageHandler mMessageHandler;
84
85 // Messages that can be sent on mHandler
86 private static final int MESSAGE_TIMED_OUT = 3;
87 private static final int MESSAGE_CONNECTED = 7;
88 private static final int MESSAGE_DISCONNECTED = 8;
89
90 private final AccountAuthenticatorCache mAuthenticatorCache;
91 private final AuthenticatorBindHelper mBindHelper;
Fred Quintana60307342009-03-24 22:48:12 -070092 private final DatabaseHelper mOpenHelper;
93 private final SimWatcher mSimWatcher;
94
95 private static final String TABLE_ACCOUNTS = "accounts";
96 private static final String ACCOUNTS_ID = "_id";
97 private static final String ACCOUNTS_NAME = "name";
98 private static final String ACCOUNTS_TYPE = "type";
99 private static final String ACCOUNTS_PASSWORD = "password";
100
101 private static final String TABLE_AUTHTOKENS = "authtokens";
102 private static final String AUTHTOKENS_ID = "_id";
103 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
104 private static final String AUTHTOKENS_TYPE = "type";
105 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
106
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700107 private static final String TABLE_GRANTS = "grants";
108 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
109 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
110 private static final String GRANTS_GRANTEE_UID = "uid";
111
Fred Quintana60307342009-03-24 22:48:12 -0700112 private static final String TABLE_EXTRAS = "extras";
113 private static final String EXTRAS_ID = "_id";
114 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
115 private static final String EXTRAS_KEY = "key";
116 private static final String EXTRAS_VALUE = "value";
117
118 private static final String TABLE_META = "meta";
119 private static final String META_KEY = "key";
120 private static final String META_VALUE = "value";
121
122 private static final String[] ACCOUNT_NAME_TYPE_PROJECTION =
123 new String[]{ACCOUNTS_ID, ACCOUNTS_NAME, ACCOUNTS_TYPE};
Fred Quintana7be59642009-08-24 18:29:25 -0700124 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700125
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700126 private static final String COUNT_OF_MATCHING_GRANTS = ""
127 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
128 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
129 + " AND " + GRANTS_GRANTEE_UID + "=?"
130 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
131 + " AND " + ACCOUNTS_NAME + "=?"
132 + " AND " + ACCOUNTS_TYPE + "=?";
133
Fred Quintanaa698f422009-04-08 19:14:54 -0700134 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700135 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
136
137 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
138 mCredentialsPermissionNotificationIds =
139 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
140 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
141 new HashMap<Account, Integer>();
142 private static AtomicReference<AccountManagerService> sThis =
143 new AtomicReference<AccountManagerService>();
144
145 private static final boolean isDebuggableMonkeyBuild =
146 SystemProperties.getBoolean("ro.monkey", false)
147 && SystemProperties.getBoolean("ro.debuggable", false);
Fred Quintana7be59642009-08-24 18:29:25 -0700148
149 static {
150 ACCOUNTS_CHANGED_INTENT = new Intent(Constants.LOGIN_ACCOUNTS_CHANGED_ACTION);
151 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
152 }
153
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700154 /**
155 * This should only be called by system code. One should only call this after the service
156 * has started.
157 * @return a reference to the AccountManagerService instance
158 * @hide
159 */
160 public static AccountManagerService getSingleton() {
161 return sThis.get();
162 }
Fred Quintana60307342009-03-24 22:48:12 -0700163
164 public class AuthTokenKey {
165 public final Account mAccount;
166 public final String mAuthTokenType;
167 private final int mHashCode;
168
169 public AuthTokenKey(Account account, String authTokenType) {
170 mAccount = account;
171 mAuthTokenType = authTokenType;
172 mHashCode = computeHashCode();
173 }
174
175 public boolean equals(Object o) {
176 if (o == this) {
177 return true;
178 }
179 if (!(o instanceof AuthTokenKey)) {
180 return false;
181 }
182 AuthTokenKey other = (AuthTokenKey)o;
183 if (!mAccount.equals(other.mAccount)) {
184 return false;
185 }
186 return (mAuthTokenType == null)
187 ? other.mAuthTokenType == null
188 : mAuthTokenType.equals(other.mAuthTokenType);
189 }
190
191 private int computeHashCode() {
192 int result = 17;
193 result = 31 * result + mAccount.hashCode();
194 result = 31 * result + ((mAuthTokenType == null) ? 0 : mAuthTokenType.hashCode());
195 return result;
196 }
197
198 public int hashCode() {
199 return mHashCode;
200 }
201 }
202
203 public AccountManagerService(Context context) {
204 mContext = context;
205
206 mOpenHelper = new DatabaseHelper(mContext);
207
208 mMessageThread = new HandlerThread("AccountManagerService");
209 mMessageThread.start();
210 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
211
212 mAuthenticatorCache = new AccountAuthenticatorCache(mContext);
213 mBindHelper = new AuthenticatorBindHelper(mContext, mAuthenticatorCache, mMessageHandler,
214 MESSAGE_CONNECTED, MESSAGE_DISCONNECTED);
215
216 mSimWatcher = new SimWatcher(mContext);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700217 sThis.set(this);
Fred Quintana60307342009-03-24 22:48:12 -0700218 }
219
Fred Quintanaa698f422009-04-08 19:14:54 -0700220 public String getPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700221 checkAuthenticateAccountsPermission(account);
222
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700223 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700224 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700225 return readPasswordFromDatabase(account);
226 } finally {
227 restoreCallingIdentity(identityToken);
228 }
229 }
230
231 private String readPasswordFromDatabase(Account account) {
232 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
233 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
234 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
235 new String[]{account.name, account.type}, null, null, null);
236 try {
237 if (cursor.moveToNext()) {
238 return cursor.getString(0);
239 }
240 return null;
241 } finally {
242 cursor.close();
243 }
244 }
245
246 public String getUserData(Account account, String key) {
247 checkAuthenticateAccountsPermission(account);
248 long identityToken = clearCallingIdentity();
249 try {
250 return readUserDataFromDatabase(account, key);
251 } finally {
252 restoreCallingIdentity(identityToken);
253 }
254 }
255
256 private String readUserDataFromDatabase(Account account, String key) {
257 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
258 db.beginTransaction();
259 try {
260 long accountId = getAccountId(db, account);
261 if (accountId < 0) {
262 return null;
263 }
264 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_VALUE},
265 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
266 new String[]{key}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700267 try {
268 if (cursor.moveToNext()) {
269 return cursor.getString(0);
270 }
271 return null;
272 } finally {
273 cursor.close();
274 }
275 } finally {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700276 db.endTransaction();
Fred Quintana60307342009-03-24 22:48:12 -0700277 }
278 }
279
Fred Quintana97889762009-06-15 12:29:24 -0700280 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700281 long identityToken = clearCallingIdentity();
282 try {
Fred Quintana97889762009-06-15 12:29:24 -0700283 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
284 authenticatorCollection = mAuthenticatorCache.getAllServices();
285 AuthenticatorDescription[] types =
286 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700287 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700288 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700289 : authenticatorCollection) {
290 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700291 i++;
292 }
293 return types;
294 } finally {
295 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700296 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700297 }
298
Fred Quintanaa698f422009-04-08 19:14:54 -0700299 public Account[] getAccountsByType(String accountType) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700300 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700301
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700302 final String selection = accountType == null ? null : (ACCOUNTS_TYPE + "=?");
303 final String[] selectionArgs = accountType == null ? null : new String[]{accountType};
304 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_NAME_TYPE_PROJECTION,
305 selection, selectionArgs, null, null, null);
306 try {
307 int i = 0;
308 Account[] accounts = new Account[cursor.getCount()];
309 while (cursor.moveToNext()) {
310 accounts[i] = new Account(cursor.getString(1), cursor.getString(2));
311 i++;
Fred Quintana60307342009-03-24 22:48:12 -0700312 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700313 return accounts;
Fred Quintana60307342009-03-24 22:48:12 -0700314 } finally {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700315 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700316 }
317 }
318
Fred Quintanaa698f422009-04-08 19:14:54 -0700319 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700320 checkAuthenticateAccountsPermission(account);
321
Fred Quintana60307342009-03-24 22:48:12 -0700322 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700323 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700324 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700325 return insertAccountIntoDatabase(account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700326 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700327 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700328 }
329 }
330
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700331 private boolean insertAccountIntoDatabase(Account account, String password, Bundle extras) {
332 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
333 db.beginTransaction();
334 try {
335 long numMatches = DatabaseUtils.longForQuery(db,
336 "select count(*) from " + TABLE_ACCOUNTS
337 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
338 new String[]{account.name, account.type});
339 if (numMatches > 0) {
340 return false;
341 }
342 ContentValues values = new ContentValues();
343 values.put(ACCOUNTS_NAME, account.name);
344 values.put(ACCOUNTS_TYPE, account.type);
345 values.put(ACCOUNTS_PASSWORD, password);
346 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
347 if (accountId < 0) {
348 return false;
349 }
350 if (extras != null) {
351 for (String key : extras.keySet()) {
352 final String value = extras.getString(key);
353 if (insertExtra(db, accountId, key, value) < 0) {
354 return false;
355 }
356 }
357 }
358 db.setTransactionSuccessful();
359 sendAccountsChangedBroadcast();
360 return true;
361 } finally {
362 db.endTransaction();
363 }
364 }
365
Fred Quintana60307342009-03-24 22:48:12 -0700366 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
367 ContentValues values = new ContentValues();
368 values.put(EXTRAS_KEY, key);
369 values.put(EXTRAS_ACCOUNTS_ID, accountId);
370 values.put(EXTRAS_VALUE, value);
371 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
372 }
373
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700374 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700375 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700376 long identityToken = clearCallingIdentity();
377 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700378 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700379 } finally {
380 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700381 }
Fred Quintana60307342009-03-24 22:48:12 -0700382 }
383
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700384 private class RemoveAccountSession extends Session {
385 final Account mAccount;
386 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
387 super(response, account.type, false /* expectActivityLaunch */);
388 mAccount = account;
389 }
390
391 protected String toDebugString(long now) {
392 return super.toDebugString(now) + ", removeAccount"
393 + ", account " + mAccount;
394 }
395
396 public void run() throws RemoteException {
397 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
398 }
399
400 public void onResult(Bundle result) {
401 if (result != null && result.containsKey(Constants.BOOLEAN_RESULT_KEY)
402 && !result.containsKey(Constants.INTENT_KEY)) {
403 final boolean removalAllowed = result.getBoolean(Constants.BOOLEAN_RESULT_KEY);
404 if (removalAllowed) {
405 removeAccount(mAccount);
406 }
407 IAccountManagerResponse response = getResponseAndClose();
408 if (response != null) {
409 Bundle result2 = new Bundle();
410 result2.putBoolean(Constants.BOOLEAN_RESULT_KEY, removalAllowed);
411 try {
412 response.onResult(result2);
413 } catch (RemoteException e) {
414 // ignore
415 }
416 }
417 }
418 super.onResult(result);
419 }
420 }
421
422 private void removeAccount(Account account) {
423 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
424 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
425 new String[]{account.name, account.type});
426 sendAccountsChangedBroadcast();
427 }
428
Fred Quintanaa698f422009-04-08 19:14:54 -0700429 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700430 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700431 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700432 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700433 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
434 db.beginTransaction();
435 try {
436 invalidateAuthToken(db, accountType, authToken);
437 db.setTransactionSuccessful();
438 } finally {
439 db.endTransaction();
440 }
Fred Quintana60307342009-03-24 22:48:12 -0700441 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700442 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700443 }
444 }
445
446 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700447 if (authToken == null || accountType == null) {
448 return;
449 }
Fred Quintana33269202009-04-20 16:05:10 -0700450 Cursor cursor = db.rawQuery(
451 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
452 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
453 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
454 + " FROM " + TABLE_ACCOUNTS
455 + " JOIN " + TABLE_AUTHTOKENS
456 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
457 + " = " + AUTHTOKENS_ACCOUNTS_ID
458 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
459 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
460 new String[]{authToken, accountType});
461 try {
462 while (cursor.moveToNext()) {
463 long authTokenId = cursor.getLong(0);
464 String accountName = cursor.getString(1);
465 String authTokenType = cursor.getString(2);
466 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700467 }
Fred Quintana33269202009-04-20 16:05:10 -0700468 } finally {
469 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700470 }
471 }
472
473 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
474 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
475 db.beginTransaction();
476 try {
Fred Quintana33269202009-04-20 16:05:10 -0700477 long accountId = getAccountId(db, account);
478 if (accountId < 0) {
479 return false;
480 }
481 db.delete(TABLE_AUTHTOKENS,
482 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
483 new String[]{type});
484 ContentValues values = new ContentValues();
485 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
486 values.put(AUTHTOKENS_TYPE, type);
487 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
488 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700489 db.setTransactionSuccessful();
490 return true;
491 }
492 return false;
493 } finally {
494 db.endTransaction();
495 }
496 }
497
Fred Quintana60307342009-03-24 22:48:12 -0700498 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
499 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
500 db.beginTransaction();
501 try {
502 long accountId = getAccountId(db, account);
503 if (accountId < 0) {
504 return null;
505 }
506 return getAuthToken(db, accountId, authTokenType);
507 } finally {
Fred Quintana60307342009-03-24 22:48:12 -0700508 db.endTransaction();
509 }
510 }
511
Fred Quintanaa698f422009-04-08 19:14:54 -0700512 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700513 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700514 long identityToken = clearCallingIdentity();
515 try {
Fred Quintana33269202009-04-20 16:05:10 -0700516 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700517 } finally {
518 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700519 }
Fred Quintana60307342009-03-24 22:48:12 -0700520 }
521
Fred Quintanaa698f422009-04-08 19:14:54 -0700522 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700523 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700524 long identityToken = clearCallingIdentity();
525 try {
526 cacheAuthToken(account, authTokenType, authToken);
527 } finally {
528 restoreCallingIdentity(identityToken);
529 }
Fred Quintana60307342009-03-24 22:48:12 -0700530 }
531
Fred Quintanaa698f422009-04-08 19:14:54 -0700532 public void setPassword(Account account, String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700533 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700534 long identityToken = clearCallingIdentity();
535 try {
536 ContentValues values = new ContentValues();
537 values.put(ACCOUNTS_PASSWORD, password);
538 mOpenHelper.getWritableDatabase().update(TABLE_ACCOUNTS, values,
539 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700540 new String[]{account.name, account.type});
Fred Quintana33269202009-04-20 16:05:10 -0700541 sendAccountsChangedBroadcast();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700542 } finally {
543 restoreCallingIdentity(identityToken);
544 }
Fred Quintana60307342009-03-24 22:48:12 -0700545 }
546
Fred Quintana33269202009-04-20 16:05:10 -0700547 private void sendAccountsChangedBroadcast() {
548 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
549 }
550
Fred Quintanaa698f422009-04-08 19:14:54 -0700551 public void clearPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700552 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700553 long identityToken = clearCallingIdentity();
554 try {
555 setPassword(account, null);
556 } finally {
557 restoreCallingIdentity(identityToken);
558 }
Fred Quintana60307342009-03-24 22:48:12 -0700559 }
560
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700561 private void sendResult(IAccountManagerResponse response, Bundle bundle) {
562 if (response != null) {
563 try {
564 response.onResult(bundle);
565 } catch (RemoteException e) {
566 // if the caller is dead then there is no one to care about remote
567 // exceptions
568 if (Log.isLoggable(TAG, Log.VERBOSE)) {
569 Log.v(TAG, "failure while notifying response", e);
570 }
571 }
572 }
573 }
574
Fred Quintanaa698f422009-04-08 19:14:54 -0700575 public void setUserData(Account account, String key, String value) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700576 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700577 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700578 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700579 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700580 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700581 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700582 }
583 }
584
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700585 private void writeUserdataIntoDatabase(Account account, String key, String value) {
586 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
587 db.beginTransaction();
588 try {
589 long accountId = getAccountId(db, account);
590 if (accountId < 0) {
591 return;
592 }
593 long extrasId = getExtrasId(db, accountId, key);
594 if (extrasId < 0 ) {
595 extrasId = insertExtra(db, accountId, key, value);
596 if (extrasId < 0) {
597 return;
598 }
599 } else {
600 ContentValues values = new ContentValues();
601 values.put(EXTRAS_VALUE, value);
602 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
603 return;
604 }
605
606 }
607 db.setTransactionSuccessful();
608 } finally {
609 db.endTransaction();
610 }
611 }
612
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700613 private void onResult(IAccountManagerResponse response, Bundle result) {
614 try {
615 response.onResult(result);
616 } catch (RemoteException e) {
617 // if the caller is dead then there is no one to care about remote
618 // exceptions
619 if (Log.isLoggable(TAG, Log.VERBOSE)) {
620 Log.v(TAG, "failure while notifying response", e);
621 }
622 }
623 }
624
Fred Quintanaa698f422009-04-08 19:14:54 -0700625 public void getAuthToken(IAccountManagerResponse response, final Account account,
626 final String authTokenType, final boolean notifyOnAuthFailure,
627 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700628 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
629 final int callerUid = Binder.getCallingUid();
630 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
631
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700632 long identityToken = clearCallingIdentity();
633 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700634 // if the caller has permission, do the peek. otherwise go the more expensive
635 // route of starting a Session
636 if (permissionGranted) {
637 String authToken = readAuthTokenFromDatabase(account, authTokenType);
638 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700639 Bundle result = new Bundle();
640 result.putString(Constants.AUTHTOKEN_KEY, authToken);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700641 result.putString(Constants.ACCOUNT_NAME_KEY, account.name);
642 result.putString(Constants.ACCOUNT_TYPE_KEY, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700643 onResult(response, result);
644 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700645 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700646 }
647
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700648 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700649 protected String toDebugString(long now) {
650 if (loginOptions != null) loginOptions.keySet();
651 return super.toDebugString(now) + ", getAuthToken"
652 + ", " + account
653 + ", authTokenType " + authTokenType
654 + ", loginOptions " + loginOptions
655 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
656 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700657
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700658 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700659 // If the caller doesn't have permission then create and return the
660 // "grant permission" intent instead of the "getAuthToken" intent.
661 if (!permissionGranted) {
662 mAuthenticator.getAuthTokenLabel(this, authTokenType);
663 } else {
664 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
665 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700666 }
667
668 public void onResult(Bundle result) {
669 if (result != null) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700670 if (result.containsKey(Constants.AUTH_TOKEN_LABEL_KEY)) {
671 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
672 new AccountAuthenticatorResponse(this),
673 authTokenType,
674 result.getString(Constants.AUTH_TOKEN_LABEL_KEY));
675 Bundle bundle = new Bundle();
676 bundle.putParcelable(Constants.INTENT_KEY, intent);
677 onResult(bundle);
678 return;
679 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700680 String authToken = result.getString(Constants.AUTHTOKEN_KEY);
681 if (authToken != null) {
682 String name = result.getString(Constants.ACCOUNT_NAME_KEY);
683 String type = result.getString(Constants.ACCOUNT_TYPE_KEY);
684 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
685 onError(Constants.ERROR_CODE_INVALID_RESPONSE,
686 "the type and name should not be empty");
687 return;
688 }
689 cacheAuthToken(new Account(name, type), authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700690 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700691
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700692 Intent intent = result.getParcelable(Constants.INTENT_KEY);
693 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700694 doNotification(
695 account, result.getString(Constants.AUTH_FAILED_MESSAGE_KEY),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700696 intent);
697 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700698 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700699 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700700 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700701 }.bind();
702 } finally {
703 restoreCallingIdentity(identityToken);
704 }
Fred Quintana60307342009-03-24 22:48:12 -0700705 }
706
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700707 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
708 int uid = intent.getIntExtra(
709 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
710 String authTokenType = intent.getStringExtra(
711 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
712 String authTokenLabel = intent.getStringExtra(
713 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
714
715 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
716 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700717 final String titleAndSubtitle =
718 mContext.getString(R.string.permission_request_notification_with_subtitle,
719 account.name);
720 final int index = titleAndSubtitle.indexOf('\n');
721 final String title = titleAndSubtitle.substring(0, index);
722 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700723 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700724 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700725 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
726 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
727 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
728 }
729
730 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
731 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
732 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
733 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700734 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700735 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700736 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700737 }
738
739 final Context authContext;
740 try {
741 authContext = mContext.createPackageContext(
742 serviceInfo.type.packageName, 0);
743 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700744 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700745 }
746
747 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
748 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
749 intent.addCategory(
750 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
751 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
752 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
753 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
754 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
755 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
756 authContext.getString(serviceInfo.type.labelId));
757 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
758 mContext.getPackageManager().getPackagesForUid(uid));
759 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
760 return intent;
761 }
762
763 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
764 int uid) {
765 Integer id;
766 synchronized(mCredentialsPermissionNotificationIds) {
767 final Pair<Pair<Account, String>, Integer> key =
768 new Pair<Pair<Account, String>, Integer>(
769 new Pair<Account, String>(account, authTokenType), uid);
770 id = mCredentialsPermissionNotificationIds.get(key);
771 if (id == null) {
772 id = mNotificationIds.incrementAndGet();
773 mCredentialsPermissionNotificationIds.put(key, id);
774 }
775 }
776 return id;
777 }
778
779 private Integer getSigninRequiredNotificationId(Account account) {
780 Integer id;
781 synchronized(mSigninRequiredNotificationIds) {
782 id = mSigninRequiredNotificationIds.get(account);
783 if (id == null) {
784 id = mNotificationIds.incrementAndGet();
785 mSigninRequiredNotificationIds.put(account, id);
786 }
787 }
788 return id;
789 }
790
Fred Quintanaa698f422009-04-08 19:14:54 -0700791
Fred Quintana33269202009-04-20 16:05:10 -0700792 public void addAcount(final IAccountManagerResponse response, final String accountType,
793 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700794 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700795 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700796 long identityToken = clearCallingIdentity();
797 try {
798 new Session(response, accountType, expectActivityLaunch) {
799 public void run() throws RemoteException {
Fred Quintana33269202009-04-20 16:05:10 -0700800 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
801 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700802 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700803
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700804 protected String toDebugString(long now) {
805 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -0700806 + ", accountType " + accountType
807 + ", requiredFeatures "
808 + (requiredFeatures != null
809 ? TextUtils.join(",", requiredFeatures)
810 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700811 }
812 }.bind();
813 } finally {
814 restoreCallingIdentity(identityToken);
815 }
Fred Quintana60307342009-03-24 22:48:12 -0700816 }
817
Fred Quintanaa698f422009-04-08 19:14:54 -0700818 public void confirmCredentials(IAccountManagerResponse response,
819 final Account account, final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700820 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700821 long identityToken = clearCallingIdentity();
822 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700823 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700824 public void run() throws RemoteException {
825 mAuthenticator.confirmCredentials(this, account);
826 }
827 protected String toDebugString(long now) {
828 return super.toDebugString(now) + ", confirmCredentials"
829 + ", " + account;
830 }
831 }.bind();
832 } finally {
833 restoreCallingIdentity(identityToken);
834 }
Fred Quintana60307342009-03-24 22:48:12 -0700835 }
836
Fred Quintanaa698f422009-04-08 19:14:54 -0700837 public void confirmPassword(IAccountManagerResponse response, final Account account,
838 final String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700839 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700840 long identityToken = clearCallingIdentity();
841 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700842 new Session(response, account.type, false /* expectActivityLaunch */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700843 public void run() throws RemoteException {
844 mAuthenticator.confirmPassword(this, account, password);
845 }
846 protected String toDebugString(long now) {
847 return super.toDebugString(now) + ", confirmPassword"
848 + ", " + account;
849 }
850 }.bind();
851 } finally {
852 restoreCallingIdentity(identityToken);
853 }
Fred Quintana60307342009-03-24 22:48:12 -0700854 }
855
Fred Quintanaa698f422009-04-08 19:14:54 -0700856 public void updateCredentials(IAccountManagerResponse response, final Account account,
857 final String authTokenType, final boolean expectActivityLaunch,
858 final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700859 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700860 long identityToken = clearCallingIdentity();
861 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700862 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700863 public void run() throws RemoteException {
864 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
865 }
866 protected String toDebugString(long now) {
867 if (loginOptions != null) loginOptions.keySet();
868 return super.toDebugString(now) + ", updateCredentials"
869 + ", " + account
870 + ", authTokenType " + authTokenType
871 + ", loginOptions " + loginOptions;
872 }
873 }.bind();
874 } finally {
875 restoreCallingIdentity(identityToken);
876 }
Fred Quintana60307342009-03-24 22:48:12 -0700877 }
878
Fred Quintanaa698f422009-04-08 19:14:54 -0700879 public void editProperties(IAccountManagerResponse response, final String accountType,
880 final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700881 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700882 long identityToken = clearCallingIdentity();
883 try {
884 new Session(response, accountType, expectActivityLaunch) {
885 public void run() throws RemoteException {
886 mAuthenticator.editProperties(this, mAccountType);
887 }
888 protected String toDebugString(long now) {
889 return super.toDebugString(now) + ", editProperties"
890 + ", accountType " + accountType;
891 }
892 }.bind();
893 } finally {
894 restoreCallingIdentity(identityToken);
895 }
Fred Quintana60307342009-03-24 22:48:12 -0700896 }
897
Fred Quintana33269202009-04-20 16:05:10 -0700898 private class GetAccountsByTypeAndFeatureSession extends Session {
899 private final String[] mFeatures;
900 private volatile Account[] mAccountsOfType = null;
901 private volatile ArrayList<Account> mAccountsWithFeatures = null;
902 private volatile int mCurrentAccount = 0;
903
904 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
905 String type, String[] features) {
906 super(response, type, false /* expectActivityLaunch */);
907 mFeatures = features;
908 }
909
910 public void run() throws RemoteException {
911 mAccountsOfType = getAccountsByType(mAccountType);
912 // check whether each account matches the requested features
913 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
914 mCurrentAccount = 0;
915
916 checkAccount();
917 }
918
919 public void checkAccount() {
920 if (mCurrentAccount >= mAccountsOfType.length) {
921 sendResult();
922 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700923 }
Fred Quintana33269202009-04-20 16:05:10 -0700924
925 try {
926 mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
927 } catch (RemoteException e) {
928 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
929 }
930 }
931
932 public void onResult(Bundle result) {
933 mNumResults++;
934 if (result == null) {
935 onError(Constants.ERROR_CODE_INVALID_RESPONSE, "null bundle");
936 return;
937 }
938 if (result.getBoolean(Constants.BOOLEAN_RESULT_KEY, false)) {
939 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
940 }
941 mCurrentAccount++;
942 checkAccount();
943 }
944
945 public void sendResult() {
946 IAccountManagerResponse response = getResponseAndClose();
947 if (response != null) {
948 try {
949 Account[] accounts = new Account[mAccountsWithFeatures.size()];
950 for (int i = 0; i < accounts.length; i++) {
951 accounts[i] = mAccountsWithFeatures.get(i);
952 }
953 Bundle result = new Bundle();
954 result.putParcelableArray(Constants.ACCOUNTS_KEY, accounts);
955 response.onResult(result);
956 } catch (RemoteException e) {
957 // if the caller is dead then there is no one to care about remote exceptions
958 if (Log.isLoggable(TAG, Log.VERBOSE)) {
959 Log.v(TAG, "failure while notifying response", e);
960 }
961 }
962 }
963 }
964
965
966 protected String toDebugString(long now) {
967 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
968 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
969 }
970 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700971
972 public Account[] getAccounts(String type) {
973 checkReadAccountsPermission();
974 long identityToken = clearCallingIdentity();
975 try {
976 return getAccountsByType(type);
977 } finally {
978 restoreCallingIdentity(identityToken);
979 }
980 }
981
982 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -0700983 String type, String[] features) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700984 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700985 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -0700986 if (response != null) {
987 try {
988 response.onError(Constants.ERROR_CODE_BAD_ARGUMENTS, "type is null");
989 } catch (RemoteException e) {
990 // ignore this
991 }
992 }
993 return;
994 }
995 long identityToken = clearCallingIdentity();
996 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700997 if (features == null || features.length == 0) {
998 getAccountsByType(type);
999 return;
1000 }
Fred Quintana33269202009-04-20 16:05:10 -07001001 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1002 } finally {
1003 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001004 }
1005 }
1006
Fred Quintana33269202009-04-20 16:05:10 -07001007 private boolean cacheAuthToken(Account account, String authTokenType, String authToken) {
1008 return saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana60307342009-03-24 22:48:12 -07001009 }
1010
1011 private long getAccountId(SQLiteDatabase db, Account account) {
1012 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001013 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001014 try {
1015 if (cursor.moveToNext()) {
1016 return cursor.getLong(0);
1017 }
1018 return -1;
1019 } finally {
1020 cursor.close();
1021 }
1022 }
1023
1024 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1025 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1026 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1027 new String[]{key}, null, null, null);
1028 try {
1029 if (cursor.moveToNext()) {
1030 return cursor.getLong(0);
1031 }
1032 return -1;
1033 } finally {
1034 cursor.close();
1035 }
1036 }
1037
1038 private String getAuthToken(SQLiteDatabase db, long accountId, String authTokenType) {
1039 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
1040 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1041 new String[]{authTokenType},
1042 null, null, null);
1043 try {
1044 if (cursor.moveToNext()) {
1045 return cursor.getString(0);
1046 }
1047 return null;
1048 } finally {
1049 cursor.close();
1050 }
1051 }
1052
Fred Quintanaa698f422009-04-08 19:14:54 -07001053 private abstract class Session extends IAccountAuthenticatorResponse.Stub
1054 implements AuthenticatorBindHelper.Callback, IBinder.DeathRecipient {
Fred Quintana60307342009-03-24 22:48:12 -07001055 IAccountManagerResponse mResponse;
1056 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001057 final boolean mExpectActivityLaunch;
1058 final long mCreationTime;
1059
Fred Quintana33269202009-04-20 16:05:10 -07001060 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001061 private int mNumRequestContinued = 0;
1062 private int mNumErrors = 0;
1063
Fred Quintana60307342009-03-24 22:48:12 -07001064
1065 IAccountAuthenticator mAuthenticator = null;
1066
Fred Quintanaa698f422009-04-08 19:14:54 -07001067 public Session(IAccountManagerResponse response, String accountType,
1068 boolean expectActivityLaunch) {
Fred Quintana60307342009-03-24 22:48:12 -07001069 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001070 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001071 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana60307342009-03-24 22:48:12 -07001072 mResponse = response;
1073 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001074 mExpectActivityLaunch = expectActivityLaunch;
1075 mCreationTime = SystemClock.elapsedRealtime();
1076 synchronized (mSessions) {
1077 mSessions.put(toString(), this);
1078 }
1079 try {
1080 response.asBinder().linkToDeath(this, 0 /* flags */);
1081 } catch (RemoteException e) {
1082 mResponse = null;
1083 binderDied();
1084 }
Fred Quintana60307342009-03-24 22:48:12 -07001085 }
1086
Fred Quintanaa698f422009-04-08 19:14:54 -07001087 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001088 if (mResponse == null) {
1089 // this session has already been closed
1090 return null;
1091 }
Fred Quintana60307342009-03-24 22:48:12 -07001092 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001093 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001094 return response;
1095 }
1096
Fred Quintanaa698f422009-04-08 19:14:54 -07001097 private void close() {
1098 synchronized (mSessions) {
1099 if (mSessions.remove(toString()) == null) {
1100 // the session was already closed, so bail out now
1101 return;
1102 }
1103 }
1104 if (mResponse != null) {
1105 // stop listening for response deaths
1106 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1107
1108 // clear this so that we don't accidentally send any further results
1109 mResponse = null;
1110 }
1111 cancelTimeout();
1112 unbind();
1113 }
1114
1115 public void binderDied() {
1116 mResponse = null;
1117 close();
1118 }
1119
1120 protected String toDebugString() {
1121 return toDebugString(SystemClock.elapsedRealtime());
1122 }
1123
1124 protected String toDebugString(long now) {
1125 return "Session: expectLaunch " + mExpectActivityLaunch
1126 + ", connected " + (mAuthenticator != null)
1127 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1128 + "/" + mNumErrors + ")"
1129 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1130 }
1131
Fred Quintana60307342009-03-24 22:48:12 -07001132 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001133 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1134 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1135 }
Fred Quintana60307342009-03-24 22:48:12 -07001136 if (!mBindHelper.bind(mAccountType, this)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001137 Log.d(TAG, "bind attempt failed for " + toDebugString());
1138 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001139 }
1140 }
1141
1142 private void unbind() {
1143 if (mAuthenticator != null) {
1144 mAuthenticator = null;
1145 mBindHelper.unbind(this);
1146 }
1147 }
1148
1149 public void scheduleTimeout() {
1150 mMessageHandler.sendMessageDelayed(
1151 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1152 }
1153
1154 public void cancelTimeout() {
1155 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1156 }
1157
1158 public void onConnected(IBinder service) {
1159 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001160 try {
1161 run();
1162 } catch (RemoteException e) {
1163 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1164 "remote exception");
1165 }
Fred Quintana60307342009-03-24 22:48:12 -07001166 }
1167
Fred Quintanaa698f422009-04-08 19:14:54 -07001168 public abstract void run() throws RemoteException;
1169
Fred Quintana60307342009-03-24 22:48:12 -07001170 public void onDisconnected() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001171 mAuthenticator = null;
1172 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001173 if (response != null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001174 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1175 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001176 }
1177 }
1178
1179 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001180 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001181 if (response != null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001182 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1183 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001184 }
1185 }
1186
Fred Quintanaa698f422009-04-08 19:14:54 -07001187 public void onResult(Bundle result) {
1188 mNumResults++;
1189 if (result != null && !TextUtils.isEmpty(result.getString(Constants.AUTHTOKEN_KEY))) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001190 String accountName = result.getString(Constants.ACCOUNT_NAME_KEY);
1191 String accountType = result.getString(Constants.ACCOUNT_TYPE_KEY);
1192 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1193 Account account = new Account(accountName, accountType);
1194 cancelNotification(getSigninRequiredNotificationId(account));
1195 }
Fred Quintana60307342009-03-24 22:48:12 -07001196 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001197 IAccountManagerResponse response;
1198 if (mExpectActivityLaunch && result != null
1199 && result.containsKey(Constants.INTENT_KEY)) {
1200 response = mResponse;
1201 } else {
1202 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001203 }
Fred Quintana60307342009-03-24 22:48:12 -07001204 if (response != null) {
1205 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001206 if (result == null) {
1207 response.onError(Constants.ERROR_CODE_INVALID_RESPONSE,
1208 "null bundle returned");
1209 } else {
1210 response.onResult(result);
1211 }
Fred Quintana60307342009-03-24 22:48:12 -07001212 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001213 // if the caller is dead then there is no one to care about remote exceptions
1214 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1215 Log.v(TAG, "failure while notifying response", e);
1216 }
Fred Quintana60307342009-03-24 22:48:12 -07001217 }
1218 }
1219 }
Fred Quintana60307342009-03-24 22:48:12 -07001220
Fred Quintanaa698f422009-04-08 19:14:54 -07001221 public void onRequestContinued() {
1222 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001223 }
1224
1225 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001226 mNumErrors++;
1227 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1228 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001229 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001230 IAccountManagerResponse response = getResponseAndClose();
1231 if (response != null) {
1232 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1233 Log.v(TAG, "Session.onError: responding");
1234 }
1235 try {
1236 response.onError(errorCode, errorMessage);
1237 } catch (RemoteException e) {
1238 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1239 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1240 }
1241 }
1242 } else {
1243 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1244 Log.v(TAG, "Session.onError: already closed");
1245 }
Fred Quintana60307342009-03-24 22:48:12 -07001246 }
1247 }
1248 }
1249
1250 private class MessageHandler extends Handler {
1251 MessageHandler(Looper looper) {
1252 super(looper);
1253 }
1254
1255 public void handleMessage(Message msg) {
1256 if (mBindHelper.handleMessage(msg)) {
1257 return;
1258 }
1259 switch (msg.what) {
1260 case MESSAGE_TIMED_OUT:
1261 Session session = (Session)msg.obj;
1262 session.onTimedOut();
1263 break;
1264
1265 default:
1266 throw new IllegalStateException("unhandled message: " + msg.what);
1267 }
1268 }
1269 }
1270
1271 private class DatabaseHelper extends SQLiteOpenHelper {
1272 public DatabaseHelper(Context context) {
1273 super(context, DATABASE_NAME, null, DATABASE_VERSION);
1274 }
1275
1276 @Override
1277 public void onCreate(SQLiteDatabase db) {
1278 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1279 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1280 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1281 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1282 + ACCOUNTS_PASSWORD + " TEXT, "
1283 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1284
1285 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1286 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1287 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1288 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1289 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1290 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1291
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001292 createGrantsTable(db);
1293
Fred Quintana60307342009-03-24 22:48:12 -07001294 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1295 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1296 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1297 + EXTRAS_KEY + " TEXT NOT NULL, "
1298 + EXTRAS_VALUE + " TEXT, "
1299 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1300
1301 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1302 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1303 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001304
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001305 createAccountsDeletionTrigger(db);
1306 }
1307
1308 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001309 db.execSQL(""
1310 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1311 + " BEGIN"
1312 + " DELETE FROM " + TABLE_AUTHTOKENS
1313 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1314 + " DELETE FROM " + TABLE_EXTRAS
1315 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001316 + " DELETE FROM " + TABLE_GRANTS
1317 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001318 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001319 }
1320
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001321 private void createGrantsTable(SQLiteDatabase db) {
1322 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1323 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1324 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1325 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1326 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1327 + "," + GRANTS_GRANTEE_UID + "))");
1328 }
1329
Fred Quintana60307342009-03-24 22:48:12 -07001330 @Override
1331 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001332 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001333
Fred Quintanaa698f422009-04-08 19:14:54 -07001334 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001335 // no longer need to do anything since the work is done
1336 // when upgrading from version 2
1337 oldVersion++;
1338 }
1339
1340 if (oldVersion == 2) {
1341 createGrantsTable(db);
1342 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1343 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001344 oldVersion++;
1345 }
Fred Quintana60307342009-03-24 22:48:12 -07001346 }
1347
1348 @Override
1349 public void onOpen(SQLiteDatabase db) {
1350 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1351 }
1352 }
1353
1354 private void setMetaValue(String key, String value) {
1355 ContentValues values = new ContentValues();
1356 values.put(META_KEY, key);
1357 values.put(META_VALUE, value);
1358 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1359 }
1360
1361 private String getMetaValue(String key) {
1362 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1363 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1364 try {
1365 if (c.moveToNext()) {
1366 return c.getString(0);
1367 }
1368 return null;
1369 } finally {
1370 c.close();
1371 }
1372 }
1373
1374 private class SimWatcher extends BroadcastReceiver {
1375 public SimWatcher(Context context) {
1376 // Re-scan the SIM card when the SIM state changes, and also if
1377 // the disk recovers from a full state (we may have failed to handle
1378 // things properly while the disk was full).
1379 final IntentFilter filter = new IntentFilter();
1380 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1381 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1382 context.registerReceiver(this, filter);
1383 }
1384
1385 /**
1386 * Compare the IMSI to the one stored in the login service's
1387 * database. If they differ, erase all passwords and
1388 * authtokens (and store the new IMSI).
1389 */
1390 @Override
1391 public void onReceive(Context context, Intent intent) {
1392 // Check IMSI on every update; nothing happens if the IMSI is missing or unchanged.
1393 String imsi = ((TelephonyManager) context.getSystemService(
1394 Context.TELEPHONY_SERVICE)).getSubscriberId();
1395 if (TextUtils.isEmpty(imsi)) return;
1396
1397 String storedImsi = getMetaValue("imsi");
1398
1399 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1400 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1401 }
1402
jsh5b462472009-09-01 16:13:55 -07001403 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001404 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1405 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001406 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1407 db.beginTransaction();
1408 try {
1409 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1410 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001411 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001412 db.setTransactionSuccessful();
1413 } finally {
1414 db.endTransaction();
1415 }
1416 }
1417 setMetaValue("imsi", imsi);
1418 }
1419 }
1420
1421 public IBinder onBind(Intent intent) {
1422 return asBinder();
1423 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001424
1425 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1426 synchronized (mSessions) {
1427 final long now = SystemClock.elapsedRealtime();
1428 fout.println("AccountManagerService: " + mSessions.size() + " sessions");
1429 for (Session session : mSessions.values()) {
1430 fout.println(" " + session.toDebugString(now));
1431 }
1432 }
1433
1434 fout.println();
1435
1436 mAuthenticatorCache.dump(fd, fout, args);
1437 }
1438
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001439 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001440 long identityToken = clearCallingIdentity();
1441 try {
1442 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1443 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1444 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001445
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001446 if (intent.getComponent() != null &&
1447 GrantCredentialsPermissionActivity.class.getName().equals(
1448 intent.getComponent().getClassName())) {
1449 createNoCredentialsPermissionNotification(account, intent);
1450 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001451 final Integer notificationId = getSigninRequiredNotificationId(account);
1452 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001453 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1454 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001455 final String notificationTitleFormat =
1456 mContext.getText(R.string.notification_title).toString();
1457 n.setLatestEventInfo(mContext,
1458 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001459 message, PendingIntent.getActivity(
1460 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1461 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001462 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001463 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001464 } finally {
1465 restoreCallingIdentity(identityToken);
1466 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001467 }
1468
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001469 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001470 long identityToken = clearCallingIdentity();
1471 try {
1472 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001473 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001474 } finally {
1475 restoreCallingIdentity(identityToken);
1476 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001477 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001478
1479 private void checkBinderPermission(String permission) {
1480 final int uid = Binder.getCallingUid();
1481 if (mContext.checkCallingOrSelfPermission(permission) !=
1482 PackageManager.PERMISSION_GRANTED) {
1483 String msg = "caller uid " + uid + " lacks " + permission;
1484 Log.w(TAG, msg);
1485 throw new SecurityException(msg);
1486 }
1487 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1488 Log.v(TAG, "caller uid " + uid + " has " + permission);
1489 }
1490 }
1491
Fred Quintana7be59642009-08-24 18:29:25 -07001492 private boolean inSystemImage(int callerUid) {
1493 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1494 for (String name : packages) {
1495 try {
1496 PackageInfo packageInfo =
1497 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1498 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1499 return true;
1500 }
1501 } catch (PackageManager.NameNotFoundException e) {
1502 return false;
1503 }
1504 }
1505 return false;
1506 }
1507
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001508 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001509 final boolean fromAuthenticator = hasAuthenticatorUid(account.type, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001510 final boolean hasExplicitGrants = hasExplicitlyGrantedPermission(account, authTokenType);
1511 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1512 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1513 + callerUid + ", account " + account
1514 + ": is authenticator? " + fromAuthenticator
1515 + ", has explicit permission? " + hasExplicitGrants);
1516 }
Fred Quintana7be59642009-08-24 18:29:25 -07001517 return fromAuthenticator || hasExplicitGrants || inSystemImage(callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001518 }
1519
1520 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
1521 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1522 mAuthenticatorCache.getAllServices()) {
1523 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001524 return (serviceInfo.uid == callingUid) ||
1525 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1526 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001527 }
1528 }
1529 return false;
1530 }
1531
1532 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1533 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1534 return true;
1535 }
1536 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1537 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001538 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001539 final boolean permissionGranted =
1540 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1541 if (!permissionGranted && isDebuggableMonkeyBuild) {
1542 // TODO: Skip this check when running automated tests. Replace this
1543 // with a more general solution.
1544 Log.w(TAG, "no credentials permission for usage of " + account + ", "
1545 + authTokenType + " by uid " + Binder.getCallingUid()
1546 + " but ignoring since this is a monkey build");
1547 return true;
1548 }
1549 return permissionGranted;
1550 }
1551
1552 private void checkCallingUidAgainstAuthenticator(Account account) {
1553 final int uid = Binder.getCallingUid();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001554 if (!hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001555 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1556 Log.w(TAG, msg);
1557 throw new SecurityException(msg);
1558 }
1559 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1560 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1561 }
1562 }
1563
1564 private void checkAuthenticateAccountsPermission(Account account) {
1565 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1566 checkCallingUidAgainstAuthenticator(account);
1567 }
1568
1569 private void checkReadAccountsPermission() {
1570 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1571 }
1572
1573 private void checkManageAccountsPermission() {
1574 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1575 }
1576
1577 /**
1578 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1579 * <p>
1580 * Although this is public it can only be accessed via the AccountManagerService object
1581 * which is in the system. This means we don't need to protect it with permissions.
1582 * @hide
1583 */
1584 public void grantAppPermission(Account account, String authTokenType, int uid) {
1585 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1586 db.beginTransaction();
1587 try {
1588 long accountId = getAccountId(db, account);
1589 if (accountId >= 0) {
1590 ContentValues values = new ContentValues();
1591 values.put(GRANTS_ACCOUNTS_ID, accountId);
1592 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1593 values.put(GRANTS_GRANTEE_UID, uid);
1594 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1595 db.setTransactionSuccessful();
1596 }
1597 } finally {
1598 db.endTransaction();
1599 }
1600 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1601 }
1602
1603 /**
1604 * Don't allow callers with the given uid permission to get credentials for
1605 * account/authTokenType.
1606 * <p>
1607 * Although this is public it can only be accessed via the AccountManagerService object
1608 * which is in the system. This means we don't need to protect it with permissions.
1609 * @hide
1610 */
1611 public void revokeAppPermission(Account account, String authTokenType, int uid) {
1612 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1613 db.beginTransaction();
1614 try {
1615 long accountId = getAccountId(db, account);
1616 if (accountId >= 0) {
1617 db.delete(TABLE_GRANTS,
1618 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1619 + GRANTS_GRANTEE_UID + "=?",
1620 new String[]{String.valueOf(accountId), authTokenType,
1621 String.valueOf(uid)});
1622 db.setTransactionSuccessful();
1623 }
1624 } finally {
1625 db.endTransaction();
1626 }
1627 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1628 }
Fred Quintana60307342009-03-24 22:48:12 -07001629}