blob: 5ed89418238f515506c67f797d6d3a93dab37a44 [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 */);
717 final CharSequence subtitleFormatString =
718 mContext.getText(R.string.permission_request_notification_subtitle);
719 n.setLatestEventInfo(mContext,
720 mContext.getText(R.string.permission_request_notification_title),
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700721 String.format(subtitleFormatString.toString(), account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700722 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
723 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
724 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
725 }
726
727 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
728 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
729 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
730 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700731 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700732 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700733 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700734 }
735
736 final Context authContext;
737 try {
738 authContext = mContext.createPackageContext(
739 serviceInfo.type.packageName, 0);
740 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700741 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700742 }
743
744 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
745 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
746 intent.addCategory(
747 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
748 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
749 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
750 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
751 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
752 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
753 authContext.getString(serviceInfo.type.labelId));
754 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
755 mContext.getPackageManager().getPackagesForUid(uid));
756 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
757 return intent;
758 }
759
760 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
761 int uid) {
762 Integer id;
763 synchronized(mCredentialsPermissionNotificationIds) {
764 final Pair<Pair<Account, String>, Integer> key =
765 new Pair<Pair<Account, String>, Integer>(
766 new Pair<Account, String>(account, authTokenType), uid);
767 id = mCredentialsPermissionNotificationIds.get(key);
768 if (id == null) {
769 id = mNotificationIds.incrementAndGet();
770 mCredentialsPermissionNotificationIds.put(key, id);
771 }
772 }
773 return id;
774 }
775
776 private Integer getSigninRequiredNotificationId(Account account) {
777 Integer id;
778 synchronized(mSigninRequiredNotificationIds) {
779 id = mSigninRequiredNotificationIds.get(account);
780 if (id == null) {
781 id = mNotificationIds.incrementAndGet();
782 mSigninRequiredNotificationIds.put(account, id);
783 }
784 }
785 return id;
786 }
787
Fred Quintanaa698f422009-04-08 19:14:54 -0700788
Fred Quintana33269202009-04-20 16:05:10 -0700789 public void addAcount(final IAccountManagerResponse response, final String accountType,
790 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700791 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700792 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700793 long identityToken = clearCallingIdentity();
794 try {
795 new Session(response, accountType, expectActivityLaunch) {
796 public void run() throws RemoteException {
Fred Quintana33269202009-04-20 16:05:10 -0700797 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
798 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700799 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700800
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700801 protected String toDebugString(long now) {
802 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -0700803 + ", accountType " + accountType
804 + ", requiredFeatures "
805 + (requiredFeatures != null
806 ? TextUtils.join(",", requiredFeatures)
807 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700808 }
809 }.bind();
810 } finally {
811 restoreCallingIdentity(identityToken);
812 }
Fred Quintana60307342009-03-24 22:48:12 -0700813 }
814
Fred Quintanaa698f422009-04-08 19:14:54 -0700815 public void confirmCredentials(IAccountManagerResponse response,
816 final Account account, final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700817 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700818 long identityToken = clearCallingIdentity();
819 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700820 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700821 public void run() throws RemoteException {
822 mAuthenticator.confirmCredentials(this, account);
823 }
824 protected String toDebugString(long now) {
825 return super.toDebugString(now) + ", confirmCredentials"
826 + ", " + account;
827 }
828 }.bind();
829 } finally {
830 restoreCallingIdentity(identityToken);
831 }
Fred Quintana60307342009-03-24 22:48:12 -0700832 }
833
Fred Quintanaa698f422009-04-08 19:14:54 -0700834 public void confirmPassword(IAccountManagerResponse response, final Account account,
835 final String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700836 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700837 long identityToken = clearCallingIdentity();
838 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700839 new Session(response, account.type, false /* expectActivityLaunch */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700840 public void run() throws RemoteException {
841 mAuthenticator.confirmPassword(this, account, password);
842 }
843 protected String toDebugString(long now) {
844 return super.toDebugString(now) + ", confirmPassword"
845 + ", " + account;
846 }
847 }.bind();
848 } finally {
849 restoreCallingIdentity(identityToken);
850 }
Fred Quintana60307342009-03-24 22:48:12 -0700851 }
852
Fred Quintanaa698f422009-04-08 19:14:54 -0700853 public void updateCredentials(IAccountManagerResponse response, final Account account,
854 final String authTokenType, final boolean expectActivityLaunch,
855 final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700856 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700857 long identityToken = clearCallingIdentity();
858 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700859 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700860 public void run() throws RemoteException {
861 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
862 }
863 protected String toDebugString(long now) {
864 if (loginOptions != null) loginOptions.keySet();
865 return super.toDebugString(now) + ", updateCredentials"
866 + ", " + account
867 + ", authTokenType " + authTokenType
868 + ", loginOptions " + loginOptions;
869 }
870 }.bind();
871 } finally {
872 restoreCallingIdentity(identityToken);
873 }
Fred Quintana60307342009-03-24 22:48:12 -0700874 }
875
Fred Quintanaa698f422009-04-08 19:14:54 -0700876 public void editProperties(IAccountManagerResponse response, final String accountType,
877 final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700878 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700879 long identityToken = clearCallingIdentity();
880 try {
881 new Session(response, accountType, expectActivityLaunch) {
882 public void run() throws RemoteException {
883 mAuthenticator.editProperties(this, mAccountType);
884 }
885 protected String toDebugString(long now) {
886 return super.toDebugString(now) + ", editProperties"
887 + ", accountType " + accountType;
888 }
889 }.bind();
890 } finally {
891 restoreCallingIdentity(identityToken);
892 }
Fred Quintana60307342009-03-24 22:48:12 -0700893 }
894
Fred Quintana33269202009-04-20 16:05:10 -0700895 private class GetAccountsByTypeAndFeatureSession extends Session {
896 private final String[] mFeatures;
897 private volatile Account[] mAccountsOfType = null;
898 private volatile ArrayList<Account> mAccountsWithFeatures = null;
899 private volatile int mCurrentAccount = 0;
900
901 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
902 String type, String[] features) {
903 super(response, type, false /* expectActivityLaunch */);
904 mFeatures = features;
905 }
906
907 public void run() throws RemoteException {
908 mAccountsOfType = getAccountsByType(mAccountType);
909 // check whether each account matches the requested features
910 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
911 mCurrentAccount = 0;
912
913 checkAccount();
914 }
915
916 public void checkAccount() {
917 if (mCurrentAccount >= mAccountsOfType.length) {
918 sendResult();
919 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700920 }
Fred Quintana33269202009-04-20 16:05:10 -0700921
922 try {
923 mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
924 } catch (RemoteException e) {
925 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
926 }
927 }
928
929 public void onResult(Bundle result) {
930 mNumResults++;
931 if (result == null) {
932 onError(Constants.ERROR_CODE_INVALID_RESPONSE, "null bundle");
933 return;
934 }
935 if (result.getBoolean(Constants.BOOLEAN_RESULT_KEY, false)) {
936 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
937 }
938 mCurrentAccount++;
939 checkAccount();
940 }
941
942 public void sendResult() {
943 IAccountManagerResponse response = getResponseAndClose();
944 if (response != null) {
945 try {
946 Account[] accounts = new Account[mAccountsWithFeatures.size()];
947 for (int i = 0; i < accounts.length; i++) {
948 accounts[i] = mAccountsWithFeatures.get(i);
949 }
950 Bundle result = new Bundle();
951 result.putParcelableArray(Constants.ACCOUNTS_KEY, accounts);
952 response.onResult(result);
953 } catch (RemoteException e) {
954 // if the caller is dead then there is no one to care about remote exceptions
955 if (Log.isLoggable(TAG, Log.VERBOSE)) {
956 Log.v(TAG, "failure while notifying response", e);
957 }
958 }
959 }
960 }
961
962
963 protected String toDebugString(long now) {
964 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
965 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
966 }
967 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700968
969 public Account[] getAccounts(String type) {
970 checkReadAccountsPermission();
971 long identityToken = clearCallingIdentity();
972 try {
973 return getAccountsByType(type);
974 } finally {
975 restoreCallingIdentity(identityToken);
976 }
977 }
978
979 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -0700980 String type, String[] features) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700981 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700982 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -0700983 if (response != null) {
984 try {
985 response.onError(Constants.ERROR_CODE_BAD_ARGUMENTS, "type is null");
986 } catch (RemoteException e) {
987 // ignore this
988 }
989 }
990 return;
991 }
992 long identityToken = clearCallingIdentity();
993 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700994 if (features == null || features.length == 0) {
995 getAccountsByType(type);
996 return;
997 }
Fred Quintana33269202009-04-20 16:05:10 -0700998 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
999 } finally {
1000 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001001 }
1002 }
1003
Fred Quintana33269202009-04-20 16:05:10 -07001004 private boolean cacheAuthToken(Account account, String authTokenType, String authToken) {
1005 return saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana60307342009-03-24 22:48:12 -07001006 }
1007
1008 private long getAccountId(SQLiteDatabase db, Account account) {
1009 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001010 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001011 try {
1012 if (cursor.moveToNext()) {
1013 return cursor.getLong(0);
1014 }
1015 return -1;
1016 } finally {
1017 cursor.close();
1018 }
1019 }
1020
1021 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1022 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1023 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1024 new String[]{key}, null, null, null);
1025 try {
1026 if (cursor.moveToNext()) {
1027 return cursor.getLong(0);
1028 }
1029 return -1;
1030 } finally {
1031 cursor.close();
1032 }
1033 }
1034
1035 private String getAuthToken(SQLiteDatabase db, long accountId, String authTokenType) {
1036 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
1037 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1038 new String[]{authTokenType},
1039 null, null, null);
1040 try {
1041 if (cursor.moveToNext()) {
1042 return cursor.getString(0);
1043 }
1044 return null;
1045 } finally {
1046 cursor.close();
1047 }
1048 }
1049
Fred Quintanaa698f422009-04-08 19:14:54 -07001050 private abstract class Session extends IAccountAuthenticatorResponse.Stub
1051 implements AuthenticatorBindHelper.Callback, IBinder.DeathRecipient {
Fred Quintana60307342009-03-24 22:48:12 -07001052 IAccountManagerResponse mResponse;
1053 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001054 final boolean mExpectActivityLaunch;
1055 final long mCreationTime;
1056
Fred Quintana33269202009-04-20 16:05:10 -07001057 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001058 private int mNumRequestContinued = 0;
1059 private int mNumErrors = 0;
1060
Fred Quintana60307342009-03-24 22:48:12 -07001061
1062 IAccountAuthenticator mAuthenticator = null;
1063
Fred Quintanaa698f422009-04-08 19:14:54 -07001064 public Session(IAccountManagerResponse response, String accountType,
1065 boolean expectActivityLaunch) {
Fred Quintana60307342009-03-24 22:48:12 -07001066 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001067 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001068 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana60307342009-03-24 22:48:12 -07001069 mResponse = response;
1070 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001071 mExpectActivityLaunch = expectActivityLaunch;
1072 mCreationTime = SystemClock.elapsedRealtime();
1073 synchronized (mSessions) {
1074 mSessions.put(toString(), this);
1075 }
1076 try {
1077 response.asBinder().linkToDeath(this, 0 /* flags */);
1078 } catch (RemoteException e) {
1079 mResponse = null;
1080 binderDied();
1081 }
Fred Quintana60307342009-03-24 22:48:12 -07001082 }
1083
Fred Quintanaa698f422009-04-08 19:14:54 -07001084 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001085 if (mResponse == null) {
1086 // this session has already been closed
1087 return null;
1088 }
Fred Quintana60307342009-03-24 22:48:12 -07001089 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001090 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001091 return response;
1092 }
1093
Fred Quintanaa698f422009-04-08 19:14:54 -07001094 private void close() {
1095 synchronized (mSessions) {
1096 if (mSessions.remove(toString()) == null) {
1097 // the session was already closed, so bail out now
1098 return;
1099 }
1100 }
1101 if (mResponse != null) {
1102 // stop listening for response deaths
1103 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1104
1105 // clear this so that we don't accidentally send any further results
1106 mResponse = null;
1107 }
1108 cancelTimeout();
1109 unbind();
1110 }
1111
1112 public void binderDied() {
1113 mResponse = null;
1114 close();
1115 }
1116
1117 protected String toDebugString() {
1118 return toDebugString(SystemClock.elapsedRealtime());
1119 }
1120
1121 protected String toDebugString(long now) {
1122 return "Session: expectLaunch " + mExpectActivityLaunch
1123 + ", connected " + (mAuthenticator != null)
1124 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1125 + "/" + mNumErrors + ")"
1126 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1127 }
1128
Fred Quintana60307342009-03-24 22:48:12 -07001129 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001130 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1131 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1132 }
Fred Quintana60307342009-03-24 22:48:12 -07001133 if (!mBindHelper.bind(mAccountType, this)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001134 Log.d(TAG, "bind attempt failed for " + toDebugString());
1135 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001136 }
1137 }
1138
1139 private void unbind() {
1140 if (mAuthenticator != null) {
1141 mAuthenticator = null;
1142 mBindHelper.unbind(this);
1143 }
1144 }
1145
1146 public void scheduleTimeout() {
1147 mMessageHandler.sendMessageDelayed(
1148 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1149 }
1150
1151 public void cancelTimeout() {
1152 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1153 }
1154
1155 public void onConnected(IBinder service) {
1156 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001157 try {
1158 run();
1159 } catch (RemoteException e) {
1160 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1161 "remote exception");
1162 }
Fred Quintana60307342009-03-24 22:48:12 -07001163 }
1164
Fred Quintanaa698f422009-04-08 19:14:54 -07001165 public abstract void run() throws RemoteException;
1166
Fred Quintana60307342009-03-24 22:48:12 -07001167 public void onDisconnected() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001168 mAuthenticator = null;
1169 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001170 if (response != null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001171 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1172 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001173 }
1174 }
1175
1176 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001177 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001178 if (response != null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001179 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1180 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001181 }
1182 }
1183
Fred Quintanaa698f422009-04-08 19:14:54 -07001184 public void onResult(Bundle result) {
1185 mNumResults++;
1186 if (result != null && !TextUtils.isEmpty(result.getString(Constants.AUTHTOKEN_KEY))) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001187 String accountName = result.getString(Constants.ACCOUNT_NAME_KEY);
1188 String accountType = result.getString(Constants.ACCOUNT_TYPE_KEY);
1189 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1190 Account account = new Account(accountName, accountType);
1191 cancelNotification(getSigninRequiredNotificationId(account));
1192 }
Fred Quintana60307342009-03-24 22:48:12 -07001193 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001194 IAccountManagerResponse response;
1195 if (mExpectActivityLaunch && result != null
1196 && result.containsKey(Constants.INTENT_KEY)) {
1197 response = mResponse;
1198 } else {
1199 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001200 }
Fred Quintana60307342009-03-24 22:48:12 -07001201 if (response != null) {
1202 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001203 if (result == null) {
1204 response.onError(Constants.ERROR_CODE_INVALID_RESPONSE,
1205 "null bundle returned");
1206 } else {
1207 response.onResult(result);
1208 }
Fred Quintana60307342009-03-24 22:48:12 -07001209 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001210 // if the caller is dead then there is no one to care about remote exceptions
1211 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1212 Log.v(TAG, "failure while notifying response", e);
1213 }
Fred Quintana60307342009-03-24 22:48:12 -07001214 }
1215 }
1216 }
Fred Quintana60307342009-03-24 22:48:12 -07001217
Fred Quintanaa698f422009-04-08 19:14:54 -07001218 public void onRequestContinued() {
1219 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001220 }
1221
1222 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001223 mNumErrors++;
1224 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1225 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001226 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001227 IAccountManagerResponse response = getResponseAndClose();
1228 if (response != null) {
1229 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1230 Log.v(TAG, "Session.onError: responding");
1231 }
1232 try {
1233 response.onError(errorCode, errorMessage);
1234 } catch (RemoteException e) {
1235 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1236 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1237 }
1238 }
1239 } else {
1240 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1241 Log.v(TAG, "Session.onError: already closed");
1242 }
Fred Quintana60307342009-03-24 22:48:12 -07001243 }
1244 }
1245 }
1246
1247 private class MessageHandler extends Handler {
1248 MessageHandler(Looper looper) {
1249 super(looper);
1250 }
1251
1252 public void handleMessage(Message msg) {
1253 if (mBindHelper.handleMessage(msg)) {
1254 return;
1255 }
1256 switch (msg.what) {
1257 case MESSAGE_TIMED_OUT:
1258 Session session = (Session)msg.obj;
1259 session.onTimedOut();
1260 break;
1261
1262 default:
1263 throw new IllegalStateException("unhandled message: " + msg.what);
1264 }
1265 }
1266 }
1267
1268 private class DatabaseHelper extends SQLiteOpenHelper {
1269 public DatabaseHelper(Context context) {
1270 super(context, DATABASE_NAME, null, DATABASE_VERSION);
1271 }
1272
1273 @Override
1274 public void onCreate(SQLiteDatabase db) {
1275 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1276 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1277 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1278 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1279 + ACCOUNTS_PASSWORD + " TEXT, "
1280 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1281
1282 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1283 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1284 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1285 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1286 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1287 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1288
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001289 createGrantsTable(db);
1290
Fred Quintana60307342009-03-24 22:48:12 -07001291 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1292 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1293 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1294 + EXTRAS_KEY + " TEXT NOT NULL, "
1295 + EXTRAS_VALUE + " TEXT, "
1296 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1297
1298 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1299 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1300 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001301
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001302 createAccountsDeletionTrigger(db);
1303 }
1304
1305 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001306 db.execSQL(""
1307 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1308 + " BEGIN"
1309 + " DELETE FROM " + TABLE_AUTHTOKENS
1310 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1311 + " DELETE FROM " + TABLE_EXTRAS
1312 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001313 + " DELETE FROM " + TABLE_GRANTS
1314 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001315 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001316 }
1317
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001318 private void createGrantsTable(SQLiteDatabase db) {
1319 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1320 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1321 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1322 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1323 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1324 + "," + GRANTS_GRANTEE_UID + "))");
1325 }
1326
Fred Quintana60307342009-03-24 22:48:12 -07001327 @Override
1328 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001329 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001330
Fred Quintanaa698f422009-04-08 19:14:54 -07001331 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001332 // no longer need to do anything since the work is done
1333 // when upgrading from version 2
1334 oldVersion++;
1335 }
1336
1337 if (oldVersion == 2) {
1338 createGrantsTable(db);
1339 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1340 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001341 oldVersion++;
1342 }
Fred Quintana60307342009-03-24 22:48:12 -07001343 }
1344
1345 @Override
1346 public void onOpen(SQLiteDatabase db) {
1347 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1348 }
1349 }
1350
1351 private void setMetaValue(String key, String value) {
1352 ContentValues values = new ContentValues();
1353 values.put(META_KEY, key);
1354 values.put(META_VALUE, value);
1355 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1356 }
1357
1358 private String getMetaValue(String key) {
1359 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1360 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1361 try {
1362 if (c.moveToNext()) {
1363 return c.getString(0);
1364 }
1365 return null;
1366 } finally {
1367 c.close();
1368 }
1369 }
1370
1371 private class SimWatcher extends BroadcastReceiver {
1372 public SimWatcher(Context context) {
1373 // Re-scan the SIM card when the SIM state changes, and also if
1374 // the disk recovers from a full state (we may have failed to handle
1375 // things properly while the disk was full).
1376 final IntentFilter filter = new IntentFilter();
1377 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1378 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1379 context.registerReceiver(this, filter);
1380 }
1381
1382 /**
1383 * Compare the IMSI to the one stored in the login service's
1384 * database. If they differ, erase all passwords and
1385 * authtokens (and store the new IMSI).
1386 */
1387 @Override
1388 public void onReceive(Context context, Intent intent) {
1389 // Check IMSI on every update; nothing happens if the IMSI is missing or unchanged.
1390 String imsi = ((TelephonyManager) context.getSystemService(
1391 Context.TELEPHONY_SERVICE)).getSubscriberId();
1392 if (TextUtils.isEmpty(imsi)) return;
1393
1394 String storedImsi = getMetaValue("imsi");
1395
1396 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1397 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1398 }
1399
1400 if (!imsi.equals(storedImsi) && !"initial".equals(storedImsi)) {
1401 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1402 Log.v(TAG, "wiping all passwords and authtokens");
1403 }
1404 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1405 db.beginTransaction();
1406 try {
1407 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1408 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001409 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001410 db.setTransactionSuccessful();
1411 } finally {
1412 db.endTransaction();
1413 }
1414 }
1415 setMetaValue("imsi", imsi);
1416 }
1417 }
1418
1419 public IBinder onBind(Intent intent) {
1420 return asBinder();
1421 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001422
1423 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1424 synchronized (mSessions) {
1425 final long now = SystemClock.elapsedRealtime();
1426 fout.println("AccountManagerService: " + mSessions.size() + " sessions");
1427 for (Session session : mSessions.values()) {
1428 fout.println(" " + session.toDebugString(now));
1429 }
1430 }
1431
1432 fout.println();
1433
1434 mAuthenticatorCache.dump(fd, fout, args);
1435 }
1436
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001437 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001438 long identityToken = clearCallingIdentity();
1439 try {
1440 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1441 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1442 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001443
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001444 if (intent.getComponent() != null &&
1445 GrantCredentialsPermissionActivity.class.getName().equals(
1446 intent.getComponent().getClassName())) {
1447 createNoCredentialsPermissionNotification(account, intent);
1448 } else {
1449 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1450 0 /* when */);
1451 n.setLatestEventInfo(mContext, mContext.getText(R.string.notification_title),
1452 message, PendingIntent.getActivity(
1453 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1454 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
1455 .notify(getSigninRequiredNotificationId(account), n);
1456 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001457 } finally {
1458 restoreCallingIdentity(identityToken);
1459 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001460 }
1461
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001462 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001463 long identityToken = clearCallingIdentity();
1464 try {
1465 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001466 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001467 } finally {
1468 restoreCallingIdentity(identityToken);
1469 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001470 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001471
1472 private void checkBinderPermission(String permission) {
1473 final int uid = Binder.getCallingUid();
1474 if (mContext.checkCallingOrSelfPermission(permission) !=
1475 PackageManager.PERMISSION_GRANTED) {
1476 String msg = "caller uid " + uid + " lacks " + permission;
1477 Log.w(TAG, msg);
1478 throw new SecurityException(msg);
1479 }
1480 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1481 Log.v(TAG, "caller uid " + uid + " has " + permission);
1482 }
1483 }
1484
Fred Quintana7be59642009-08-24 18:29:25 -07001485 private boolean inSystemImage(int callerUid) {
1486 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1487 for (String name : packages) {
1488 try {
1489 PackageInfo packageInfo =
1490 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1491 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1492 return true;
1493 }
1494 } catch (PackageManager.NameNotFoundException e) {
1495 return false;
1496 }
1497 }
1498 return false;
1499 }
1500
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001501 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001502 final boolean fromAuthenticator = hasAuthenticatorUid(account.type, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001503 final boolean hasExplicitGrants = hasExplicitlyGrantedPermission(account, authTokenType);
1504 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1505 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1506 + callerUid + ", account " + account
1507 + ": is authenticator? " + fromAuthenticator
1508 + ", has explicit permission? " + hasExplicitGrants);
1509 }
Fred Quintana7be59642009-08-24 18:29:25 -07001510 return fromAuthenticator || hasExplicitGrants || inSystemImage(callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001511 }
1512
1513 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
1514 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1515 mAuthenticatorCache.getAllServices()) {
1516 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001517 return (serviceInfo.uid == callingUid) ||
1518 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1519 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001520 }
1521 }
1522 return false;
1523 }
1524
1525 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1526 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1527 return true;
1528 }
1529 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1530 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001531 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001532 final boolean permissionGranted =
1533 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1534 if (!permissionGranted && isDebuggableMonkeyBuild) {
1535 // TODO: Skip this check when running automated tests. Replace this
1536 // with a more general solution.
1537 Log.w(TAG, "no credentials permission for usage of " + account + ", "
1538 + authTokenType + " by uid " + Binder.getCallingUid()
1539 + " but ignoring since this is a monkey build");
1540 return true;
1541 }
1542 return permissionGranted;
1543 }
1544
1545 private void checkCallingUidAgainstAuthenticator(Account account) {
1546 final int uid = Binder.getCallingUid();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001547 if (!hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001548 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1549 Log.w(TAG, msg);
1550 throw new SecurityException(msg);
1551 }
1552 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1553 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1554 }
1555 }
1556
1557 private void checkAuthenticateAccountsPermission(Account account) {
1558 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1559 checkCallingUidAgainstAuthenticator(account);
1560 }
1561
1562 private void checkReadAccountsPermission() {
1563 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1564 }
1565
1566 private void checkManageAccountsPermission() {
1567 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1568 }
1569
1570 /**
1571 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1572 * <p>
1573 * Although this is public it can only be accessed via the AccountManagerService object
1574 * which is in the system. This means we don't need to protect it with permissions.
1575 * @hide
1576 */
1577 public void grantAppPermission(Account account, String authTokenType, int uid) {
1578 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1579 db.beginTransaction();
1580 try {
1581 long accountId = getAccountId(db, account);
1582 if (accountId >= 0) {
1583 ContentValues values = new ContentValues();
1584 values.put(GRANTS_ACCOUNTS_ID, accountId);
1585 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1586 values.put(GRANTS_GRANTEE_UID, uid);
1587 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1588 db.setTransactionSuccessful();
1589 }
1590 } finally {
1591 db.endTransaction();
1592 }
1593 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1594 }
1595
1596 /**
1597 * Don't allow callers with the given uid permission to get credentials for
1598 * account/authTokenType.
1599 * <p>
1600 * Although this is public it can only be accessed via the AccountManagerService object
1601 * which is in the system. This means we don't need to protect it with permissions.
1602 * @hide
1603 */
1604 public void revokeAppPermission(Account account, String authTokenType, int uid) {
1605 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1606 db.beginTransaction();
1607 try {
1608 long accountId = getAccountId(db, account);
1609 if (accountId >= 0) {
1610 db.delete(TABLE_GRANTS,
1611 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1612 + GRANTS_GRANTEE_UID + "=?",
1613 new String[]{String.valueOf(accountId), authTokenType,
1614 String.valueOf(uid)});
1615 db.setTransactionSuccessful();
1616 }
1617 } finally {
1618 db.endTransaction();
1619 }
1620 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1621 }
Fred Quintana60307342009-03-24 22:48:12 -07001622}