blob: 9c8006ee0d9f12f0806be817c0f43065a8ce61e3 [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 Quintana3ecd5f42009-09-17 12:42:35 -070028import android.content.pm.RegisteredServicesCacheListener;
Fred Quintana60307342009-03-24 22:48:12 -070029import android.database.Cursor;
30import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070031import android.database.sqlite.SQLiteDatabase;
32import android.database.sqlite.SQLiteOpenHelper;
33import android.os.Bundle;
34import android.os.Handler;
35import android.os.HandlerThread;
36import android.os.IBinder;
37import android.os.Looper;
38import android.os.Message;
39import android.os.RemoteException;
40import android.os.SystemClock;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070041import android.os.Binder;
42import android.os.SystemProperties;
Fred Quintana60307342009-03-24 22:48:12 -070043import android.telephony.TelephonyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070044import android.text.TextUtils;
45import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070046import android.util.Pair;
Fred Quintana26fc5eb2009-04-09 15:05:50 -070047import android.app.PendingIntent;
48import android.app.NotificationManager;
49import android.app.Notification;
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 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070073public class AccountManagerService
74 extends IAccountManager.Stub
75 implements RegisteredServicesCacheListener {
Fred Quintana60307342009-03-24 22:48:12 -070076 private static final String TAG = "AccountManagerService";
77
78 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
79 private static final String DATABASE_NAME = "accounts.db";
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070080 private static final int DATABASE_VERSION = 3;
Fred Quintana60307342009-03-24 22:48:12 -070081
82 private final Context mContext;
83
84 private HandlerThread mMessageThread;
85 private final MessageHandler mMessageHandler;
86
87 // Messages that can be sent on mHandler
88 private static final int MESSAGE_TIMED_OUT = 3;
89 private static final int MESSAGE_CONNECTED = 7;
90 private static final int MESSAGE_DISCONNECTED = 8;
91
92 private final AccountAuthenticatorCache mAuthenticatorCache;
93 private final AuthenticatorBindHelper mBindHelper;
Fred Quintana60307342009-03-24 22:48:12 -070094 private final DatabaseHelper mOpenHelper;
95 private final SimWatcher mSimWatcher;
96
97 private static final String TABLE_ACCOUNTS = "accounts";
98 private static final String ACCOUNTS_ID = "_id";
99 private static final String ACCOUNTS_NAME = "name";
100 private static final String ACCOUNTS_TYPE = "type";
101 private static final String ACCOUNTS_PASSWORD = "password";
102
103 private static final String TABLE_AUTHTOKENS = "authtokens";
104 private static final String AUTHTOKENS_ID = "_id";
105 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
106 private static final String AUTHTOKENS_TYPE = "type";
107 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
108
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700109 private static final String TABLE_GRANTS = "grants";
110 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
111 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
112 private static final String GRANTS_GRANTEE_UID = "uid";
113
Fred Quintana60307342009-03-24 22:48:12 -0700114 private static final String TABLE_EXTRAS = "extras";
115 private static final String EXTRAS_ID = "_id";
116 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
117 private static final String EXTRAS_KEY = "key";
118 private static final String EXTRAS_VALUE = "value";
119
120 private static final String TABLE_META = "meta";
121 private static final String META_KEY = "key";
122 private static final String META_VALUE = "value";
123
124 private static final String[] ACCOUNT_NAME_TYPE_PROJECTION =
125 new String[]{ACCOUNTS_ID, ACCOUNTS_NAME, ACCOUNTS_TYPE};
Fred Quintana7be59642009-08-24 18:29:25 -0700126 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700127
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700128 private static final String COUNT_OF_MATCHING_GRANTS = ""
129 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
130 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
131 + " AND " + GRANTS_GRANTEE_UID + "=?"
132 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
133 + " AND " + ACCOUNTS_NAME + "=?"
134 + " AND " + ACCOUNTS_TYPE + "=?";
135
Fred Quintanaa698f422009-04-08 19:14:54 -0700136 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700137 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
138
139 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
140 mCredentialsPermissionNotificationIds =
141 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
142 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
143 new HashMap<Account, Integer>();
144 private static AtomicReference<AccountManagerService> sThis =
145 new AtomicReference<AccountManagerService>();
146
147 private static final boolean isDebuggableMonkeyBuild =
148 SystemProperties.getBoolean("ro.monkey", false)
149 && SystemProperties.getBoolean("ro.debuggable", false);
Fred Quintana7be59642009-08-24 18:29:25 -0700150
151 static {
152 ACCOUNTS_CHANGED_INTENT = new Intent(Constants.LOGIN_ACCOUNTS_CHANGED_ACTION);
153 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
154 }
155
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700156 /**
157 * This should only be called by system code. One should only call this after the service
158 * has started.
159 * @return a reference to the AccountManagerService instance
160 * @hide
161 */
162 public static AccountManagerService getSingleton() {
163 return sThis.get();
164 }
Fred Quintana60307342009-03-24 22:48:12 -0700165
166 public class AuthTokenKey {
167 public final Account mAccount;
168 public final String mAuthTokenType;
169 private final int mHashCode;
170
171 public AuthTokenKey(Account account, String authTokenType) {
172 mAccount = account;
173 mAuthTokenType = authTokenType;
174 mHashCode = computeHashCode();
175 }
176
177 public boolean equals(Object o) {
178 if (o == this) {
179 return true;
180 }
181 if (!(o instanceof AuthTokenKey)) {
182 return false;
183 }
184 AuthTokenKey other = (AuthTokenKey)o;
185 if (!mAccount.equals(other.mAccount)) {
186 return false;
187 }
188 return (mAuthTokenType == null)
189 ? other.mAuthTokenType == null
190 : mAuthTokenType.equals(other.mAuthTokenType);
191 }
192
193 private int computeHashCode() {
194 int result = 17;
195 result = 31 * result + mAccount.hashCode();
196 result = 31 * result + ((mAuthTokenType == null) ? 0 : mAuthTokenType.hashCode());
197 return result;
198 }
199
200 public int hashCode() {
201 return mHashCode;
202 }
203 }
204
205 public AccountManagerService(Context context) {
206 mContext = context;
207
208 mOpenHelper = new DatabaseHelper(mContext);
209
210 mMessageThread = new HandlerThread("AccountManagerService");
211 mMessageThread.start();
212 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
213
214 mAuthenticatorCache = new AccountAuthenticatorCache(mContext);
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700215 mAuthenticatorCache.setListener(this);
Fred Quintana60307342009-03-24 22:48:12 -0700216 mBindHelper = new AuthenticatorBindHelper(mContext, mAuthenticatorCache, mMessageHandler,
217 MESSAGE_CONNECTED, MESSAGE_DISCONNECTED);
218
219 mSimWatcher = new SimWatcher(mContext);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700220 sThis.set(this);
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700221
222 onRegisteredServicesCacheChanged();
223 }
224
225 public void onRegisteredServicesCacheChanged() {
226 boolean accountDeleted = false;
227 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
228 Cursor cursor = db.query(TABLE_ACCOUNTS,
229 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
230 null, null, null, null, null);
231 try {
232 while (cursor.moveToNext()) {
233 final long accountId = cursor.getLong(0);
234 final String accountType = cursor.getString(1);
235 final String accountName = cursor.getString(2);
236 if (mAuthenticatorCache.getServiceInfo(AuthenticatorDescription.newKey(accountType))
237 == null) {
238 Log.d(TAG, "deleting account " + accountName + " because type "
239 + accountType + " no longer has a registered authenticator");
240 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
241 accountDeleted= true;
242 }
243 }
244 } finally {
245 cursor.close();
246 if (accountDeleted) {
247 sendAccountsChangedBroadcast();
248 }
249 }
Fred Quintana60307342009-03-24 22:48:12 -0700250 }
251
Fred Quintanaa698f422009-04-08 19:14:54 -0700252 public String getPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700253 checkAuthenticateAccountsPermission(account);
254
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700255 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700256 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700257 return readPasswordFromDatabase(account);
258 } finally {
259 restoreCallingIdentity(identityToken);
260 }
261 }
262
263 private String readPasswordFromDatabase(Account account) {
264 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
265 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
266 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
267 new String[]{account.name, account.type}, null, null, null);
268 try {
269 if (cursor.moveToNext()) {
270 return cursor.getString(0);
271 }
272 return null;
273 } finally {
274 cursor.close();
275 }
276 }
277
278 public String getUserData(Account account, String key) {
279 checkAuthenticateAccountsPermission(account);
280 long identityToken = clearCallingIdentity();
281 try {
282 return readUserDataFromDatabase(account, key);
283 } finally {
284 restoreCallingIdentity(identityToken);
285 }
286 }
287
288 private String readUserDataFromDatabase(Account account, String key) {
289 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
290 db.beginTransaction();
291 try {
292 long accountId = getAccountId(db, account);
293 if (accountId < 0) {
294 return null;
295 }
296 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_VALUE},
297 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
298 new String[]{key}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700299 try {
300 if (cursor.moveToNext()) {
301 return cursor.getString(0);
302 }
303 return null;
304 } finally {
305 cursor.close();
306 }
307 } finally {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700308 db.endTransaction();
Fred Quintana60307342009-03-24 22:48:12 -0700309 }
310 }
311
Fred Quintana97889762009-06-15 12:29:24 -0700312 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700313 long identityToken = clearCallingIdentity();
314 try {
Fred Quintana97889762009-06-15 12:29:24 -0700315 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
316 authenticatorCollection = mAuthenticatorCache.getAllServices();
317 AuthenticatorDescription[] types =
318 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700319 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700320 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700321 : authenticatorCollection) {
322 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700323 i++;
324 }
325 return types;
326 } finally {
327 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700328 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700329 }
330
Fred Quintanaa698f422009-04-08 19:14:54 -0700331 public Account[] getAccountsByType(String accountType) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700332 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700333
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700334 final String selection = accountType == null ? null : (ACCOUNTS_TYPE + "=?");
335 final String[] selectionArgs = accountType == null ? null : new String[]{accountType};
336 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_NAME_TYPE_PROJECTION,
337 selection, selectionArgs, null, null, null);
338 try {
339 int i = 0;
340 Account[] accounts = new Account[cursor.getCount()];
341 while (cursor.moveToNext()) {
342 accounts[i] = new Account(cursor.getString(1), cursor.getString(2));
343 i++;
Fred Quintana60307342009-03-24 22:48:12 -0700344 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700345 return accounts;
Fred Quintana60307342009-03-24 22:48:12 -0700346 } finally {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700347 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700348 }
349 }
350
Fred Quintanaa698f422009-04-08 19:14:54 -0700351 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700352 checkAuthenticateAccountsPermission(account);
353
Fred Quintana60307342009-03-24 22:48:12 -0700354 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700355 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700356 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700357 return insertAccountIntoDatabase(account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700358 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700359 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700360 }
361 }
362
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700363 private boolean insertAccountIntoDatabase(Account account, String password, Bundle extras) {
364 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
365 db.beginTransaction();
366 try {
367 long numMatches = DatabaseUtils.longForQuery(db,
368 "select count(*) from " + TABLE_ACCOUNTS
369 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
370 new String[]{account.name, account.type});
371 if (numMatches > 0) {
372 return false;
373 }
374 ContentValues values = new ContentValues();
375 values.put(ACCOUNTS_NAME, account.name);
376 values.put(ACCOUNTS_TYPE, account.type);
377 values.put(ACCOUNTS_PASSWORD, password);
378 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
379 if (accountId < 0) {
380 return false;
381 }
382 if (extras != null) {
383 for (String key : extras.keySet()) {
384 final String value = extras.getString(key);
385 if (insertExtra(db, accountId, key, value) < 0) {
386 return false;
387 }
388 }
389 }
390 db.setTransactionSuccessful();
391 sendAccountsChangedBroadcast();
392 return true;
393 } finally {
394 db.endTransaction();
395 }
396 }
397
Fred Quintana60307342009-03-24 22:48:12 -0700398 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
399 ContentValues values = new ContentValues();
400 values.put(EXTRAS_KEY, key);
401 values.put(EXTRAS_ACCOUNTS_ID, accountId);
402 values.put(EXTRAS_VALUE, value);
403 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
404 }
405
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700406 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700407 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700408 long identityToken = clearCallingIdentity();
409 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700410 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700411 } finally {
412 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700413 }
Fred Quintana60307342009-03-24 22:48:12 -0700414 }
415
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700416 private class RemoveAccountSession extends Session {
417 final Account mAccount;
418 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
419 super(response, account.type, false /* expectActivityLaunch */);
420 mAccount = account;
421 }
422
423 protected String toDebugString(long now) {
424 return super.toDebugString(now) + ", removeAccount"
425 + ", account " + mAccount;
426 }
427
428 public void run() throws RemoteException {
429 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
430 }
431
432 public void onResult(Bundle result) {
433 if (result != null && result.containsKey(Constants.BOOLEAN_RESULT_KEY)
434 && !result.containsKey(Constants.INTENT_KEY)) {
435 final boolean removalAllowed = result.getBoolean(Constants.BOOLEAN_RESULT_KEY);
436 if (removalAllowed) {
437 removeAccount(mAccount);
438 }
439 IAccountManagerResponse response = getResponseAndClose();
440 if (response != null) {
441 Bundle result2 = new Bundle();
442 result2.putBoolean(Constants.BOOLEAN_RESULT_KEY, removalAllowed);
443 try {
444 response.onResult(result2);
445 } catch (RemoteException e) {
446 // ignore
447 }
448 }
449 }
450 super.onResult(result);
451 }
452 }
453
454 private void removeAccount(Account account) {
455 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
456 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
457 new String[]{account.name, account.type});
458 sendAccountsChangedBroadcast();
459 }
460
Fred Quintanaa698f422009-04-08 19:14:54 -0700461 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700462 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700463 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700464 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700465 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
466 db.beginTransaction();
467 try {
468 invalidateAuthToken(db, accountType, authToken);
469 db.setTransactionSuccessful();
470 } finally {
471 db.endTransaction();
472 }
Fred Quintana60307342009-03-24 22:48:12 -0700473 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700474 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700475 }
476 }
477
478 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700479 if (authToken == null || accountType == null) {
480 return;
481 }
Fred Quintana33269202009-04-20 16:05:10 -0700482 Cursor cursor = db.rawQuery(
483 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
484 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
485 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
486 + " FROM " + TABLE_ACCOUNTS
487 + " JOIN " + TABLE_AUTHTOKENS
488 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
489 + " = " + AUTHTOKENS_ACCOUNTS_ID
490 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
491 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
492 new String[]{authToken, accountType});
493 try {
494 while (cursor.moveToNext()) {
495 long authTokenId = cursor.getLong(0);
496 String accountName = cursor.getString(1);
497 String authTokenType = cursor.getString(2);
498 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700499 }
Fred Quintana33269202009-04-20 16:05:10 -0700500 } finally {
501 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700502 }
503 }
504
505 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700506 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700507 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
508 db.beginTransaction();
509 try {
Fred Quintana33269202009-04-20 16:05:10 -0700510 long accountId = getAccountId(db, account);
511 if (accountId < 0) {
512 return false;
513 }
514 db.delete(TABLE_AUTHTOKENS,
515 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
516 new String[]{type});
517 ContentValues values = new ContentValues();
518 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
519 values.put(AUTHTOKENS_TYPE, type);
520 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
521 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700522 db.setTransactionSuccessful();
523 return true;
524 }
525 return false;
526 } finally {
527 db.endTransaction();
528 }
529 }
530
Fred Quintana60307342009-03-24 22:48:12 -0700531 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
532 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
533 db.beginTransaction();
534 try {
535 long accountId = getAccountId(db, account);
536 if (accountId < 0) {
537 return null;
538 }
539 return getAuthToken(db, accountId, authTokenType);
540 } finally {
Fred Quintana60307342009-03-24 22:48:12 -0700541 db.endTransaction();
542 }
543 }
544
Fred Quintanaa698f422009-04-08 19:14:54 -0700545 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700546 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700547 long identityToken = clearCallingIdentity();
548 try {
Fred Quintana33269202009-04-20 16:05:10 -0700549 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700550 } finally {
551 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700552 }
Fred Quintana60307342009-03-24 22:48:12 -0700553 }
554
Fred Quintanaa698f422009-04-08 19:14:54 -0700555 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700556 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700557 long identityToken = clearCallingIdentity();
558 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700559 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700560 } finally {
561 restoreCallingIdentity(identityToken);
562 }
Fred Quintana60307342009-03-24 22:48:12 -0700563 }
564
Fred Quintanaa698f422009-04-08 19:14:54 -0700565 public void setPassword(Account account, String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700566 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700567 long identityToken = clearCallingIdentity();
568 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700569 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700570 } finally {
571 restoreCallingIdentity(identityToken);
572 }
Fred Quintana60307342009-03-24 22:48:12 -0700573 }
574
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700575 private void setPasswordInDB(Account account, String password) {
576 ContentValues values = new ContentValues();
577 values.put(ACCOUNTS_PASSWORD, password);
578 mOpenHelper.getWritableDatabase().update(TABLE_ACCOUNTS, values,
579 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
580 new String[]{account.name, account.type});
581 sendAccountsChangedBroadcast();
582 }
583
Fred Quintana33269202009-04-20 16:05:10 -0700584 private void sendAccountsChangedBroadcast() {
585 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
586 }
587
Fred Quintanaa698f422009-04-08 19:14:54 -0700588 public void clearPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700589 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700590 long identityToken = clearCallingIdentity();
591 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700592 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700593 } finally {
594 restoreCallingIdentity(identityToken);
595 }
Fred Quintana60307342009-03-24 22:48:12 -0700596 }
597
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700598 private void sendResult(IAccountManagerResponse response, Bundle bundle) {
599 if (response != null) {
600 try {
601 response.onResult(bundle);
602 } catch (RemoteException e) {
603 // if the caller is dead then there is no one to care about remote
604 // exceptions
605 if (Log.isLoggable(TAG, Log.VERBOSE)) {
606 Log.v(TAG, "failure while notifying response", e);
607 }
608 }
609 }
610 }
611
Fred Quintanaa698f422009-04-08 19:14:54 -0700612 public void setUserData(Account account, String key, String value) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700613 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700614 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700615 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700616 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700617 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700618 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700619 }
620 }
621
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700622 private void writeUserdataIntoDatabase(Account account, String key, String value) {
623 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
624 db.beginTransaction();
625 try {
626 long accountId = getAccountId(db, account);
627 if (accountId < 0) {
628 return;
629 }
630 long extrasId = getExtrasId(db, accountId, key);
631 if (extrasId < 0 ) {
632 extrasId = insertExtra(db, accountId, key, value);
633 if (extrasId < 0) {
634 return;
635 }
636 } else {
637 ContentValues values = new ContentValues();
638 values.put(EXTRAS_VALUE, value);
639 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
640 return;
641 }
642
643 }
644 db.setTransactionSuccessful();
645 } finally {
646 db.endTransaction();
647 }
648 }
649
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700650 private void onResult(IAccountManagerResponse response, Bundle result) {
651 try {
652 response.onResult(result);
653 } catch (RemoteException e) {
654 // if the caller is dead then there is no one to care about remote
655 // exceptions
656 if (Log.isLoggable(TAG, Log.VERBOSE)) {
657 Log.v(TAG, "failure while notifying response", e);
658 }
659 }
660 }
661
Fred Quintanaa698f422009-04-08 19:14:54 -0700662 public void getAuthToken(IAccountManagerResponse response, final Account account,
663 final String authTokenType, final boolean notifyOnAuthFailure,
664 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700665 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
666 final int callerUid = Binder.getCallingUid();
667 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
668
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700669 long identityToken = clearCallingIdentity();
670 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700671 // if the caller has permission, do the peek. otherwise go the more expensive
672 // route of starting a Session
673 if (permissionGranted) {
674 String authToken = readAuthTokenFromDatabase(account, authTokenType);
675 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700676 Bundle result = new Bundle();
677 result.putString(Constants.AUTHTOKEN_KEY, authToken);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700678 result.putString(Constants.ACCOUNT_NAME_KEY, account.name);
679 result.putString(Constants.ACCOUNT_TYPE_KEY, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700680 onResult(response, result);
681 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700682 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700683 }
684
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700685 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700686 protected String toDebugString(long now) {
687 if (loginOptions != null) loginOptions.keySet();
688 return super.toDebugString(now) + ", getAuthToken"
689 + ", " + account
690 + ", authTokenType " + authTokenType
691 + ", loginOptions " + loginOptions
692 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
693 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700694
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700695 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700696 // If the caller doesn't have permission then create and return the
697 // "grant permission" intent instead of the "getAuthToken" intent.
698 if (!permissionGranted) {
699 mAuthenticator.getAuthTokenLabel(this, authTokenType);
700 } else {
701 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
702 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700703 }
704
705 public void onResult(Bundle result) {
706 if (result != null) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700707 if (result.containsKey(Constants.AUTH_TOKEN_LABEL_KEY)) {
708 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
709 new AccountAuthenticatorResponse(this),
710 authTokenType,
711 result.getString(Constants.AUTH_TOKEN_LABEL_KEY));
712 Bundle bundle = new Bundle();
713 bundle.putParcelable(Constants.INTENT_KEY, intent);
714 onResult(bundle);
715 return;
716 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700717 String authToken = result.getString(Constants.AUTHTOKEN_KEY);
718 if (authToken != null) {
719 String name = result.getString(Constants.ACCOUNT_NAME_KEY);
720 String type = result.getString(Constants.ACCOUNT_TYPE_KEY);
721 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
722 onError(Constants.ERROR_CODE_INVALID_RESPONSE,
723 "the type and name should not be empty");
724 return;
725 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700726 saveAuthTokenToDatabase(new Account(name, type),
727 authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700728 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700729
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700730 Intent intent = result.getParcelable(Constants.INTENT_KEY);
731 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700732 doNotification(
733 account, result.getString(Constants.AUTH_FAILED_MESSAGE_KEY),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700734 intent);
735 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700736 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700737 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700738 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700739 }.bind();
740 } finally {
741 restoreCallingIdentity(identityToken);
742 }
Fred Quintana60307342009-03-24 22:48:12 -0700743 }
744
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700745 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
746 int uid = intent.getIntExtra(
747 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
748 String authTokenType = intent.getStringExtra(
749 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
750 String authTokenLabel = intent.getStringExtra(
751 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
752
753 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
754 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700755 final String titleAndSubtitle =
756 mContext.getString(R.string.permission_request_notification_with_subtitle,
757 account.name);
758 final int index = titleAndSubtitle.indexOf('\n');
759 final String title = titleAndSubtitle.substring(0, index);
760 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700761 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700762 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700763 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
764 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
765 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
766 }
767
768 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
769 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
770 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
771 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700772 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700773 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700774 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700775 }
776
777 final Context authContext;
778 try {
779 authContext = mContext.createPackageContext(
780 serviceInfo.type.packageName, 0);
781 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700782 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700783 }
784
785 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
786 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
787 intent.addCategory(
788 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
789 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
790 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
791 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
792 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
793 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
794 authContext.getString(serviceInfo.type.labelId));
795 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
796 mContext.getPackageManager().getPackagesForUid(uid));
797 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
798 return intent;
799 }
800
801 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
802 int uid) {
803 Integer id;
804 synchronized(mCredentialsPermissionNotificationIds) {
805 final Pair<Pair<Account, String>, Integer> key =
806 new Pair<Pair<Account, String>, Integer>(
807 new Pair<Account, String>(account, authTokenType), uid);
808 id = mCredentialsPermissionNotificationIds.get(key);
809 if (id == null) {
810 id = mNotificationIds.incrementAndGet();
811 mCredentialsPermissionNotificationIds.put(key, id);
812 }
813 }
814 return id;
815 }
816
817 private Integer getSigninRequiredNotificationId(Account account) {
818 Integer id;
819 synchronized(mSigninRequiredNotificationIds) {
820 id = mSigninRequiredNotificationIds.get(account);
821 if (id == null) {
822 id = mNotificationIds.incrementAndGet();
823 mSigninRequiredNotificationIds.put(account, id);
824 }
825 }
826 return id;
827 }
828
Fred Quintanaa698f422009-04-08 19:14:54 -0700829
Fred Quintana33269202009-04-20 16:05:10 -0700830 public void addAcount(final IAccountManagerResponse response, final String accountType,
831 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700832 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700833 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700834 long identityToken = clearCallingIdentity();
835 try {
836 new Session(response, accountType, expectActivityLaunch) {
837 public void run() throws RemoteException {
Fred Quintana33269202009-04-20 16:05:10 -0700838 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
839 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700840 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700841
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700842 protected String toDebugString(long now) {
843 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -0700844 + ", accountType " + accountType
845 + ", requiredFeatures "
846 + (requiredFeatures != null
847 ? TextUtils.join(",", requiredFeatures)
848 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700849 }
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 confirmCredentials(IAccountManagerResponse response,
857 final Account account, final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700858 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700859 long identityToken = clearCallingIdentity();
860 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700861 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700862 public void run() throws RemoteException {
863 mAuthenticator.confirmCredentials(this, account);
864 }
865 protected String toDebugString(long now) {
866 return super.toDebugString(now) + ", confirmCredentials"
867 + ", " + account;
868 }
869 }.bind();
870 } finally {
871 restoreCallingIdentity(identityToken);
872 }
Fred Quintana60307342009-03-24 22:48:12 -0700873 }
874
Fred Quintanaa698f422009-04-08 19:14:54 -0700875 public void confirmPassword(IAccountManagerResponse response, final Account account,
876 final String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700877 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700878 long identityToken = clearCallingIdentity();
879 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700880 new Session(response, account.type, false /* expectActivityLaunch */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700881 public void run() throws RemoteException {
882 mAuthenticator.confirmPassword(this, account, password);
883 }
884 protected String toDebugString(long now) {
885 return super.toDebugString(now) + ", confirmPassword"
886 + ", " + account;
887 }
888 }.bind();
889 } finally {
890 restoreCallingIdentity(identityToken);
891 }
Fred Quintana60307342009-03-24 22:48:12 -0700892 }
893
Fred Quintanaa698f422009-04-08 19:14:54 -0700894 public void updateCredentials(IAccountManagerResponse response, final Account account,
895 final String authTokenType, final boolean expectActivityLaunch,
896 final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700897 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700898 long identityToken = clearCallingIdentity();
899 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700900 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700901 public void run() throws RemoteException {
902 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
903 }
904 protected String toDebugString(long now) {
905 if (loginOptions != null) loginOptions.keySet();
906 return super.toDebugString(now) + ", updateCredentials"
907 + ", " + account
908 + ", authTokenType " + authTokenType
909 + ", loginOptions " + loginOptions;
910 }
911 }.bind();
912 } finally {
913 restoreCallingIdentity(identityToken);
914 }
Fred Quintana60307342009-03-24 22:48:12 -0700915 }
916
Fred Quintanaa698f422009-04-08 19:14:54 -0700917 public void editProperties(IAccountManagerResponse response, final String accountType,
918 final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700919 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700920 long identityToken = clearCallingIdentity();
921 try {
922 new Session(response, accountType, expectActivityLaunch) {
923 public void run() throws RemoteException {
924 mAuthenticator.editProperties(this, mAccountType);
925 }
926 protected String toDebugString(long now) {
927 return super.toDebugString(now) + ", editProperties"
928 + ", accountType " + accountType;
929 }
930 }.bind();
931 } finally {
932 restoreCallingIdentity(identityToken);
933 }
Fred Quintana60307342009-03-24 22:48:12 -0700934 }
935
Fred Quintana33269202009-04-20 16:05:10 -0700936 private class GetAccountsByTypeAndFeatureSession extends Session {
937 private final String[] mFeatures;
938 private volatile Account[] mAccountsOfType = null;
939 private volatile ArrayList<Account> mAccountsWithFeatures = null;
940 private volatile int mCurrentAccount = 0;
941
942 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
943 String type, String[] features) {
944 super(response, type, false /* expectActivityLaunch */);
945 mFeatures = features;
946 }
947
948 public void run() throws RemoteException {
949 mAccountsOfType = getAccountsByType(mAccountType);
950 // check whether each account matches the requested features
951 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
952 mCurrentAccount = 0;
953
954 checkAccount();
955 }
956
957 public void checkAccount() {
958 if (mCurrentAccount >= mAccountsOfType.length) {
959 sendResult();
960 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700961 }
Fred Quintana33269202009-04-20 16:05:10 -0700962
963 try {
964 mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
965 } catch (RemoteException e) {
966 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
967 }
968 }
969
970 public void onResult(Bundle result) {
971 mNumResults++;
972 if (result == null) {
973 onError(Constants.ERROR_CODE_INVALID_RESPONSE, "null bundle");
974 return;
975 }
976 if (result.getBoolean(Constants.BOOLEAN_RESULT_KEY, false)) {
977 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
978 }
979 mCurrentAccount++;
980 checkAccount();
981 }
982
983 public void sendResult() {
984 IAccountManagerResponse response = getResponseAndClose();
985 if (response != null) {
986 try {
987 Account[] accounts = new Account[mAccountsWithFeatures.size()];
988 for (int i = 0; i < accounts.length; i++) {
989 accounts[i] = mAccountsWithFeatures.get(i);
990 }
991 Bundle result = new Bundle();
992 result.putParcelableArray(Constants.ACCOUNTS_KEY, accounts);
993 response.onResult(result);
994 } catch (RemoteException e) {
995 // if the caller is dead then there is no one to care about remote exceptions
996 if (Log.isLoggable(TAG, Log.VERBOSE)) {
997 Log.v(TAG, "failure while notifying response", e);
998 }
999 }
1000 }
1001 }
1002
1003
1004 protected String toDebugString(long now) {
1005 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1006 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1007 }
1008 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001009
1010 public Account[] getAccounts(String type) {
1011 checkReadAccountsPermission();
1012 long identityToken = clearCallingIdentity();
1013 try {
1014 return getAccountsByType(type);
1015 } finally {
1016 restoreCallingIdentity(identityToken);
1017 }
1018 }
1019
1020 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001021 String type, String[] features) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001022 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001023 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -07001024 if (response != null) {
1025 try {
1026 response.onError(Constants.ERROR_CODE_BAD_ARGUMENTS, "type is null");
1027 } catch (RemoteException e) {
1028 // ignore this
1029 }
1030 }
1031 return;
1032 }
1033 long identityToken = clearCallingIdentity();
1034 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001035 if (features == null || features.length == 0) {
1036 getAccountsByType(type);
1037 return;
1038 }
Fred Quintana33269202009-04-20 16:05:10 -07001039 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1040 } finally {
1041 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001042 }
1043 }
1044
Fred Quintana60307342009-03-24 22:48:12 -07001045 private long getAccountId(SQLiteDatabase db, Account account) {
1046 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001047 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001048 try {
1049 if (cursor.moveToNext()) {
1050 return cursor.getLong(0);
1051 }
1052 return -1;
1053 } finally {
1054 cursor.close();
1055 }
1056 }
1057
1058 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1059 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1060 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1061 new String[]{key}, null, null, null);
1062 try {
1063 if (cursor.moveToNext()) {
1064 return cursor.getLong(0);
1065 }
1066 return -1;
1067 } finally {
1068 cursor.close();
1069 }
1070 }
1071
1072 private String getAuthToken(SQLiteDatabase db, long accountId, String authTokenType) {
1073 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
1074 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1075 new String[]{authTokenType},
1076 null, null, null);
1077 try {
1078 if (cursor.moveToNext()) {
1079 return cursor.getString(0);
1080 }
1081 return null;
1082 } finally {
1083 cursor.close();
1084 }
1085 }
1086
Fred Quintanaa698f422009-04-08 19:14:54 -07001087 private abstract class Session extends IAccountAuthenticatorResponse.Stub
1088 implements AuthenticatorBindHelper.Callback, IBinder.DeathRecipient {
Fred Quintana60307342009-03-24 22:48:12 -07001089 IAccountManagerResponse mResponse;
1090 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001091 final boolean mExpectActivityLaunch;
1092 final long mCreationTime;
1093
Fred Quintana33269202009-04-20 16:05:10 -07001094 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001095 private int mNumRequestContinued = 0;
1096 private int mNumErrors = 0;
1097
Fred Quintana60307342009-03-24 22:48:12 -07001098
1099 IAccountAuthenticator mAuthenticator = null;
1100
Fred Quintanaa698f422009-04-08 19:14:54 -07001101 public Session(IAccountManagerResponse response, String accountType,
1102 boolean expectActivityLaunch) {
Fred Quintana60307342009-03-24 22:48:12 -07001103 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001104 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001105 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana60307342009-03-24 22:48:12 -07001106 mResponse = response;
1107 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001108 mExpectActivityLaunch = expectActivityLaunch;
1109 mCreationTime = SystemClock.elapsedRealtime();
1110 synchronized (mSessions) {
1111 mSessions.put(toString(), this);
1112 }
1113 try {
1114 response.asBinder().linkToDeath(this, 0 /* flags */);
1115 } catch (RemoteException e) {
1116 mResponse = null;
1117 binderDied();
1118 }
Fred Quintana60307342009-03-24 22:48:12 -07001119 }
1120
Fred Quintanaa698f422009-04-08 19:14:54 -07001121 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001122 if (mResponse == null) {
1123 // this session has already been closed
1124 return null;
1125 }
Fred Quintana60307342009-03-24 22:48:12 -07001126 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001127 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001128 return response;
1129 }
1130
Fred Quintanaa698f422009-04-08 19:14:54 -07001131 private void close() {
1132 synchronized (mSessions) {
1133 if (mSessions.remove(toString()) == null) {
1134 // the session was already closed, so bail out now
1135 return;
1136 }
1137 }
1138 if (mResponse != null) {
1139 // stop listening for response deaths
1140 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1141
1142 // clear this so that we don't accidentally send any further results
1143 mResponse = null;
1144 }
1145 cancelTimeout();
1146 unbind();
1147 }
1148
1149 public void binderDied() {
1150 mResponse = null;
1151 close();
1152 }
1153
1154 protected String toDebugString() {
1155 return toDebugString(SystemClock.elapsedRealtime());
1156 }
1157
1158 protected String toDebugString(long now) {
1159 return "Session: expectLaunch " + mExpectActivityLaunch
1160 + ", connected " + (mAuthenticator != null)
1161 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1162 + "/" + mNumErrors + ")"
1163 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1164 }
1165
Fred Quintana60307342009-03-24 22:48:12 -07001166 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001167 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1168 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1169 }
Fred Quintana60307342009-03-24 22:48:12 -07001170 if (!mBindHelper.bind(mAccountType, this)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001171 Log.d(TAG, "bind attempt failed for " + toDebugString());
1172 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001173 }
1174 }
1175
1176 private void unbind() {
1177 if (mAuthenticator != null) {
1178 mAuthenticator = null;
1179 mBindHelper.unbind(this);
1180 }
1181 }
1182
1183 public void scheduleTimeout() {
1184 mMessageHandler.sendMessageDelayed(
1185 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1186 }
1187
1188 public void cancelTimeout() {
1189 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1190 }
1191
1192 public void onConnected(IBinder service) {
1193 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001194 try {
1195 run();
1196 } catch (RemoteException e) {
1197 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1198 "remote exception");
1199 }
Fred Quintana60307342009-03-24 22:48:12 -07001200 }
1201
Fred Quintanaa698f422009-04-08 19:14:54 -07001202 public abstract void run() throws RemoteException;
1203
Fred Quintana60307342009-03-24 22:48:12 -07001204 public void onDisconnected() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001205 mAuthenticator = null;
1206 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001207 if (response != null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001208 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1209 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001210 }
1211 }
1212
1213 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001214 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001215 if (response != null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001216 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1217 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001218 }
1219 }
1220
Fred Quintanaa698f422009-04-08 19:14:54 -07001221 public void onResult(Bundle result) {
1222 mNumResults++;
1223 if (result != null && !TextUtils.isEmpty(result.getString(Constants.AUTHTOKEN_KEY))) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001224 String accountName = result.getString(Constants.ACCOUNT_NAME_KEY);
1225 String accountType = result.getString(Constants.ACCOUNT_TYPE_KEY);
1226 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1227 Account account = new Account(accountName, accountType);
1228 cancelNotification(getSigninRequiredNotificationId(account));
1229 }
Fred Quintana60307342009-03-24 22:48:12 -07001230 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001231 IAccountManagerResponse response;
1232 if (mExpectActivityLaunch && result != null
1233 && result.containsKey(Constants.INTENT_KEY)) {
1234 response = mResponse;
1235 } else {
1236 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001237 }
Fred Quintana60307342009-03-24 22:48:12 -07001238 if (response != null) {
1239 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001240 if (result == null) {
1241 response.onError(Constants.ERROR_CODE_INVALID_RESPONSE,
1242 "null bundle returned");
1243 } else {
1244 response.onResult(result);
1245 }
Fred Quintana60307342009-03-24 22:48:12 -07001246 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001247 // if the caller is dead then there is no one to care about remote exceptions
1248 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1249 Log.v(TAG, "failure while notifying response", e);
1250 }
Fred Quintana60307342009-03-24 22:48:12 -07001251 }
1252 }
1253 }
Fred Quintana60307342009-03-24 22:48:12 -07001254
Fred Quintanaa698f422009-04-08 19:14:54 -07001255 public void onRequestContinued() {
1256 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001257 }
1258
1259 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001260 mNumErrors++;
1261 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1262 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001263 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001264 IAccountManagerResponse response = getResponseAndClose();
1265 if (response != null) {
1266 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1267 Log.v(TAG, "Session.onError: responding");
1268 }
1269 try {
1270 response.onError(errorCode, errorMessage);
1271 } catch (RemoteException e) {
1272 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1273 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1274 }
1275 }
1276 } else {
1277 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1278 Log.v(TAG, "Session.onError: already closed");
1279 }
Fred Quintana60307342009-03-24 22:48:12 -07001280 }
1281 }
1282 }
1283
1284 private class MessageHandler extends Handler {
1285 MessageHandler(Looper looper) {
1286 super(looper);
1287 }
1288
1289 public void handleMessage(Message msg) {
1290 if (mBindHelper.handleMessage(msg)) {
1291 return;
1292 }
1293 switch (msg.what) {
1294 case MESSAGE_TIMED_OUT:
1295 Session session = (Session)msg.obj;
1296 session.onTimedOut();
1297 break;
1298
1299 default:
1300 throw new IllegalStateException("unhandled message: " + msg.what);
1301 }
1302 }
1303 }
1304
1305 private class DatabaseHelper extends SQLiteOpenHelper {
1306 public DatabaseHelper(Context context) {
1307 super(context, DATABASE_NAME, null, DATABASE_VERSION);
1308 }
1309
1310 @Override
1311 public void onCreate(SQLiteDatabase db) {
1312 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1313 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1314 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1315 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1316 + ACCOUNTS_PASSWORD + " TEXT, "
1317 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1318
1319 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1320 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1321 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1322 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1323 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1324 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1325
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001326 createGrantsTable(db);
1327
Fred Quintana60307342009-03-24 22:48:12 -07001328 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1329 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1330 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1331 + EXTRAS_KEY + " TEXT NOT NULL, "
1332 + EXTRAS_VALUE + " TEXT, "
1333 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1334
1335 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1336 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1337 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001338
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001339 createAccountsDeletionTrigger(db);
1340 }
1341
1342 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001343 db.execSQL(""
1344 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1345 + " BEGIN"
1346 + " DELETE FROM " + TABLE_AUTHTOKENS
1347 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1348 + " DELETE FROM " + TABLE_EXTRAS
1349 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001350 + " DELETE FROM " + TABLE_GRANTS
1351 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001352 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001353 }
1354
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001355 private void createGrantsTable(SQLiteDatabase db) {
1356 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1357 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1358 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1359 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1360 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1361 + "," + GRANTS_GRANTEE_UID + "))");
1362 }
1363
Fred Quintana60307342009-03-24 22:48:12 -07001364 @Override
1365 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001366 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001367
Fred Quintanaa698f422009-04-08 19:14:54 -07001368 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001369 // no longer need to do anything since the work is done
1370 // when upgrading from version 2
1371 oldVersion++;
1372 }
1373
1374 if (oldVersion == 2) {
1375 createGrantsTable(db);
1376 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1377 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001378 oldVersion++;
1379 }
Fred Quintana60307342009-03-24 22:48:12 -07001380 }
1381
1382 @Override
1383 public void onOpen(SQLiteDatabase db) {
1384 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1385 }
1386 }
1387
1388 private void setMetaValue(String key, String value) {
1389 ContentValues values = new ContentValues();
1390 values.put(META_KEY, key);
1391 values.put(META_VALUE, value);
1392 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1393 }
1394
1395 private String getMetaValue(String key) {
1396 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1397 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1398 try {
1399 if (c.moveToNext()) {
1400 return c.getString(0);
1401 }
1402 return null;
1403 } finally {
1404 c.close();
1405 }
1406 }
1407
1408 private class SimWatcher extends BroadcastReceiver {
1409 public SimWatcher(Context context) {
1410 // Re-scan the SIM card when the SIM state changes, and also if
1411 // the disk recovers from a full state (we may have failed to handle
1412 // things properly while the disk was full).
1413 final IntentFilter filter = new IntentFilter();
1414 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1415 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1416 context.registerReceiver(this, filter);
1417 }
1418
1419 /**
1420 * Compare the IMSI to the one stored in the login service's
1421 * database. If they differ, erase all passwords and
1422 * authtokens (and store the new IMSI).
1423 */
1424 @Override
1425 public void onReceive(Context context, Intent intent) {
1426 // Check IMSI on every update; nothing happens if the IMSI is missing or unchanged.
1427 String imsi = ((TelephonyManager) context.getSystemService(
1428 Context.TELEPHONY_SERVICE)).getSubscriberId();
1429 if (TextUtils.isEmpty(imsi)) return;
1430
1431 String storedImsi = getMetaValue("imsi");
1432
1433 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1434 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1435 }
1436
jsh5b462472009-09-01 16:13:55 -07001437 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001438 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1439 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001440 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1441 db.beginTransaction();
1442 try {
1443 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1444 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001445 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001446 db.setTransactionSuccessful();
1447 } finally {
1448 db.endTransaction();
1449 }
1450 }
1451 setMetaValue("imsi", imsi);
1452 }
1453 }
1454
1455 public IBinder onBind(Intent intent) {
1456 return asBinder();
1457 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001458
1459 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1460 synchronized (mSessions) {
1461 final long now = SystemClock.elapsedRealtime();
1462 fout.println("AccountManagerService: " + mSessions.size() + " sessions");
1463 for (Session session : mSessions.values()) {
1464 fout.println(" " + session.toDebugString(now));
1465 }
1466 }
1467
1468 fout.println();
1469
1470 mAuthenticatorCache.dump(fd, fout, args);
1471 }
1472
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001473 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001474 long identityToken = clearCallingIdentity();
1475 try {
1476 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1477 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1478 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001479
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001480 if (intent.getComponent() != null &&
1481 GrantCredentialsPermissionActivity.class.getName().equals(
1482 intent.getComponent().getClassName())) {
1483 createNoCredentialsPermissionNotification(account, intent);
1484 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001485 final Integer notificationId = getSigninRequiredNotificationId(account);
1486 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001487 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1488 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001489 final String notificationTitleFormat =
1490 mContext.getText(R.string.notification_title).toString();
1491 n.setLatestEventInfo(mContext,
1492 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001493 message, PendingIntent.getActivity(
1494 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1495 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001496 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001497 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001498 } finally {
1499 restoreCallingIdentity(identityToken);
1500 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001501 }
1502
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001503 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001504 long identityToken = clearCallingIdentity();
1505 try {
1506 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001507 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001508 } finally {
1509 restoreCallingIdentity(identityToken);
1510 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001511 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001512
1513 private void checkBinderPermission(String permission) {
1514 final int uid = Binder.getCallingUid();
1515 if (mContext.checkCallingOrSelfPermission(permission) !=
1516 PackageManager.PERMISSION_GRANTED) {
1517 String msg = "caller uid " + uid + " lacks " + permission;
1518 Log.w(TAG, msg);
1519 throw new SecurityException(msg);
1520 }
1521 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1522 Log.v(TAG, "caller uid " + uid + " has " + permission);
1523 }
1524 }
1525
Fred Quintana7be59642009-08-24 18:29:25 -07001526 private boolean inSystemImage(int callerUid) {
1527 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1528 for (String name : packages) {
1529 try {
1530 PackageInfo packageInfo =
1531 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1532 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1533 return true;
1534 }
1535 } catch (PackageManager.NameNotFoundException e) {
1536 return false;
1537 }
1538 }
1539 return false;
1540 }
1541
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001542 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001543 final boolean fromAuthenticator = hasAuthenticatorUid(account.type, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001544 final boolean hasExplicitGrants = hasExplicitlyGrantedPermission(account, authTokenType);
1545 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1546 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1547 + callerUid + ", account " + account
1548 + ": is authenticator? " + fromAuthenticator
1549 + ", has explicit permission? " + hasExplicitGrants);
1550 }
Fred Quintana7be59642009-08-24 18:29:25 -07001551 return fromAuthenticator || hasExplicitGrants || inSystemImage(callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001552 }
1553
1554 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
1555 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1556 mAuthenticatorCache.getAllServices()) {
1557 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001558 return (serviceInfo.uid == callingUid) ||
1559 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1560 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001561 }
1562 }
1563 return false;
1564 }
1565
1566 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1567 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1568 return true;
1569 }
1570 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1571 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001572 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001573 final boolean permissionGranted =
1574 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1575 if (!permissionGranted && isDebuggableMonkeyBuild) {
1576 // TODO: Skip this check when running automated tests. Replace this
1577 // with a more general solution.
1578 Log.w(TAG, "no credentials permission for usage of " + account + ", "
1579 + authTokenType + " by uid " + Binder.getCallingUid()
1580 + " but ignoring since this is a monkey build");
1581 return true;
1582 }
1583 return permissionGranted;
1584 }
1585
1586 private void checkCallingUidAgainstAuthenticator(Account account) {
1587 final int uid = Binder.getCallingUid();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001588 if (!hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001589 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1590 Log.w(TAG, msg);
1591 throw new SecurityException(msg);
1592 }
1593 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1594 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1595 }
1596 }
1597
1598 private void checkAuthenticateAccountsPermission(Account account) {
1599 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1600 checkCallingUidAgainstAuthenticator(account);
1601 }
1602
1603 private void checkReadAccountsPermission() {
1604 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1605 }
1606
1607 private void checkManageAccountsPermission() {
1608 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1609 }
1610
1611 /**
1612 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1613 * <p>
1614 * Although this is public it can only be accessed via the AccountManagerService object
1615 * which is in the system. This means we don't need to protect it with permissions.
1616 * @hide
1617 */
1618 public void grantAppPermission(Account account, String authTokenType, int uid) {
1619 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1620 db.beginTransaction();
1621 try {
1622 long accountId = getAccountId(db, account);
1623 if (accountId >= 0) {
1624 ContentValues values = new ContentValues();
1625 values.put(GRANTS_ACCOUNTS_ID, accountId);
1626 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1627 values.put(GRANTS_GRANTEE_UID, uid);
1628 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1629 db.setTransactionSuccessful();
1630 }
1631 } finally {
1632 db.endTransaction();
1633 }
1634 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1635 }
1636
1637 /**
1638 * Don't allow callers with the given uid permission to get credentials for
1639 * account/authTokenType.
1640 * <p>
1641 * Although this is public it can only be accessed via the AccountManagerService object
1642 * which is in the system. This means we don't need to protect it with permissions.
1643 * @hide
1644 */
1645 public void revokeAppPermission(Account account, String authTokenType, int uid) {
1646 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1647 db.beginTransaction();
1648 try {
1649 long accountId = getAccountId(db, account);
1650 if (accountId >= 0) {
1651 db.delete(TABLE_GRANTS,
1652 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1653 + GRANTS_GRANTEE_UID + "=?",
1654 new String[]{String.valueOf(accountId), authTokenType,
1655 String.valueOf(uid)});
1656 db.setTransactionSuccessful();
1657 }
1658 } finally {
1659 db.endTransaction();
1660 }
1661 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1662 }
Fred Quintana60307342009-03-24 22:48:12 -07001663}