blob: 3b39ae4398c65ac12b66500010d43e482a73f5dd [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 {
Jim Miller50c05f32009-09-21 19:07:44 -070076 private static final String GOOGLE_ACCOUNT_TYPE = "com.google.GAIA";
77
78 private static final String NO_BROADCAST_FLAG = "nobroadcast";
79
Fred Quintana60307342009-03-24 22:48:12 -070080 private static final String TAG = "AccountManagerService";
81
82 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
83 private static final String DATABASE_NAME = "accounts.db";
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070084 private static final int DATABASE_VERSION = 3;
Fred Quintana60307342009-03-24 22:48:12 -070085
86 private final Context mContext;
87
88 private HandlerThread mMessageThread;
89 private final MessageHandler mMessageHandler;
90
91 // Messages that can be sent on mHandler
92 private static final int MESSAGE_TIMED_OUT = 3;
93 private static final int MESSAGE_CONNECTED = 7;
94 private static final int MESSAGE_DISCONNECTED = 8;
95
96 private final AccountAuthenticatorCache mAuthenticatorCache;
97 private final AuthenticatorBindHelper mBindHelper;
Fred Quintana60307342009-03-24 22:48:12 -070098 private final DatabaseHelper mOpenHelper;
99 private final SimWatcher mSimWatcher;
100
101 private static final String TABLE_ACCOUNTS = "accounts";
102 private static final String ACCOUNTS_ID = "_id";
103 private static final String ACCOUNTS_NAME = "name";
104 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700105 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700106 private static final String ACCOUNTS_PASSWORD = "password";
107
108 private static final String TABLE_AUTHTOKENS = "authtokens";
109 private static final String AUTHTOKENS_ID = "_id";
110 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
111 private static final String AUTHTOKENS_TYPE = "type";
112 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
113
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700114 private static final String TABLE_GRANTS = "grants";
115 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
116 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
117 private static final String GRANTS_GRANTEE_UID = "uid";
118
Fred Quintana60307342009-03-24 22:48:12 -0700119 private static final String TABLE_EXTRAS = "extras";
120 private static final String EXTRAS_ID = "_id";
121 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
122 private static final String EXTRAS_KEY = "key";
123 private static final String EXTRAS_VALUE = "value";
124
125 private static final String TABLE_META = "meta";
126 private static final String META_KEY = "key";
127 private static final String META_VALUE = "value";
128
129 private static final String[] ACCOUNT_NAME_TYPE_PROJECTION =
130 new String[]{ACCOUNTS_ID, ACCOUNTS_NAME, ACCOUNTS_TYPE};
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700131 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
132 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700133 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700134
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700135 private static final String COUNT_OF_MATCHING_GRANTS = ""
136 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
137 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
138 + " AND " + GRANTS_GRANTEE_UID + "=?"
139 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
140 + " AND " + ACCOUNTS_NAME + "=?"
141 + " AND " + ACCOUNTS_TYPE + "=?";
142
Fred Quintanaa698f422009-04-08 19:14:54 -0700143 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700144 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
145
146 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
147 mCredentialsPermissionNotificationIds =
148 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
149 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
150 new HashMap<Account, Integer>();
151 private static AtomicReference<AccountManagerService> sThis =
152 new AtomicReference<AccountManagerService>();
153
154 private static final boolean isDebuggableMonkeyBuild =
155 SystemProperties.getBoolean("ro.monkey", false)
156 && SystemProperties.getBoolean("ro.debuggable", false);
Fred Quintana7be59642009-08-24 18:29:25 -0700157
158 static {
159 ACCOUNTS_CHANGED_INTENT = new Intent(Constants.LOGIN_ACCOUNTS_CHANGED_ACTION);
160 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
161 }
162
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700163 /**
164 * This should only be called by system code. One should only call this after the service
165 * has started.
166 * @return a reference to the AccountManagerService instance
167 * @hide
168 */
169 public static AccountManagerService getSingleton() {
170 return sThis.get();
171 }
Fred Quintana60307342009-03-24 22:48:12 -0700172
173 public class AuthTokenKey {
174 public final Account mAccount;
175 public final String mAuthTokenType;
176 private final int mHashCode;
177
178 public AuthTokenKey(Account account, String authTokenType) {
179 mAccount = account;
180 mAuthTokenType = authTokenType;
181 mHashCode = computeHashCode();
182 }
183
184 public boolean equals(Object o) {
185 if (o == this) {
186 return true;
187 }
188 if (!(o instanceof AuthTokenKey)) {
189 return false;
190 }
191 AuthTokenKey other = (AuthTokenKey)o;
192 if (!mAccount.equals(other.mAccount)) {
193 return false;
194 }
195 return (mAuthTokenType == null)
196 ? other.mAuthTokenType == null
197 : mAuthTokenType.equals(other.mAuthTokenType);
198 }
199
200 private int computeHashCode() {
201 int result = 17;
202 result = 31 * result + mAccount.hashCode();
203 result = 31 * result + ((mAuthTokenType == null) ? 0 : mAuthTokenType.hashCode());
204 return result;
205 }
206
207 public int hashCode() {
208 return mHashCode;
209 }
210 }
211
212 public AccountManagerService(Context context) {
213 mContext = context;
214
215 mOpenHelper = new DatabaseHelper(mContext);
216
217 mMessageThread = new HandlerThread("AccountManagerService");
218 mMessageThread.start();
219 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
220
221 mAuthenticatorCache = new AccountAuthenticatorCache(mContext);
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700222 mAuthenticatorCache.setListener(this);
Fred Quintana60307342009-03-24 22:48:12 -0700223 mBindHelper = new AuthenticatorBindHelper(mContext, mAuthenticatorCache, mMessageHandler,
224 MESSAGE_CONNECTED, MESSAGE_DISCONNECTED);
225
226 mSimWatcher = new SimWatcher(mContext);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700227 sThis.set(this);
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700228
229 onRegisteredServicesCacheChanged();
230 }
231
232 public void onRegisteredServicesCacheChanged() {
233 boolean accountDeleted = false;
234 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
235 Cursor cursor = db.query(TABLE_ACCOUNTS,
236 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
237 null, null, null, null, null);
238 try {
239 while (cursor.moveToNext()) {
240 final long accountId = cursor.getLong(0);
241 final String accountType = cursor.getString(1);
242 final String accountName = cursor.getString(2);
243 if (mAuthenticatorCache.getServiceInfo(AuthenticatorDescription.newKey(accountType))
244 == null) {
245 Log.d(TAG, "deleting account " + accountName + " because type "
246 + accountType + " no longer has a registered authenticator");
247 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
248 accountDeleted= true;
249 }
250 }
251 } finally {
252 cursor.close();
253 if (accountDeleted) {
254 sendAccountsChangedBroadcast();
255 }
256 }
Fred Quintana60307342009-03-24 22:48:12 -0700257 }
258
Fred Quintanaa698f422009-04-08 19:14:54 -0700259 public String getPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700260 checkAuthenticateAccountsPermission(account);
261
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700262 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700263 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700264 return readPasswordFromDatabase(account);
265 } finally {
266 restoreCallingIdentity(identityToken);
267 }
268 }
269
270 private String readPasswordFromDatabase(Account account) {
271 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
272 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
273 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
274 new String[]{account.name, account.type}, null, null, null);
275 try {
276 if (cursor.moveToNext()) {
277 return cursor.getString(0);
278 }
279 return null;
280 } finally {
281 cursor.close();
282 }
283 }
284
285 public String getUserData(Account account, String key) {
286 checkAuthenticateAccountsPermission(account);
287 long identityToken = clearCallingIdentity();
288 try {
289 return readUserDataFromDatabase(account, key);
290 } finally {
291 restoreCallingIdentity(identityToken);
292 }
293 }
294
295 private String readUserDataFromDatabase(Account account, String key) {
296 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700297 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_VALUE},
298 EXTRAS_ACCOUNTS_ID
299 + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
300 + EXTRAS_KEY + "=?",
301 new String[]{account.name, account.type, key}, null, null, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700302 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700303 if (cursor.moveToNext()) {
304 return cursor.getString(0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700305 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700306 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700307 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700308 cursor.close();
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 {
Jim Miller50c05f32009-09-21 19:07:44 -0700367 boolean noBroadcast = false;
368 if (account.type.equals(GOOGLE_ACCOUNT_TYPE)) {
369 // Look for the 'nobroadcast' flag and remove it since we don't want it to persist
370 // in the db.
371 noBroadcast = extras.getBoolean(NO_BROADCAST_FLAG, false);
372 extras.remove(NO_BROADCAST_FLAG);
373 }
374
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700375 long numMatches = DatabaseUtils.longForQuery(db,
376 "select count(*) from " + TABLE_ACCOUNTS
377 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
378 new String[]{account.name, account.type});
379 if (numMatches > 0) {
380 return false;
381 }
382 ContentValues values = new ContentValues();
383 values.put(ACCOUNTS_NAME, account.name);
384 values.put(ACCOUNTS_TYPE, account.type);
385 values.put(ACCOUNTS_PASSWORD, password);
386 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
387 if (accountId < 0) {
388 return false;
389 }
390 if (extras != null) {
391 for (String key : extras.keySet()) {
392 final String value = extras.getString(key);
393 if (insertExtra(db, accountId, key, value) < 0) {
394 return false;
395 }
396 }
397 }
398 db.setTransactionSuccessful();
Jim Miller50c05f32009-09-21 19:07:44 -0700399 if (!noBroadcast) {
400 sendAccountsChangedBroadcast();
401 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700402 return true;
403 } finally {
404 db.endTransaction();
405 }
406 }
407
Fred Quintana60307342009-03-24 22:48:12 -0700408 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
409 ContentValues values = new ContentValues();
410 values.put(EXTRAS_KEY, key);
411 values.put(EXTRAS_ACCOUNTS_ID, accountId);
412 values.put(EXTRAS_VALUE, value);
413 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
414 }
415
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700416 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700417 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700418 long identityToken = clearCallingIdentity();
419 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700420 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700421 } finally {
422 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700423 }
Fred Quintana60307342009-03-24 22:48:12 -0700424 }
425
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700426 private class RemoveAccountSession extends Session {
427 final Account mAccount;
428 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
429 super(response, account.type, false /* expectActivityLaunch */);
430 mAccount = account;
431 }
432
433 protected String toDebugString(long now) {
434 return super.toDebugString(now) + ", removeAccount"
435 + ", account " + mAccount;
436 }
437
438 public void run() throws RemoteException {
439 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
440 }
441
442 public void onResult(Bundle result) {
443 if (result != null && result.containsKey(Constants.BOOLEAN_RESULT_KEY)
444 && !result.containsKey(Constants.INTENT_KEY)) {
445 final boolean removalAllowed = result.getBoolean(Constants.BOOLEAN_RESULT_KEY);
446 if (removalAllowed) {
447 removeAccount(mAccount);
448 }
449 IAccountManagerResponse response = getResponseAndClose();
450 if (response != null) {
451 Bundle result2 = new Bundle();
452 result2.putBoolean(Constants.BOOLEAN_RESULT_KEY, removalAllowed);
453 try {
454 response.onResult(result2);
455 } catch (RemoteException e) {
456 // ignore
457 }
458 }
459 }
460 super.onResult(result);
461 }
462 }
463
464 private void removeAccount(Account account) {
465 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
466 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
467 new String[]{account.name, account.type});
468 sendAccountsChangedBroadcast();
469 }
470
Fred Quintanaa698f422009-04-08 19:14:54 -0700471 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700472 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700473 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700474 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700475 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
476 db.beginTransaction();
477 try {
478 invalidateAuthToken(db, accountType, authToken);
479 db.setTransactionSuccessful();
480 } finally {
481 db.endTransaction();
482 }
Fred Quintana60307342009-03-24 22:48:12 -0700483 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700484 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700485 }
486 }
487
488 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700489 if (authToken == null || accountType == null) {
490 return;
491 }
Fred Quintana33269202009-04-20 16:05:10 -0700492 Cursor cursor = db.rawQuery(
493 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
494 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
495 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
496 + " FROM " + TABLE_ACCOUNTS
497 + " JOIN " + TABLE_AUTHTOKENS
498 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
499 + " = " + AUTHTOKENS_ACCOUNTS_ID
500 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
501 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
502 new String[]{authToken, accountType});
503 try {
504 while (cursor.moveToNext()) {
505 long authTokenId = cursor.getLong(0);
506 String accountName = cursor.getString(1);
507 String authTokenType = cursor.getString(2);
508 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700509 }
Fred Quintana33269202009-04-20 16:05:10 -0700510 } finally {
511 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700512 }
513 }
514
515 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700516 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700517 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
518 db.beginTransaction();
519 try {
Fred Quintana33269202009-04-20 16:05:10 -0700520 long accountId = getAccountId(db, account);
521 if (accountId < 0) {
522 return false;
523 }
524 db.delete(TABLE_AUTHTOKENS,
525 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
526 new String[]{type});
527 ContentValues values = new ContentValues();
528 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
529 values.put(AUTHTOKENS_TYPE, type);
530 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
531 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700532 db.setTransactionSuccessful();
533 return true;
534 }
535 return false;
536 } finally {
537 db.endTransaction();
538 }
539 }
540
Fred Quintana60307342009-03-24 22:48:12 -0700541 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
542 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700543 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
544 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
545 + AUTHTOKENS_TYPE + "=?",
546 new String[]{account.name, account.type, authTokenType},
547 null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700548 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700549 if (cursor.moveToNext()) {
550 return cursor.getString(0);
Fred Quintana60307342009-03-24 22:48:12 -0700551 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700552 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700553 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700554 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700555 }
556 }
557
Fred Quintanaa698f422009-04-08 19:14:54 -0700558 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700559 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700560 long identityToken = clearCallingIdentity();
561 try {
Fred Quintana33269202009-04-20 16:05:10 -0700562 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700563 } finally {
564 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700565 }
Fred Quintana60307342009-03-24 22:48:12 -0700566 }
567
Fred Quintanaa698f422009-04-08 19:14:54 -0700568 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700569 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700570 long identityToken = clearCallingIdentity();
571 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700572 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700573 } finally {
574 restoreCallingIdentity(identityToken);
575 }
Fred Quintana60307342009-03-24 22:48:12 -0700576 }
577
Fred Quintanaa698f422009-04-08 19:14:54 -0700578 public void setPassword(Account account, String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700579 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700580 long identityToken = clearCallingIdentity();
581 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700582 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700583 } finally {
584 restoreCallingIdentity(identityToken);
585 }
Fred Quintana60307342009-03-24 22:48:12 -0700586 }
587
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700588 private void setPasswordInDB(Account account, String password) {
589 ContentValues values = new ContentValues();
590 values.put(ACCOUNTS_PASSWORD, password);
591 mOpenHelper.getWritableDatabase().update(TABLE_ACCOUNTS, values,
592 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
593 new String[]{account.name, account.type});
594 sendAccountsChangedBroadcast();
595 }
596
Fred Quintana33269202009-04-20 16:05:10 -0700597 private void sendAccountsChangedBroadcast() {
598 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
599 }
600
Fred Quintanaa698f422009-04-08 19:14:54 -0700601 public void clearPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700602 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700603 long identityToken = clearCallingIdentity();
604 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700605 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700606 } finally {
607 restoreCallingIdentity(identityToken);
608 }
Fred Quintana60307342009-03-24 22:48:12 -0700609 }
610
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700611 private void sendResult(IAccountManagerResponse response, Bundle bundle) {
612 if (response != null) {
613 try {
614 response.onResult(bundle);
615 } catch (RemoteException e) {
616 // if the caller is dead then there is no one to care about remote
617 // exceptions
618 if (Log.isLoggable(TAG, Log.VERBOSE)) {
619 Log.v(TAG, "failure while notifying response", e);
620 }
621 }
622 }
623 }
624
Fred Quintanaa698f422009-04-08 19:14:54 -0700625 public void setUserData(Account account, String key, String value) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700626 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700627 long identityToken = clearCallingIdentity();
Jim Miller50c05f32009-09-21 19:07:44 -0700628 if (account.type.equals(GOOGLE_ACCOUNT_TYPE) && key.equals("broadcast")) {
629 sendAccountsChangedBroadcast();
630 return;
631 }
Fred Quintana60307342009-03-24 22:48:12 -0700632 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700633 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700634 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700635 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700636 }
637 }
638
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700639 private void writeUserdataIntoDatabase(Account account, String key, String value) {
640 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
641 db.beginTransaction();
642 try {
643 long accountId = getAccountId(db, account);
644 if (accountId < 0) {
645 return;
646 }
647 long extrasId = getExtrasId(db, accountId, key);
648 if (extrasId < 0 ) {
649 extrasId = insertExtra(db, accountId, key, value);
650 if (extrasId < 0) {
651 return;
652 }
653 } else {
654 ContentValues values = new ContentValues();
655 values.put(EXTRAS_VALUE, value);
656 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
657 return;
658 }
659
660 }
661 db.setTransactionSuccessful();
662 } finally {
663 db.endTransaction();
664 }
665 }
666
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700667 private void onResult(IAccountManagerResponse response, Bundle result) {
668 try {
669 response.onResult(result);
670 } catch (RemoteException e) {
671 // if the caller is dead then there is no one to care about remote
672 // exceptions
673 if (Log.isLoggable(TAG, Log.VERBOSE)) {
674 Log.v(TAG, "failure while notifying response", e);
675 }
676 }
677 }
678
Fred Quintanaa698f422009-04-08 19:14:54 -0700679 public void getAuthToken(IAccountManagerResponse response, final Account account,
680 final String authTokenType, final boolean notifyOnAuthFailure,
681 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700682 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
683 final int callerUid = Binder.getCallingUid();
684 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
685
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700686 long identityToken = clearCallingIdentity();
687 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700688 // if the caller has permission, do the peek. otherwise go the more expensive
689 // route of starting a Session
690 if (permissionGranted) {
691 String authToken = readAuthTokenFromDatabase(account, authTokenType);
692 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700693 Bundle result = new Bundle();
694 result.putString(Constants.AUTHTOKEN_KEY, authToken);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700695 result.putString(Constants.ACCOUNT_NAME_KEY, account.name);
696 result.putString(Constants.ACCOUNT_TYPE_KEY, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700697 onResult(response, result);
698 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700699 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700700 }
701
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700702 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700703 protected String toDebugString(long now) {
704 if (loginOptions != null) loginOptions.keySet();
705 return super.toDebugString(now) + ", getAuthToken"
706 + ", " + account
707 + ", authTokenType " + authTokenType
708 + ", loginOptions " + loginOptions
709 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
710 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700711
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700712 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700713 // If the caller doesn't have permission then create and return the
714 // "grant permission" intent instead of the "getAuthToken" intent.
715 if (!permissionGranted) {
716 mAuthenticator.getAuthTokenLabel(this, authTokenType);
717 } else {
718 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
719 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700720 }
721
722 public void onResult(Bundle result) {
723 if (result != null) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700724 if (result.containsKey(Constants.AUTH_TOKEN_LABEL_KEY)) {
725 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
726 new AccountAuthenticatorResponse(this),
727 authTokenType,
728 result.getString(Constants.AUTH_TOKEN_LABEL_KEY));
729 Bundle bundle = new Bundle();
730 bundle.putParcelable(Constants.INTENT_KEY, intent);
731 onResult(bundle);
732 return;
733 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700734 String authToken = result.getString(Constants.AUTHTOKEN_KEY);
735 if (authToken != null) {
736 String name = result.getString(Constants.ACCOUNT_NAME_KEY);
737 String type = result.getString(Constants.ACCOUNT_TYPE_KEY);
738 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
739 onError(Constants.ERROR_CODE_INVALID_RESPONSE,
740 "the type and name should not be empty");
741 return;
742 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700743 saveAuthTokenToDatabase(new Account(name, type),
744 authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700745 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700746
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700747 Intent intent = result.getParcelable(Constants.INTENT_KEY);
748 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700749 doNotification(
750 account, result.getString(Constants.AUTH_FAILED_MESSAGE_KEY),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700751 intent);
752 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700753 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700754 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700755 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700756 }.bind();
757 } finally {
758 restoreCallingIdentity(identityToken);
759 }
Fred Quintana60307342009-03-24 22:48:12 -0700760 }
761
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700762 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
763 int uid = intent.getIntExtra(
764 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
765 String authTokenType = intent.getStringExtra(
766 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
767 String authTokenLabel = intent.getStringExtra(
768 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
769
770 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
771 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700772 final String titleAndSubtitle =
773 mContext.getString(R.string.permission_request_notification_with_subtitle,
774 account.name);
775 final int index = titleAndSubtitle.indexOf('\n');
776 final String title = titleAndSubtitle.substring(0, index);
777 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700778 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700779 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700780 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
781 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
782 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
783 }
784
785 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
786 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
787 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
788 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700789 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700790 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700791 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700792 }
793
794 final Context authContext;
795 try {
796 authContext = mContext.createPackageContext(
797 serviceInfo.type.packageName, 0);
798 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700799 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700800 }
801
802 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
803 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
804 intent.addCategory(
805 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
806 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
807 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
808 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
809 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
810 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
811 authContext.getString(serviceInfo.type.labelId));
812 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
813 mContext.getPackageManager().getPackagesForUid(uid));
814 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
815 return intent;
816 }
817
818 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
819 int uid) {
820 Integer id;
821 synchronized(mCredentialsPermissionNotificationIds) {
822 final Pair<Pair<Account, String>, Integer> key =
823 new Pair<Pair<Account, String>, Integer>(
824 new Pair<Account, String>(account, authTokenType), uid);
825 id = mCredentialsPermissionNotificationIds.get(key);
826 if (id == null) {
827 id = mNotificationIds.incrementAndGet();
828 mCredentialsPermissionNotificationIds.put(key, id);
829 }
830 }
831 return id;
832 }
833
834 private Integer getSigninRequiredNotificationId(Account account) {
835 Integer id;
836 synchronized(mSigninRequiredNotificationIds) {
837 id = mSigninRequiredNotificationIds.get(account);
838 if (id == null) {
839 id = mNotificationIds.incrementAndGet();
840 mSigninRequiredNotificationIds.put(account, id);
841 }
842 }
843 return id;
844 }
845
Fred Quintanaa698f422009-04-08 19:14:54 -0700846
Fred Quintana33269202009-04-20 16:05:10 -0700847 public void addAcount(final IAccountManagerResponse response, final String accountType,
848 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700849 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700850 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700851 long identityToken = clearCallingIdentity();
852 try {
853 new Session(response, accountType, expectActivityLaunch) {
854 public void run() throws RemoteException {
Fred Quintana33269202009-04-20 16:05:10 -0700855 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
856 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700857 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700858
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700859 protected String toDebugString(long now) {
860 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -0700861 + ", accountType " + accountType
862 + ", requiredFeatures "
863 + (requiredFeatures != null
864 ? TextUtils.join(",", requiredFeatures)
865 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700866 }
867 }.bind();
868 } finally {
869 restoreCallingIdentity(identityToken);
870 }
Fred Quintana60307342009-03-24 22:48:12 -0700871 }
872
Fred Quintanaa698f422009-04-08 19:14:54 -0700873 public void confirmCredentials(IAccountManagerResponse response,
874 final Account account, final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700875 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700876 long identityToken = clearCallingIdentity();
877 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700878 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700879 public void run() throws RemoteException {
880 mAuthenticator.confirmCredentials(this, account);
881 }
882 protected String toDebugString(long now) {
883 return super.toDebugString(now) + ", confirmCredentials"
884 + ", " + account;
885 }
886 }.bind();
887 } finally {
888 restoreCallingIdentity(identityToken);
889 }
Fred Quintana60307342009-03-24 22:48:12 -0700890 }
891
Fred Quintanaa698f422009-04-08 19:14:54 -0700892 public void confirmPassword(IAccountManagerResponse response, final Account account,
893 final String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700894 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700895 long identityToken = clearCallingIdentity();
896 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700897 new Session(response, account.type, false /* expectActivityLaunch */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700898 public void run() throws RemoteException {
899 mAuthenticator.confirmPassword(this, account, password);
900 }
901 protected String toDebugString(long now) {
902 return super.toDebugString(now) + ", confirmPassword"
903 + ", " + account;
904 }
905 }.bind();
906 } finally {
907 restoreCallingIdentity(identityToken);
908 }
Fred Quintana60307342009-03-24 22:48:12 -0700909 }
910
Fred Quintanaa698f422009-04-08 19:14:54 -0700911 public void updateCredentials(IAccountManagerResponse response, final Account account,
912 final String authTokenType, final boolean expectActivityLaunch,
913 final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700914 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700915 long identityToken = clearCallingIdentity();
916 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700917 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700918 public void run() throws RemoteException {
919 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
920 }
921 protected String toDebugString(long now) {
922 if (loginOptions != null) loginOptions.keySet();
923 return super.toDebugString(now) + ", updateCredentials"
924 + ", " + account
925 + ", authTokenType " + authTokenType
926 + ", loginOptions " + loginOptions;
927 }
928 }.bind();
929 } finally {
930 restoreCallingIdentity(identityToken);
931 }
Fred Quintana60307342009-03-24 22:48:12 -0700932 }
933
Fred Quintanaa698f422009-04-08 19:14:54 -0700934 public void editProperties(IAccountManagerResponse response, final String accountType,
935 final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700936 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700937 long identityToken = clearCallingIdentity();
938 try {
939 new Session(response, accountType, expectActivityLaunch) {
940 public void run() throws RemoteException {
941 mAuthenticator.editProperties(this, mAccountType);
942 }
943 protected String toDebugString(long now) {
944 return super.toDebugString(now) + ", editProperties"
945 + ", accountType " + accountType;
946 }
947 }.bind();
948 } finally {
949 restoreCallingIdentity(identityToken);
950 }
Fred Quintana60307342009-03-24 22:48:12 -0700951 }
952
Fred Quintana33269202009-04-20 16:05:10 -0700953 private class GetAccountsByTypeAndFeatureSession extends Session {
954 private final String[] mFeatures;
955 private volatile Account[] mAccountsOfType = null;
956 private volatile ArrayList<Account> mAccountsWithFeatures = null;
957 private volatile int mCurrentAccount = 0;
958
959 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
960 String type, String[] features) {
961 super(response, type, false /* expectActivityLaunch */);
962 mFeatures = features;
963 }
964
965 public void run() throws RemoteException {
966 mAccountsOfType = getAccountsByType(mAccountType);
967 // check whether each account matches the requested features
968 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
969 mCurrentAccount = 0;
970
971 checkAccount();
972 }
973
974 public void checkAccount() {
975 if (mCurrentAccount >= mAccountsOfType.length) {
976 sendResult();
977 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700978 }
Fred Quintana33269202009-04-20 16:05:10 -0700979
980 try {
981 mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
982 } catch (RemoteException e) {
983 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
984 }
985 }
986
987 public void onResult(Bundle result) {
988 mNumResults++;
989 if (result == null) {
990 onError(Constants.ERROR_CODE_INVALID_RESPONSE, "null bundle");
991 return;
992 }
993 if (result.getBoolean(Constants.BOOLEAN_RESULT_KEY, false)) {
994 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
995 }
996 mCurrentAccount++;
997 checkAccount();
998 }
999
1000 public void sendResult() {
1001 IAccountManagerResponse response = getResponseAndClose();
1002 if (response != null) {
1003 try {
1004 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1005 for (int i = 0; i < accounts.length; i++) {
1006 accounts[i] = mAccountsWithFeatures.get(i);
1007 }
1008 Bundle result = new Bundle();
1009 result.putParcelableArray(Constants.ACCOUNTS_KEY, accounts);
1010 response.onResult(result);
1011 } catch (RemoteException e) {
1012 // if the caller is dead then there is no one to care about remote exceptions
1013 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1014 Log.v(TAG, "failure while notifying response", e);
1015 }
1016 }
1017 }
1018 }
1019
1020
1021 protected String toDebugString(long now) {
1022 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1023 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1024 }
1025 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001026
1027 public Account[] getAccounts(String type) {
1028 checkReadAccountsPermission();
1029 long identityToken = clearCallingIdentity();
1030 try {
1031 return getAccountsByType(type);
1032 } finally {
1033 restoreCallingIdentity(identityToken);
1034 }
1035 }
1036
1037 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001038 String type, String[] features) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001039 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001040 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -07001041 if (response != null) {
1042 try {
1043 response.onError(Constants.ERROR_CODE_BAD_ARGUMENTS, "type is null");
1044 } catch (RemoteException e) {
1045 // ignore this
1046 }
1047 }
1048 return;
1049 }
1050 long identityToken = clearCallingIdentity();
1051 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001052 if (features == null || features.length == 0) {
1053 getAccountsByType(type);
1054 return;
1055 }
Fred Quintana33269202009-04-20 16:05:10 -07001056 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1057 } finally {
1058 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001059 }
1060 }
1061
Fred Quintana60307342009-03-24 22:48:12 -07001062 private long getAccountId(SQLiteDatabase db, Account account) {
1063 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001064 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001065 try {
1066 if (cursor.moveToNext()) {
1067 return cursor.getLong(0);
1068 }
1069 return -1;
1070 } finally {
1071 cursor.close();
1072 }
1073 }
1074
1075 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1076 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1077 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1078 new String[]{key}, null, null, null);
1079 try {
1080 if (cursor.moveToNext()) {
1081 return cursor.getLong(0);
1082 }
1083 return -1;
1084 } finally {
1085 cursor.close();
1086 }
1087 }
1088
Fred Quintanaa698f422009-04-08 19:14:54 -07001089 private abstract class Session extends IAccountAuthenticatorResponse.Stub
1090 implements AuthenticatorBindHelper.Callback, IBinder.DeathRecipient {
Fred Quintana60307342009-03-24 22:48:12 -07001091 IAccountManagerResponse mResponse;
1092 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001093 final boolean mExpectActivityLaunch;
1094 final long mCreationTime;
1095
Fred Quintana33269202009-04-20 16:05:10 -07001096 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001097 private int mNumRequestContinued = 0;
1098 private int mNumErrors = 0;
1099
Fred Quintana60307342009-03-24 22:48:12 -07001100
1101 IAccountAuthenticator mAuthenticator = null;
1102
Fred Quintanaa698f422009-04-08 19:14:54 -07001103 public Session(IAccountManagerResponse response, String accountType,
1104 boolean expectActivityLaunch) {
Fred Quintana60307342009-03-24 22:48:12 -07001105 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001106 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001107 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana60307342009-03-24 22:48:12 -07001108 mResponse = response;
1109 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001110 mExpectActivityLaunch = expectActivityLaunch;
1111 mCreationTime = SystemClock.elapsedRealtime();
1112 synchronized (mSessions) {
1113 mSessions.put(toString(), this);
1114 }
1115 try {
1116 response.asBinder().linkToDeath(this, 0 /* flags */);
1117 } catch (RemoteException e) {
1118 mResponse = null;
1119 binderDied();
1120 }
Fred Quintana60307342009-03-24 22:48:12 -07001121 }
1122
Fred Quintanaa698f422009-04-08 19:14:54 -07001123 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001124 if (mResponse == null) {
1125 // this session has already been closed
1126 return null;
1127 }
Fred Quintana60307342009-03-24 22:48:12 -07001128 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001129 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001130 return response;
1131 }
1132
Fred Quintanaa698f422009-04-08 19:14:54 -07001133 private void close() {
1134 synchronized (mSessions) {
1135 if (mSessions.remove(toString()) == null) {
1136 // the session was already closed, so bail out now
1137 return;
1138 }
1139 }
1140 if (mResponse != null) {
1141 // stop listening for response deaths
1142 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1143
1144 // clear this so that we don't accidentally send any further results
1145 mResponse = null;
1146 }
1147 cancelTimeout();
1148 unbind();
1149 }
1150
1151 public void binderDied() {
1152 mResponse = null;
1153 close();
1154 }
1155
1156 protected String toDebugString() {
1157 return toDebugString(SystemClock.elapsedRealtime());
1158 }
1159
1160 protected String toDebugString(long now) {
1161 return "Session: expectLaunch " + mExpectActivityLaunch
1162 + ", connected " + (mAuthenticator != null)
1163 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1164 + "/" + mNumErrors + ")"
1165 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1166 }
1167
Fred Quintana60307342009-03-24 22:48:12 -07001168 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001169 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1170 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1171 }
Fred Quintana60307342009-03-24 22:48:12 -07001172 if (!mBindHelper.bind(mAccountType, this)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001173 Log.d(TAG, "bind attempt failed for " + toDebugString());
1174 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001175 }
1176 }
1177
1178 private void unbind() {
1179 if (mAuthenticator != null) {
1180 mAuthenticator = null;
1181 mBindHelper.unbind(this);
1182 }
1183 }
1184
1185 public void scheduleTimeout() {
1186 mMessageHandler.sendMessageDelayed(
1187 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1188 }
1189
1190 public void cancelTimeout() {
1191 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1192 }
1193
1194 public void onConnected(IBinder service) {
1195 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001196 try {
1197 run();
1198 } catch (RemoteException e) {
1199 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1200 "remote exception");
1201 }
Fred Quintana60307342009-03-24 22:48:12 -07001202 }
1203
Fred Quintanaa698f422009-04-08 19:14:54 -07001204 public abstract void run() throws RemoteException;
1205
Fred Quintana60307342009-03-24 22:48:12 -07001206 public void onDisconnected() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001207 mAuthenticator = null;
1208 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001209 if (response != null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001210 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1211 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001212 }
1213 }
1214
1215 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001216 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001217 if (response != null) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001218 onError(Constants.ERROR_CODE_REMOTE_EXCEPTION,
1219 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001220 }
1221 }
1222
Fred Quintanaa698f422009-04-08 19:14:54 -07001223 public void onResult(Bundle result) {
1224 mNumResults++;
1225 if (result != null && !TextUtils.isEmpty(result.getString(Constants.AUTHTOKEN_KEY))) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001226 String accountName = result.getString(Constants.ACCOUNT_NAME_KEY);
1227 String accountType = result.getString(Constants.ACCOUNT_TYPE_KEY);
1228 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1229 Account account = new Account(accountName, accountType);
1230 cancelNotification(getSigninRequiredNotificationId(account));
1231 }
Fred Quintana60307342009-03-24 22:48:12 -07001232 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001233 IAccountManagerResponse response;
1234 if (mExpectActivityLaunch && result != null
1235 && result.containsKey(Constants.INTENT_KEY)) {
1236 response = mResponse;
1237 } else {
1238 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001239 }
Fred Quintana60307342009-03-24 22:48:12 -07001240 if (response != null) {
1241 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001242 if (result == null) {
1243 response.onError(Constants.ERROR_CODE_INVALID_RESPONSE,
1244 "null bundle returned");
1245 } else {
1246 response.onResult(result);
1247 }
Fred Quintana60307342009-03-24 22:48:12 -07001248 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001249 // if the caller is dead then there is no one to care about remote exceptions
1250 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1251 Log.v(TAG, "failure while notifying response", e);
1252 }
Fred Quintana60307342009-03-24 22:48:12 -07001253 }
1254 }
1255 }
Fred Quintana60307342009-03-24 22:48:12 -07001256
Fred Quintanaa698f422009-04-08 19:14:54 -07001257 public void onRequestContinued() {
1258 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001259 }
1260
1261 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001262 mNumErrors++;
1263 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1264 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001265 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001266 IAccountManagerResponse response = getResponseAndClose();
1267 if (response != null) {
1268 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1269 Log.v(TAG, "Session.onError: responding");
1270 }
1271 try {
1272 response.onError(errorCode, errorMessage);
1273 } catch (RemoteException e) {
1274 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1275 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1276 }
1277 }
1278 } else {
1279 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1280 Log.v(TAG, "Session.onError: already closed");
1281 }
Fred Quintana60307342009-03-24 22:48:12 -07001282 }
1283 }
1284 }
1285
1286 private class MessageHandler extends Handler {
1287 MessageHandler(Looper looper) {
1288 super(looper);
1289 }
1290
1291 public void handleMessage(Message msg) {
1292 if (mBindHelper.handleMessage(msg)) {
1293 return;
1294 }
1295 switch (msg.what) {
1296 case MESSAGE_TIMED_OUT:
1297 Session session = (Session)msg.obj;
1298 session.onTimedOut();
1299 break;
1300
1301 default:
1302 throw new IllegalStateException("unhandled message: " + msg.what);
1303 }
1304 }
1305 }
1306
1307 private class DatabaseHelper extends SQLiteOpenHelper {
1308 public DatabaseHelper(Context context) {
1309 super(context, DATABASE_NAME, null, DATABASE_VERSION);
1310 }
1311
1312 @Override
1313 public void onCreate(SQLiteDatabase db) {
1314 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1315 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1316 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1317 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1318 + ACCOUNTS_PASSWORD + " TEXT, "
1319 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1320
1321 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1322 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1323 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1324 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1325 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1326 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1327
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001328 createGrantsTable(db);
1329
Fred Quintana60307342009-03-24 22:48:12 -07001330 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1331 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1332 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1333 + EXTRAS_KEY + " TEXT NOT NULL, "
1334 + EXTRAS_VALUE + " TEXT, "
1335 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1336
1337 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1338 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1339 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001340
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001341 createAccountsDeletionTrigger(db);
1342 }
1343
1344 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001345 db.execSQL(""
1346 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1347 + " BEGIN"
1348 + " DELETE FROM " + TABLE_AUTHTOKENS
1349 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1350 + " DELETE FROM " + TABLE_EXTRAS
1351 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001352 + " DELETE FROM " + TABLE_GRANTS
1353 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001354 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001355 }
1356
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001357 private void createGrantsTable(SQLiteDatabase db) {
1358 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1359 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1360 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1361 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1362 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1363 + "," + GRANTS_GRANTEE_UID + "))");
1364 }
1365
Fred Quintana60307342009-03-24 22:48:12 -07001366 @Override
1367 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001368 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001369
Fred Quintanaa698f422009-04-08 19:14:54 -07001370 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001371 // no longer need to do anything since the work is done
1372 // when upgrading from version 2
1373 oldVersion++;
1374 }
1375
1376 if (oldVersion == 2) {
1377 createGrantsTable(db);
1378 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1379 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001380 oldVersion++;
1381 }
Fred Quintana60307342009-03-24 22:48:12 -07001382 }
1383
1384 @Override
1385 public void onOpen(SQLiteDatabase db) {
1386 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1387 }
1388 }
1389
1390 private void setMetaValue(String key, String value) {
1391 ContentValues values = new ContentValues();
1392 values.put(META_KEY, key);
1393 values.put(META_VALUE, value);
1394 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1395 }
1396
1397 private String getMetaValue(String key) {
1398 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1399 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1400 try {
1401 if (c.moveToNext()) {
1402 return c.getString(0);
1403 }
1404 return null;
1405 } finally {
1406 c.close();
1407 }
1408 }
1409
1410 private class SimWatcher extends BroadcastReceiver {
1411 public SimWatcher(Context context) {
1412 // Re-scan the SIM card when the SIM state changes, and also if
1413 // the disk recovers from a full state (we may have failed to handle
1414 // things properly while the disk was full).
1415 final IntentFilter filter = new IntentFilter();
1416 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1417 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1418 context.registerReceiver(this, filter);
1419 }
1420
1421 /**
1422 * Compare the IMSI to the one stored in the login service's
1423 * database. If they differ, erase all passwords and
1424 * authtokens (and store the new IMSI).
1425 */
1426 @Override
1427 public void onReceive(Context context, Intent intent) {
1428 // Check IMSI on every update; nothing happens if the IMSI is missing or unchanged.
1429 String imsi = ((TelephonyManager) context.getSystemService(
1430 Context.TELEPHONY_SERVICE)).getSubscriberId();
1431 if (TextUtils.isEmpty(imsi)) return;
1432
1433 String storedImsi = getMetaValue("imsi");
1434
1435 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1436 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1437 }
1438
jsh5b462472009-09-01 16:13:55 -07001439 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001440 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1441 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001442 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1443 db.beginTransaction();
1444 try {
1445 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1446 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001447 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001448 db.setTransactionSuccessful();
1449 } finally {
1450 db.endTransaction();
1451 }
1452 }
1453 setMetaValue("imsi", imsi);
1454 }
1455 }
1456
1457 public IBinder onBind(Intent intent) {
1458 return asBinder();
1459 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001460
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001461 /**
1462 * Searches array of arguments for the specified string
1463 * @param args array of argument strings
1464 * @param value value to search for
1465 * @return true if the value is contained in the array
1466 */
1467 private static boolean scanArgs(String[] args, String value) {
1468 if (args != null) {
1469 for (String arg : args) {
1470 if (value.equals(arg)) {
1471 return true;
1472 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001473 }
1474 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001475 return false;
1476 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001477
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001478 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1479 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001480
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001481 if (isCheckinRequest) {
1482 // This is a checkin request. *Only* upload the account types and the count of each.
1483 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1484
1485 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1486 null, null, ACCOUNTS_TYPE, null, null);
1487 try {
1488 while (cursor.moveToNext()) {
1489 // print type,count
1490 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1491 }
1492 } finally {
1493 if (cursor != null) {
1494 cursor.close();
1495 }
1496 }
1497 } else {
1498 synchronized (mSessions) {
1499 final long now = SystemClock.elapsedRealtime();
1500 fout.println("AccountManagerService: " + mSessions.size() + " sessions");
1501 for (Session session : mSessions.values()) {
1502 fout.println(" " + session.toDebugString(now));
1503 }
1504 }
1505
1506 fout.println();
1507 mAuthenticatorCache.dump(fd, fout, args);
1508 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001509 }
1510
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001511 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001512 long identityToken = clearCallingIdentity();
1513 try {
1514 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1515 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1516 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001517
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001518 if (intent.getComponent() != null &&
1519 GrantCredentialsPermissionActivity.class.getName().equals(
1520 intent.getComponent().getClassName())) {
1521 createNoCredentialsPermissionNotification(account, intent);
1522 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001523 final Integer notificationId = getSigninRequiredNotificationId(account);
1524 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001525 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1526 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001527 final String notificationTitleFormat =
1528 mContext.getText(R.string.notification_title).toString();
1529 n.setLatestEventInfo(mContext,
1530 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001531 message, PendingIntent.getActivity(
1532 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1533 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001534 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001535 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001536 } finally {
1537 restoreCallingIdentity(identityToken);
1538 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001539 }
1540
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001541 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001542 long identityToken = clearCallingIdentity();
1543 try {
1544 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001545 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001546 } finally {
1547 restoreCallingIdentity(identityToken);
1548 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001549 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001550
1551 private void checkBinderPermission(String permission) {
1552 final int uid = Binder.getCallingUid();
1553 if (mContext.checkCallingOrSelfPermission(permission) !=
1554 PackageManager.PERMISSION_GRANTED) {
1555 String msg = "caller uid " + uid + " lacks " + permission;
1556 Log.w(TAG, msg);
1557 throw new SecurityException(msg);
1558 }
1559 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1560 Log.v(TAG, "caller uid " + uid + " has " + permission);
1561 }
1562 }
1563
Fred Quintana7be59642009-08-24 18:29:25 -07001564 private boolean inSystemImage(int callerUid) {
1565 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1566 for (String name : packages) {
1567 try {
1568 PackageInfo packageInfo =
1569 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1570 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1571 return true;
1572 }
1573 } catch (PackageManager.NameNotFoundException e) {
1574 return false;
1575 }
1576 }
1577 return false;
1578 }
1579
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001580 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001581 final boolean fromAuthenticator = hasAuthenticatorUid(account.type, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001582 final boolean hasExplicitGrants = hasExplicitlyGrantedPermission(account, authTokenType);
1583 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1584 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1585 + callerUid + ", account " + account
1586 + ": is authenticator? " + fromAuthenticator
1587 + ", has explicit permission? " + hasExplicitGrants);
1588 }
Fred Quintana7be59642009-08-24 18:29:25 -07001589 return fromAuthenticator || hasExplicitGrants || inSystemImage(callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001590 }
1591
1592 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
1593 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1594 mAuthenticatorCache.getAllServices()) {
1595 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001596 return (serviceInfo.uid == callingUid) ||
1597 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1598 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001599 }
1600 }
1601 return false;
1602 }
1603
1604 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1605 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1606 return true;
1607 }
1608 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1609 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001610 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001611 final boolean permissionGranted =
1612 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1613 if (!permissionGranted && isDebuggableMonkeyBuild) {
1614 // TODO: Skip this check when running automated tests. Replace this
1615 // with a more general solution.
1616 Log.w(TAG, "no credentials permission for usage of " + account + ", "
1617 + authTokenType + " by uid " + Binder.getCallingUid()
1618 + " but ignoring since this is a monkey build");
1619 return true;
1620 }
1621 return permissionGranted;
1622 }
1623
1624 private void checkCallingUidAgainstAuthenticator(Account account) {
1625 final int uid = Binder.getCallingUid();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001626 if (!hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001627 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1628 Log.w(TAG, msg);
1629 throw new SecurityException(msg);
1630 }
1631 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1632 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1633 }
1634 }
1635
1636 private void checkAuthenticateAccountsPermission(Account account) {
1637 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1638 checkCallingUidAgainstAuthenticator(account);
1639 }
1640
1641 private void checkReadAccountsPermission() {
1642 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1643 }
1644
1645 private void checkManageAccountsPermission() {
1646 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1647 }
1648
1649 /**
1650 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1651 * <p>
1652 * Although this is public it can only be accessed via the AccountManagerService object
1653 * which is in the system. This means we don't need to protect it with permissions.
1654 * @hide
1655 */
1656 public void grantAppPermission(Account account, String authTokenType, int uid) {
1657 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1658 db.beginTransaction();
1659 try {
1660 long accountId = getAccountId(db, account);
1661 if (accountId >= 0) {
1662 ContentValues values = new ContentValues();
1663 values.put(GRANTS_ACCOUNTS_ID, accountId);
1664 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1665 values.put(GRANTS_GRANTEE_UID, uid);
1666 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1667 db.setTransactionSuccessful();
1668 }
1669 } finally {
1670 db.endTransaction();
1671 }
1672 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1673 }
1674
1675 /**
1676 * Don't allow callers with the given uid permission to get credentials for
1677 * account/authTokenType.
1678 * <p>
1679 * Although this is public it can only be accessed via the AccountManagerService object
1680 * which is in the system. This means we don't need to protect it with permissions.
1681 * @hide
1682 */
1683 public void revokeAppPermission(Account account, String authTokenType, int uid) {
1684 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1685 db.beginTransaction();
1686 try {
1687 long accountId = getAccountId(db, account);
1688 if (accountId >= 0) {
1689 db.delete(TABLE_GRANTS,
1690 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1691 + GRANTS_GRANTEE_UID + "=?",
1692 new String[]{String.valueOf(accountId), authTokenType,
1693 String.valueOf(uid)});
1694 db.setTransactionSuccessful();
1695 }
1696 } finally {
1697 db.endTransaction();
1698 }
1699 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1700 }
Fred Quintana60307342009-03-24 22:48:12 -07001701}