blob: e2453f673a3557721cf750e6fee3446718eb5b95 [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 Quintanab839afc2009-10-14 15:57:28 -070024import android.content.ServiceConnection;
25import android.content.ComponentName;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070026import android.content.pm.PackageManager;
27import android.content.pm.RegisteredServicesCache;
Fred Quintana7be59642009-08-24 18:29:25 -070028import android.content.pm.PackageInfo;
29import android.content.pm.ApplicationInfo;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070030import android.content.pm.RegisteredServicesCacheListener;
Fred Quintana60307342009-03-24 22:48:12 -070031import android.database.Cursor;
32import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070033import android.database.sqlite.SQLiteDatabase;
34import android.database.sqlite.SQLiteOpenHelper;
35import android.os.Bundle;
36import android.os.Handler;
37import android.os.HandlerThread;
38import android.os.IBinder;
39import android.os.Looper;
40import android.os.Message;
41import android.os.RemoteException;
42import android.os.SystemClock;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070043import android.os.Binder;
44import android.os.SystemProperties;
Fred Quintana60307342009-03-24 22:48:12 -070045import android.telephony.TelephonyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070046import android.text.TextUtils;
47import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070048import android.util.Pair;
Fred Quintana26fc5eb2009-04-09 15:05:50 -070049import android.app.PendingIntent;
50import android.app.NotificationManager;
51import android.app.Notification;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070052import android.Manifest;
Fred Quintana60307342009-03-24 22:48:12 -070053
Fred Quintanaa698f422009-04-08 19:14:54 -070054import java.io.FileDescriptor;
55import java.io.PrintWriter;
56import java.util.ArrayList;
57import java.util.Collection;
Fred Quintanaa698f422009-04-08 19:14:54 -070058import java.util.LinkedHashMap;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070059import java.util.HashMap;
60import java.util.concurrent.atomic.AtomicInteger;
61import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070062
Fred Quintana60307342009-03-24 22:48:12 -070063import com.android.internal.telephony.TelephonyIntents;
Fred Quintana26fc5eb2009-04-09 15:05:50 -070064import com.android.internal.R;
Fred Quintana60307342009-03-24 22:48:12 -070065
66/**
67 * A system service that provides account, password, and authtoken management for all
68 * accounts on the device. Some of these calls are implemented with the help of the corresponding
69 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
70 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
71 * AccountManager accountManager =
72 * (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE)
Fred Quintana33269202009-04-20 16:05:10 -070073 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070074 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070075public class AccountManagerService
76 extends IAccountManager.Stub
77 implements RegisteredServicesCacheListener {
Costin Manolache3348f142009-09-29 18:58:36 -070078 private static final String GOOGLE_ACCOUNT_TYPE = "com.google";
Jim Miller50c05f32009-09-21 19:07:44 -070079
80 private static final String NO_BROADCAST_FLAG = "nobroadcast";
81
Fred Quintana60307342009-03-24 22:48:12 -070082 private static final String TAG = "AccountManagerService";
83
84 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
85 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070086 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070087
88 private final Context mContext;
89
90 private HandlerThread mMessageThread;
91 private final MessageHandler mMessageHandler;
92
93 // Messages that can be sent on mHandler
94 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -070095
96 private final AccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -070097 private final DatabaseHelper mOpenHelper;
98 private final SimWatcher mSimWatcher;
99
100 private static final String TABLE_ACCOUNTS = "accounts";
101 private static final String ACCOUNTS_ID = "_id";
102 private static final String ACCOUNTS_NAME = "name";
103 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700104 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700105 private static final String ACCOUNTS_PASSWORD = "password";
106
107 private static final String TABLE_AUTHTOKENS = "authtokens";
108 private static final String AUTHTOKENS_ID = "_id";
109 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
110 private static final String AUTHTOKENS_TYPE = "type";
111 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
112
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700113 private static final String TABLE_GRANTS = "grants";
114 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
115 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
116 private static final String GRANTS_GRANTEE_UID = "uid";
117
Fred Quintana60307342009-03-24 22:48:12 -0700118 private static final String TABLE_EXTRAS = "extras";
119 private static final String EXTRAS_ID = "_id";
120 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
121 private static final String EXTRAS_KEY = "key";
122 private static final String EXTRAS_VALUE = "value";
123
124 private static final String TABLE_META = "meta";
125 private static final String META_KEY = "key";
126 private static final String META_VALUE = "value";
127
128 private static final String[] ACCOUNT_NAME_TYPE_PROJECTION =
129 new String[]{ACCOUNTS_ID, ACCOUNTS_NAME, ACCOUNTS_TYPE};
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700130 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
131 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700132 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700133
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700134 private static final String COUNT_OF_MATCHING_GRANTS = ""
135 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
136 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
137 + " AND " + GRANTS_GRANTEE_UID + "=?"
138 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
139 + " AND " + ACCOUNTS_NAME + "=?"
140 + " AND " + ACCOUNTS_TYPE + "=?";
141
Fred Quintanaa698f422009-04-08 19:14:54 -0700142 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700143 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
144
145 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
146 mCredentialsPermissionNotificationIds =
147 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
148 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
149 new HashMap<Account, Integer>();
150 private static AtomicReference<AccountManagerService> sThis =
151 new AtomicReference<AccountManagerService>();
152
153 private static final boolean isDebuggableMonkeyBuild =
154 SystemProperties.getBoolean("ro.monkey", false)
155 && SystemProperties.getBoolean("ro.debuggable", false);
Fred Quintana7be59642009-08-24 18:29:25 -0700156
157 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700158 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700159 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
160 }
161
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700162 /**
163 * This should only be called by system code. One should only call this after the service
164 * has started.
165 * @return a reference to the AccountManagerService instance
166 * @hide
167 */
168 public static AccountManagerService getSingleton() {
169 return sThis.get();
170 }
Fred Quintana60307342009-03-24 22:48:12 -0700171
172 public class AuthTokenKey {
173 public final Account mAccount;
174 public final String mAuthTokenType;
175 private final int mHashCode;
176
177 public AuthTokenKey(Account account, String authTokenType) {
178 mAccount = account;
179 mAuthTokenType = authTokenType;
180 mHashCode = computeHashCode();
181 }
182
183 public boolean equals(Object o) {
184 if (o == this) {
185 return true;
186 }
187 if (!(o instanceof AuthTokenKey)) {
188 return false;
189 }
190 AuthTokenKey other = (AuthTokenKey)o;
191 if (!mAccount.equals(other.mAccount)) {
192 return false;
193 }
194 return (mAuthTokenType == null)
195 ? other.mAuthTokenType == null
196 : mAuthTokenType.equals(other.mAuthTokenType);
197 }
198
199 private int computeHashCode() {
200 int result = 17;
201 result = 31 * result + mAccount.hashCode();
202 result = 31 * result + ((mAuthTokenType == null) ? 0 : mAuthTokenType.hashCode());
203 return result;
204 }
205
206 public int hashCode() {
207 return mHashCode;
208 }
209 }
210
211 public AccountManagerService(Context context) {
212 mContext = context;
213
214 mOpenHelper = new DatabaseHelper(mContext);
215
216 mMessageThread = new HandlerThread("AccountManagerService");
217 mMessageThread.start();
218 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
219
220 mAuthenticatorCache = new AccountAuthenticatorCache(mContext);
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700221 mAuthenticatorCache.setListener(this);
Fred Quintana60307342009-03-24 22:48:12 -0700222
Doug Zongker7fa8c502009-10-13 13:02:49 -0700223 if (SystemProperties.getBoolean("ro.config.sim_password_clear", false)) {
224 mSimWatcher = new SimWatcher(mContext);
225 } else {
226 mSimWatcher = null;
227 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700228 sThis.set(this);
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700229
230 onRegisteredServicesCacheChanged();
231 }
232
233 public void onRegisteredServicesCacheChanged() {
234 boolean accountDeleted = false;
235 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
236 Cursor cursor = db.query(TABLE_ACCOUNTS,
237 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
238 null, null, null, null, null);
239 try {
240 while (cursor.moveToNext()) {
241 final long accountId = cursor.getLong(0);
242 final String accountType = cursor.getString(1);
243 final String accountName = cursor.getString(2);
244 if (mAuthenticatorCache.getServiceInfo(AuthenticatorDescription.newKey(accountType))
245 == null) {
246 Log.d(TAG, "deleting account " + accountName + " because type "
247 + accountType + " no longer has a registered authenticator");
248 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
249 accountDeleted= true;
250 }
251 }
252 } finally {
253 cursor.close();
254 if (accountDeleted) {
255 sendAccountsChangedBroadcast();
256 }
257 }
Fred Quintana60307342009-03-24 22:48:12 -0700258 }
259
Fred Quintanaa698f422009-04-08 19:14:54 -0700260 public String getPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700261 checkAuthenticateAccountsPermission(account);
262
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700263 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700264 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700265 return readPasswordFromDatabase(account);
266 } finally {
267 restoreCallingIdentity(identityToken);
268 }
269 }
270
271 private String readPasswordFromDatabase(Account account) {
272 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
273 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
274 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
275 new String[]{account.name, account.type}, null, null, null);
276 try {
277 if (cursor.moveToNext()) {
278 return cursor.getString(0);
279 }
280 return null;
281 } finally {
282 cursor.close();
283 }
284 }
285
286 public String getUserData(Account account, String key) {
287 checkAuthenticateAccountsPermission(account);
288 long identityToken = clearCallingIdentity();
289 try {
290 return readUserDataFromDatabase(account, key);
291 } finally {
292 restoreCallingIdentity(identityToken);
293 }
294 }
295
296 private String readUserDataFromDatabase(Account account, String key) {
297 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700298 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_VALUE},
299 EXTRAS_ACCOUNTS_ID
300 + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
301 + EXTRAS_KEY + "=?",
302 new String[]{account.name, account.type, key}, null, null, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700303 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700304 if (cursor.moveToNext()) {
305 return cursor.getString(0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700306 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700307 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700308 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700309 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700310 }
311 }
312
Fred Quintana97889762009-06-15 12:29:24 -0700313 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700314 long identityToken = clearCallingIdentity();
315 try {
Fred Quintana97889762009-06-15 12:29:24 -0700316 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
317 authenticatorCollection = mAuthenticatorCache.getAllServices();
318 AuthenticatorDescription[] types =
319 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700320 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700321 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700322 : authenticatorCollection) {
323 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700324 i++;
325 }
326 return types;
327 } finally {
328 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700329 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700330 }
331
Fred Quintanaa698f422009-04-08 19:14:54 -0700332 public Account[] getAccountsByType(String accountType) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700333 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700334
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700335 final String selection = accountType == null ? null : (ACCOUNTS_TYPE + "=?");
336 final String[] selectionArgs = accountType == null ? null : new String[]{accountType};
337 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_NAME_TYPE_PROJECTION,
338 selection, selectionArgs, null, null, null);
339 try {
340 int i = 0;
341 Account[] accounts = new Account[cursor.getCount()];
342 while (cursor.moveToNext()) {
343 accounts[i] = new Account(cursor.getString(1), cursor.getString(2));
344 i++;
Fred Quintana60307342009-03-24 22:48:12 -0700345 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700346 return accounts;
Fred Quintana60307342009-03-24 22:48:12 -0700347 } finally {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700348 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700349 }
350 }
351
Fred Quintanaa698f422009-04-08 19:14:54 -0700352 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700353 checkAuthenticateAccountsPermission(account);
354
Fred Quintana60307342009-03-24 22:48:12 -0700355 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700356 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700357 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700358 return insertAccountIntoDatabase(account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700359 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700360 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700361 }
362 }
363
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700364 private boolean insertAccountIntoDatabase(Account account, String password, Bundle extras) {
365 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
366 db.beginTransaction();
367 try {
Jim Miller50c05f32009-09-21 19:07:44 -0700368 boolean noBroadcast = false;
369 if (account.type.equals(GOOGLE_ACCOUNT_TYPE)) {
370 // Look for the 'nobroadcast' flag and remove it since we don't want it to persist
371 // in the db.
372 noBroadcast = extras.getBoolean(NO_BROADCAST_FLAG, false);
373 extras.remove(NO_BROADCAST_FLAG);
374 }
375
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700376 long numMatches = DatabaseUtils.longForQuery(db,
377 "select count(*) from " + TABLE_ACCOUNTS
378 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
379 new String[]{account.name, account.type});
380 if (numMatches > 0) {
381 return false;
382 }
383 ContentValues values = new ContentValues();
384 values.put(ACCOUNTS_NAME, account.name);
385 values.put(ACCOUNTS_TYPE, account.type);
386 values.put(ACCOUNTS_PASSWORD, password);
387 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
388 if (accountId < 0) {
389 return false;
390 }
391 if (extras != null) {
392 for (String key : extras.keySet()) {
393 final String value = extras.getString(key);
394 if (insertExtra(db, accountId, key, value) < 0) {
395 return false;
396 }
397 }
398 }
399 db.setTransactionSuccessful();
Jim Miller50c05f32009-09-21 19:07:44 -0700400 if (!noBroadcast) {
401 sendAccountsChangedBroadcast();
402 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700403 return true;
404 } finally {
405 db.endTransaction();
406 }
407 }
408
Fred Quintana60307342009-03-24 22:48:12 -0700409 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
410 ContentValues values = new ContentValues();
411 values.put(EXTRAS_KEY, key);
412 values.put(EXTRAS_ACCOUNTS_ID, accountId);
413 values.put(EXTRAS_VALUE, value);
414 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
415 }
416
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700417 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700418 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700419 long identityToken = clearCallingIdentity();
420 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700421 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700422 } finally {
423 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700424 }
Fred Quintana60307342009-03-24 22:48:12 -0700425 }
426
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700427 private class RemoveAccountSession extends Session {
428 final Account mAccount;
429 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
430 super(response, account.type, false /* expectActivityLaunch */);
431 mAccount = account;
432 }
433
434 protected String toDebugString(long now) {
435 return super.toDebugString(now) + ", removeAccount"
436 + ", account " + mAccount;
437 }
438
439 public void run() throws RemoteException {
440 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
441 }
442
443 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700444 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
445 && !result.containsKey(AccountManager.KEY_INTENT)) {
446 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700447 if (removalAllowed) {
448 removeAccount(mAccount);
449 }
450 IAccountManagerResponse response = getResponseAndClose();
451 if (response != null) {
452 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700453 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700454 try {
455 response.onResult(result2);
456 } catch (RemoteException e) {
457 // ignore
458 }
459 }
460 }
461 super.onResult(result);
462 }
463 }
464
465 private void removeAccount(Account account) {
466 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
467 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
468 new String[]{account.name, account.type});
469 sendAccountsChangedBroadcast();
470 }
471
Fred Quintanaa698f422009-04-08 19:14:54 -0700472 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700473 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700474 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700475 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700476 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
477 db.beginTransaction();
478 try {
479 invalidateAuthToken(db, accountType, authToken);
480 db.setTransactionSuccessful();
481 } finally {
482 db.endTransaction();
483 }
Fred Quintana60307342009-03-24 22:48:12 -0700484 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700485 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700486 }
487 }
488
489 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700490 if (authToken == null || accountType == null) {
491 return;
492 }
Fred Quintana33269202009-04-20 16:05:10 -0700493 Cursor cursor = db.rawQuery(
494 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
495 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
496 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
497 + " FROM " + TABLE_ACCOUNTS
498 + " JOIN " + TABLE_AUTHTOKENS
499 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
500 + " = " + AUTHTOKENS_ACCOUNTS_ID
501 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
502 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
503 new String[]{authToken, accountType});
504 try {
505 while (cursor.moveToNext()) {
506 long authTokenId = cursor.getLong(0);
507 String accountName = cursor.getString(1);
508 String authTokenType = cursor.getString(2);
509 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700510 }
Fred Quintana33269202009-04-20 16:05:10 -0700511 } finally {
512 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700513 }
514 }
515
516 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700517 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700518 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
519 db.beginTransaction();
520 try {
Fred Quintana33269202009-04-20 16:05:10 -0700521 long accountId = getAccountId(db, account);
522 if (accountId < 0) {
523 return false;
524 }
525 db.delete(TABLE_AUTHTOKENS,
526 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
527 new String[]{type});
528 ContentValues values = new ContentValues();
529 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
530 values.put(AUTHTOKENS_TYPE, type);
531 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
532 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700533 db.setTransactionSuccessful();
534 return true;
535 }
536 return false;
537 } finally {
538 db.endTransaction();
539 }
540 }
541
Fred Quintana60307342009-03-24 22:48:12 -0700542 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
543 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700544 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
545 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
546 + AUTHTOKENS_TYPE + "=?",
547 new String[]{account.name, account.type, authTokenType},
548 null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700549 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700550 if (cursor.moveToNext()) {
551 return cursor.getString(0);
Fred Quintana60307342009-03-24 22:48:12 -0700552 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700553 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700554 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700555 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700556 }
557 }
558
Fred Quintanaa698f422009-04-08 19:14:54 -0700559 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700560 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700561 long identityToken = clearCallingIdentity();
562 try {
Fred Quintana33269202009-04-20 16:05:10 -0700563 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700564 } finally {
565 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700566 }
Fred Quintana60307342009-03-24 22:48:12 -0700567 }
568
Fred Quintanaa698f422009-04-08 19:14:54 -0700569 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700570 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700571 long identityToken = clearCallingIdentity();
572 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700573 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700574 } finally {
575 restoreCallingIdentity(identityToken);
576 }
Fred Quintana60307342009-03-24 22:48:12 -0700577 }
578
Fred Quintanaa698f422009-04-08 19:14:54 -0700579 public void setPassword(Account account, String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700580 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700581 long identityToken = clearCallingIdentity();
582 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700583 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700584 } finally {
585 restoreCallingIdentity(identityToken);
586 }
Fred Quintana60307342009-03-24 22:48:12 -0700587 }
588
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700589 private void setPasswordInDB(Account account, String password) {
590 ContentValues values = new ContentValues();
591 values.put(ACCOUNTS_PASSWORD, password);
592 mOpenHelper.getWritableDatabase().update(TABLE_ACCOUNTS, values,
593 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
594 new String[]{account.name, account.type});
595 sendAccountsChangedBroadcast();
596 }
597
Fred Quintana33269202009-04-20 16:05:10 -0700598 private void sendAccountsChangedBroadcast() {
599 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
600 }
601
Fred Quintanaa698f422009-04-08 19:14:54 -0700602 public void clearPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700603 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700604 long identityToken = clearCallingIdentity();
605 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700606 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700607 } finally {
608 restoreCallingIdentity(identityToken);
609 }
Fred Quintana60307342009-03-24 22:48:12 -0700610 }
611
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700612 private void sendResult(IAccountManagerResponse response, Bundle bundle) {
613 if (response != null) {
614 try {
615 response.onResult(bundle);
616 } catch (RemoteException e) {
617 // if the caller is dead then there is no one to care about remote
618 // exceptions
619 if (Log.isLoggable(TAG, Log.VERBOSE)) {
620 Log.v(TAG, "failure while notifying response", e);
621 }
622 }
623 }
624 }
625
Fred Quintanaa698f422009-04-08 19:14:54 -0700626 public void setUserData(Account account, String key, String value) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700627 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700628 long identityToken = clearCallingIdentity();
Jim Miller50c05f32009-09-21 19:07:44 -0700629 if (account.type.equals(GOOGLE_ACCOUNT_TYPE) && key.equals("broadcast")) {
630 sendAccountsChangedBroadcast();
631 return;
632 }
Fred Quintana60307342009-03-24 22:48:12 -0700633 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700634 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700635 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700636 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700637 }
638 }
639
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700640 private void writeUserdataIntoDatabase(Account account, String key, String value) {
641 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
642 db.beginTransaction();
643 try {
644 long accountId = getAccountId(db, account);
645 if (accountId < 0) {
646 return;
647 }
648 long extrasId = getExtrasId(db, accountId, key);
649 if (extrasId < 0 ) {
650 extrasId = insertExtra(db, accountId, key, value);
651 if (extrasId < 0) {
652 return;
653 }
654 } else {
655 ContentValues values = new ContentValues();
656 values.put(EXTRAS_VALUE, value);
657 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
658 return;
659 }
660
661 }
662 db.setTransactionSuccessful();
663 } finally {
664 db.endTransaction();
665 }
666 }
667
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700668 private void onResult(IAccountManagerResponse response, Bundle result) {
669 try {
670 response.onResult(result);
671 } catch (RemoteException e) {
672 // if the caller is dead then there is no one to care about remote
673 // exceptions
674 if (Log.isLoggable(TAG, Log.VERBOSE)) {
675 Log.v(TAG, "failure while notifying response", e);
676 }
677 }
678 }
679
Fred Quintanaa698f422009-04-08 19:14:54 -0700680 public void getAuthToken(IAccountManagerResponse response, final Account account,
681 final String authTokenType, final boolean notifyOnAuthFailure,
682 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700683 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
684 final int callerUid = Binder.getCallingUid();
685 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
686
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700687 long identityToken = clearCallingIdentity();
688 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700689 // if the caller has permission, do the peek. otherwise go the more expensive
690 // route of starting a Session
691 if (permissionGranted) {
692 String authToken = readAuthTokenFromDatabase(account, authTokenType);
693 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700694 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700695 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
696 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
697 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700698 onResult(response, result);
699 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700700 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700701 }
702
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700703 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700704 protected String toDebugString(long now) {
705 if (loginOptions != null) loginOptions.keySet();
706 return super.toDebugString(now) + ", getAuthToken"
707 + ", " + account
708 + ", authTokenType " + authTokenType
709 + ", loginOptions " + loginOptions
710 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
711 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700712
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700713 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700714 // If the caller doesn't have permission then create and return the
715 // "grant permission" intent instead of the "getAuthToken" intent.
716 if (!permissionGranted) {
717 mAuthenticator.getAuthTokenLabel(this, authTokenType);
718 } else {
719 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
720 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700721 }
722
723 public void onResult(Bundle result) {
724 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700725 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700726 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
727 new AccountAuthenticatorResponse(this),
728 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700729 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700730 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700731 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700732 onResult(bundle);
733 return;
734 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700735 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700736 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700737 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
738 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700739 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700740 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700741 "the type and name should not be empty");
742 return;
743 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700744 saveAuthTokenToDatabase(new Account(name, type),
745 authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700746 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700747
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700748 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700749 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700750 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700751 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700752 intent);
753 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700754 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700755 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700756 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700757 }.bind();
758 } finally {
759 restoreCallingIdentity(identityToken);
760 }
Fred Quintana60307342009-03-24 22:48:12 -0700761 }
762
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700763 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
764 int uid = intent.getIntExtra(
765 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
766 String authTokenType = intent.getStringExtra(
767 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
768 String authTokenLabel = intent.getStringExtra(
769 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
770
771 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
772 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700773 final String titleAndSubtitle =
774 mContext.getString(R.string.permission_request_notification_with_subtitle,
775 account.name);
776 final int index = titleAndSubtitle.indexOf('\n');
777 final String title = titleAndSubtitle.substring(0, index);
778 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700779 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700780 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700781 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
782 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
783 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
784 }
785
786 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
787 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
788 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
789 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700790 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700791 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700792 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700793 }
794
795 final Context authContext;
796 try {
797 authContext = mContext.createPackageContext(
798 serviceInfo.type.packageName, 0);
799 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700800 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700801 }
802
803 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
804 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
805 intent.addCategory(
806 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
807 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
808 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
809 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
810 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
811 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
812 authContext.getString(serviceInfo.type.labelId));
813 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
814 mContext.getPackageManager().getPackagesForUid(uid));
815 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
816 return intent;
817 }
818
819 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
820 int uid) {
821 Integer id;
822 synchronized(mCredentialsPermissionNotificationIds) {
823 final Pair<Pair<Account, String>, Integer> key =
824 new Pair<Pair<Account, String>, Integer>(
825 new Pair<Account, String>(account, authTokenType), uid);
826 id = mCredentialsPermissionNotificationIds.get(key);
827 if (id == null) {
828 id = mNotificationIds.incrementAndGet();
829 mCredentialsPermissionNotificationIds.put(key, id);
830 }
831 }
832 return id;
833 }
834
835 private Integer getSigninRequiredNotificationId(Account account) {
836 Integer id;
837 synchronized(mSigninRequiredNotificationIds) {
838 id = mSigninRequiredNotificationIds.get(account);
839 if (id == null) {
840 id = mNotificationIds.incrementAndGet();
841 mSigninRequiredNotificationIds.put(account, id);
842 }
843 }
844 return id;
845 }
846
Fred Quintanaa698f422009-04-08 19:14:54 -0700847
Fred Quintana33269202009-04-20 16:05:10 -0700848 public void addAcount(final IAccountManagerResponse response, final String accountType,
849 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700850 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700851 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700852 long identityToken = clearCallingIdentity();
853 try {
854 new Session(response, accountType, expectActivityLaunch) {
855 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -0700856 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -0700857 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700858 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700859
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700860 protected String toDebugString(long now) {
861 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -0700862 + ", accountType " + accountType
863 + ", requiredFeatures "
864 + (requiredFeatures != null
865 ? TextUtils.join(",", requiredFeatures)
866 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700867 }
868 }.bind();
869 } finally {
870 restoreCallingIdentity(identityToken);
871 }
Fred Quintana60307342009-03-24 22:48:12 -0700872 }
873
Fred Quintanaa698f422009-04-08 19:14:54 -0700874 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700875 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700876 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700877 long identityToken = clearCallingIdentity();
878 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700879 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700880 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700881 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700882 }
883 protected String toDebugString(long now) {
884 return super.toDebugString(now) + ", confirmCredentials"
885 + ", " + account;
886 }
887 }.bind();
888 } finally {
889 restoreCallingIdentity(identityToken);
890 }
Fred Quintana60307342009-03-24 22:48:12 -0700891 }
892
Fred Quintanaa698f422009-04-08 19:14:54 -0700893 public void updateCredentials(IAccountManagerResponse response, final Account account,
894 final String authTokenType, final boolean expectActivityLaunch,
895 final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700896 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700897 long identityToken = clearCallingIdentity();
898 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700899 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700900 public void run() throws RemoteException {
901 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
902 }
903 protected String toDebugString(long now) {
904 if (loginOptions != null) loginOptions.keySet();
905 return super.toDebugString(now) + ", updateCredentials"
906 + ", " + account
907 + ", authTokenType " + authTokenType
908 + ", loginOptions " + loginOptions;
909 }
910 }.bind();
911 } finally {
912 restoreCallingIdentity(identityToken);
913 }
Fred Quintana60307342009-03-24 22:48:12 -0700914 }
915
Fred Quintanaa698f422009-04-08 19:14:54 -0700916 public void editProperties(IAccountManagerResponse response, final String accountType,
917 final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700918 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700919 long identityToken = clearCallingIdentity();
920 try {
921 new Session(response, accountType, expectActivityLaunch) {
922 public void run() throws RemoteException {
923 mAuthenticator.editProperties(this, mAccountType);
924 }
925 protected String toDebugString(long now) {
926 return super.toDebugString(now) + ", editProperties"
927 + ", accountType " + accountType;
928 }
929 }.bind();
930 } finally {
931 restoreCallingIdentity(identityToken);
932 }
Fred Quintana60307342009-03-24 22:48:12 -0700933 }
934
Fred Quintana33269202009-04-20 16:05:10 -0700935 private class GetAccountsByTypeAndFeatureSession extends Session {
936 private final String[] mFeatures;
937 private volatile Account[] mAccountsOfType = null;
938 private volatile ArrayList<Account> mAccountsWithFeatures = null;
939 private volatile int mCurrentAccount = 0;
940
941 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
942 String type, String[] features) {
943 super(response, type, false /* expectActivityLaunch */);
944 mFeatures = features;
945 }
946
947 public void run() throws RemoteException {
948 mAccountsOfType = getAccountsByType(mAccountType);
949 // check whether each account matches the requested features
950 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
951 mCurrentAccount = 0;
952
953 checkAccount();
954 }
955
956 public void checkAccount() {
957 if (mCurrentAccount >= mAccountsOfType.length) {
958 sendResult();
959 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700960 }
Fred Quintana33269202009-04-20 16:05:10 -0700961
962 try {
963 mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
964 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700965 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -0700966 }
967 }
968
969 public void onResult(Bundle result) {
970 mNumResults++;
971 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700972 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -0700973 return;
974 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700975 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -0700976 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
977 }
978 mCurrentAccount++;
979 checkAccount();
980 }
981
982 public void sendResult() {
983 IAccountManagerResponse response = getResponseAndClose();
984 if (response != null) {
985 try {
986 Account[] accounts = new Account[mAccountsWithFeatures.size()];
987 for (int i = 0; i < accounts.length; i++) {
988 accounts[i] = mAccountsWithFeatures.get(i);
989 }
990 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700991 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -0700992 response.onResult(result);
993 } catch (RemoteException e) {
994 // if the caller is dead then there is no one to care about remote exceptions
995 if (Log.isLoggable(TAG, Log.VERBOSE)) {
996 Log.v(TAG, "failure while notifying response", e);
997 }
998 }
999 }
1000 }
1001
1002
1003 protected String toDebugString(long now) {
1004 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1005 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1006 }
1007 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001008
1009 public Account[] getAccounts(String type) {
1010 checkReadAccountsPermission();
1011 long identityToken = clearCallingIdentity();
1012 try {
1013 return getAccountsByType(type);
1014 } finally {
1015 restoreCallingIdentity(identityToken);
1016 }
1017 }
1018
1019 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001020 String type, String[] features) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001021 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001022 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -07001023 if (response != null) {
1024 try {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001025 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "type is null");
Fred Quintana33269202009-04-20 16:05:10 -07001026 } catch (RemoteException e) {
1027 // ignore this
1028 }
1029 }
1030 return;
1031 }
1032 long identityToken = clearCallingIdentity();
1033 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001034 if (features == null || features.length == 0) {
1035 getAccountsByType(type);
1036 return;
1037 }
Fred Quintana33269202009-04-20 16:05:10 -07001038 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1039 } finally {
1040 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001041 }
1042 }
1043
Fred Quintana60307342009-03-24 22:48:12 -07001044 private long getAccountId(SQLiteDatabase db, Account account) {
1045 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001046 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001047 try {
1048 if (cursor.moveToNext()) {
1049 return cursor.getLong(0);
1050 }
1051 return -1;
1052 } finally {
1053 cursor.close();
1054 }
1055 }
1056
1057 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1058 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1059 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1060 new String[]{key}, null, null, null);
1061 try {
1062 if (cursor.moveToNext()) {
1063 return cursor.getLong(0);
1064 }
1065 return -1;
1066 } finally {
1067 cursor.close();
1068 }
1069 }
1070
Fred Quintanaa698f422009-04-08 19:14:54 -07001071 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001072 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001073 IAccountManagerResponse mResponse;
1074 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001075 final boolean mExpectActivityLaunch;
1076 final long mCreationTime;
1077
Fred Quintana33269202009-04-20 16:05:10 -07001078 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001079 private int mNumRequestContinued = 0;
1080 private int mNumErrors = 0;
1081
Fred Quintana60307342009-03-24 22:48:12 -07001082
1083 IAccountAuthenticator mAuthenticator = null;
1084
Fred Quintanaa698f422009-04-08 19:14:54 -07001085 public Session(IAccountManagerResponse response, String accountType,
1086 boolean expectActivityLaunch) {
Fred Quintana60307342009-03-24 22:48:12 -07001087 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001088 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001089 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana60307342009-03-24 22:48:12 -07001090 mResponse = response;
1091 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001092 mExpectActivityLaunch = expectActivityLaunch;
1093 mCreationTime = SystemClock.elapsedRealtime();
1094 synchronized (mSessions) {
1095 mSessions.put(toString(), this);
1096 }
1097 try {
1098 response.asBinder().linkToDeath(this, 0 /* flags */);
1099 } catch (RemoteException e) {
1100 mResponse = null;
1101 binderDied();
1102 }
Fred Quintana60307342009-03-24 22:48:12 -07001103 }
1104
Fred Quintanaa698f422009-04-08 19:14:54 -07001105 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001106 if (mResponse == null) {
1107 // this session has already been closed
1108 return null;
1109 }
Fred Quintana60307342009-03-24 22:48:12 -07001110 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001111 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001112 return response;
1113 }
1114
Fred Quintanaa698f422009-04-08 19:14:54 -07001115 private void close() {
1116 synchronized (mSessions) {
1117 if (mSessions.remove(toString()) == null) {
1118 // the session was already closed, so bail out now
1119 return;
1120 }
1121 }
1122 if (mResponse != null) {
1123 // stop listening for response deaths
1124 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1125
1126 // clear this so that we don't accidentally send any further results
1127 mResponse = null;
1128 }
1129 cancelTimeout();
1130 unbind();
1131 }
1132
1133 public void binderDied() {
1134 mResponse = null;
1135 close();
1136 }
1137
1138 protected String toDebugString() {
1139 return toDebugString(SystemClock.elapsedRealtime());
1140 }
1141
1142 protected String toDebugString(long now) {
1143 return "Session: expectLaunch " + mExpectActivityLaunch
1144 + ", connected " + (mAuthenticator != null)
1145 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1146 + "/" + mNumErrors + ")"
1147 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1148 }
1149
Fred Quintana60307342009-03-24 22:48:12 -07001150 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001151 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1152 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1153 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001154 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001155 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001156 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001157 }
1158 }
1159
1160 private void unbind() {
1161 if (mAuthenticator != null) {
1162 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001163 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001164 }
1165 }
1166
1167 public void scheduleTimeout() {
1168 mMessageHandler.sendMessageDelayed(
1169 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1170 }
1171
1172 public void cancelTimeout() {
1173 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1174 }
1175
Fred Quintanab839afc2009-10-14 15:57:28 -07001176 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001177 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001178 try {
1179 run();
1180 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001181 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001182 "remote exception");
1183 }
Fred Quintana60307342009-03-24 22:48:12 -07001184 }
1185
Fred Quintanab839afc2009-10-14 15:57:28 -07001186 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001187 mAuthenticator = null;
1188 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001189 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001190 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001191 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001192 }
1193 }
1194
Fred Quintanab839afc2009-10-14 15:57:28 -07001195 public abstract void run() throws RemoteException;
1196
Fred Quintana60307342009-03-24 22:48:12 -07001197 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001198 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001199 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001200 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001201 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001202 }
1203 }
1204
Fred Quintanaa698f422009-04-08 19:14:54 -07001205 public void onResult(Bundle result) {
1206 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001207 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1208 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1209 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001210 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1211 Account account = new Account(accountName, accountType);
1212 cancelNotification(getSigninRequiredNotificationId(account));
1213 }
Fred Quintana60307342009-03-24 22:48:12 -07001214 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001215 IAccountManagerResponse response;
1216 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001217 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001218 response = mResponse;
1219 } else {
1220 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001221 }
Fred Quintana60307342009-03-24 22:48:12 -07001222 if (response != null) {
1223 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001224 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001225 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001226 "null bundle returned");
1227 } else {
1228 response.onResult(result);
1229 }
Fred Quintana60307342009-03-24 22:48:12 -07001230 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001231 // if the caller is dead then there is no one to care about remote exceptions
1232 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1233 Log.v(TAG, "failure while notifying response", e);
1234 }
Fred Quintana60307342009-03-24 22:48:12 -07001235 }
1236 }
1237 }
Fred Quintana60307342009-03-24 22:48:12 -07001238
Fred Quintanaa698f422009-04-08 19:14:54 -07001239 public void onRequestContinued() {
1240 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001241 }
1242
1243 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001244 mNumErrors++;
1245 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1246 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001247 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001248 IAccountManagerResponse response = getResponseAndClose();
1249 if (response != null) {
1250 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1251 Log.v(TAG, "Session.onError: responding");
1252 }
1253 try {
1254 response.onError(errorCode, errorMessage);
1255 } catch (RemoteException e) {
1256 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1257 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1258 }
1259 }
1260 } else {
1261 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1262 Log.v(TAG, "Session.onError: already closed");
1263 }
Fred Quintana60307342009-03-24 22:48:12 -07001264 }
1265 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001266
1267 /**
1268 * find the component name for the authenticator and initiate a bind
1269 * if no authenticator or the bind fails then return false, otherwise return true
1270 */
1271 private boolean bindToAuthenticator(String authenticatorType) {
1272 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1273 mAuthenticatorCache.getServiceInfo(
1274 AuthenticatorDescription.newKey(authenticatorType));
1275 if (authenticatorInfo == null) {
1276 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1277 Log.v(TAG, "there is no authenticator for " + authenticatorType
1278 + ", bailing out");
1279 }
1280 return false;
1281 }
1282
1283 Intent intent = new Intent();
1284 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1285 intent.setComponent(authenticatorInfo.componentName);
1286 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1287 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1288 }
1289 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1290 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1291 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1292 }
1293 return false;
1294 }
1295
1296
1297 return true;
1298 }
Fred Quintana60307342009-03-24 22:48:12 -07001299 }
1300
1301 private class MessageHandler extends Handler {
1302 MessageHandler(Looper looper) {
1303 super(looper);
1304 }
Costin Manolache3348f142009-09-29 18:58:36 -07001305
Fred Quintana60307342009-03-24 22:48:12 -07001306 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001307 switch (msg.what) {
1308 case MESSAGE_TIMED_OUT:
1309 Session session = (Session)msg.obj;
1310 session.onTimedOut();
1311 break;
1312
1313 default:
1314 throw new IllegalStateException("unhandled message: " + msg.what);
1315 }
1316 }
1317 }
1318
1319 private class DatabaseHelper extends SQLiteOpenHelper {
1320 public DatabaseHelper(Context context) {
1321 super(context, DATABASE_NAME, null, DATABASE_VERSION);
1322 }
1323
1324 @Override
1325 public void onCreate(SQLiteDatabase db) {
1326 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1327 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1328 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1329 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1330 + ACCOUNTS_PASSWORD + " TEXT, "
1331 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1332
1333 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1334 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1335 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1336 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1337 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1338 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1339
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001340 createGrantsTable(db);
1341
Fred Quintana60307342009-03-24 22:48:12 -07001342 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1343 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1344 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1345 + EXTRAS_KEY + " TEXT NOT NULL, "
1346 + EXTRAS_VALUE + " TEXT, "
1347 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1348
1349 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1350 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1351 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001352
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001353 createAccountsDeletionTrigger(db);
1354 }
1355
1356 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001357 db.execSQL(""
1358 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1359 + " BEGIN"
1360 + " DELETE FROM " + TABLE_AUTHTOKENS
1361 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1362 + " DELETE FROM " + TABLE_EXTRAS
1363 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001364 + " DELETE FROM " + TABLE_GRANTS
1365 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001366 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001367 }
1368
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001369 private void createGrantsTable(SQLiteDatabase db) {
1370 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1371 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1372 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1373 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1374 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1375 + "," + GRANTS_GRANTEE_UID + "))");
1376 }
1377
Fred Quintana60307342009-03-24 22:48:12 -07001378 @Override
1379 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001380 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001381
Fred Quintanaa698f422009-04-08 19:14:54 -07001382 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001383 // no longer need to do anything since the work is done
1384 // when upgrading from version 2
1385 oldVersion++;
1386 }
1387
1388 if (oldVersion == 2) {
1389 createGrantsTable(db);
1390 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1391 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001392 oldVersion++;
1393 }
Costin Manolache3348f142009-09-29 18:58:36 -07001394
1395 if (oldVersion == 3) {
1396 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1397 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1398 oldVersion++;
1399 }
Fred Quintana60307342009-03-24 22:48:12 -07001400 }
1401
1402 @Override
1403 public void onOpen(SQLiteDatabase db) {
1404 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1405 }
1406 }
1407
1408 private void setMetaValue(String key, String value) {
1409 ContentValues values = new ContentValues();
1410 values.put(META_KEY, key);
1411 values.put(META_VALUE, value);
1412 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1413 }
1414
1415 private String getMetaValue(String key) {
1416 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1417 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1418 try {
1419 if (c.moveToNext()) {
1420 return c.getString(0);
1421 }
1422 return null;
1423 } finally {
1424 c.close();
1425 }
1426 }
1427
1428 private class SimWatcher extends BroadcastReceiver {
1429 public SimWatcher(Context context) {
1430 // Re-scan the SIM card when the SIM state changes, and also if
1431 // the disk recovers from a full state (we may have failed to handle
1432 // things properly while the disk was full).
1433 final IntentFilter filter = new IntentFilter();
1434 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1435 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1436 context.registerReceiver(this, filter);
1437 }
Costin Manolache3348f142009-09-29 18:58:36 -07001438
Fred Quintana60307342009-03-24 22:48:12 -07001439 /**
1440 * Compare the IMSI to the one stored in the login service's
1441 * database. If they differ, erase all passwords and
1442 * authtokens (and store the new IMSI).
1443 */
1444 @Override
1445 public void onReceive(Context context, Intent intent) {
1446 // Check IMSI on every update; nothing happens if the IMSI is missing or unchanged.
1447 String imsi = ((TelephonyManager) context.getSystemService(
1448 Context.TELEPHONY_SERVICE)).getSubscriberId();
1449 if (TextUtils.isEmpty(imsi)) return;
1450
1451 String storedImsi = getMetaValue("imsi");
1452
1453 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1454 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1455 }
1456
jsh5b462472009-09-01 16:13:55 -07001457 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001458 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1459 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001460 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1461 db.beginTransaction();
1462 try {
1463 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1464 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001465 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001466 db.setTransactionSuccessful();
1467 } finally {
1468 db.endTransaction();
1469 }
1470 }
1471 setMetaValue("imsi", imsi);
1472 }
1473 }
1474
1475 public IBinder onBind(Intent intent) {
1476 return asBinder();
1477 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001478
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001479 /**
1480 * Searches array of arguments for the specified string
1481 * @param args array of argument strings
1482 * @param value value to search for
1483 * @return true if the value is contained in the array
1484 */
1485 private static boolean scanArgs(String[] args, String value) {
1486 if (args != null) {
1487 for (String arg : args) {
1488 if (value.equals(arg)) {
1489 return true;
1490 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001491 }
1492 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001493 return false;
1494 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001495
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001496 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1497 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001498
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001499 if (isCheckinRequest) {
1500 // This is a checkin request. *Only* upload the account types and the count of each.
1501 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1502
1503 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1504 null, null, ACCOUNTS_TYPE, null, null);
1505 try {
1506 while (cursor.moveToNext()) {
1507 // print type,count
1508 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1509 }
1510 } finally {
1511 if (cursor != null) {
1512 cursor.close();
1513 }
1514 }
1515 } else {
1516 synchronized (mSessions) {
1517 final long now = SystemClock.elapsedRealtime();
1518 fout.println("AccountManagerService: " + mSessions.size() + " sessions");
1519 for (Session session : mSessions.values()) {
1520 fout.println(" " + session.toDebugString(now));
1521 }
1522 }
1523
1524 fout.println();
1525 mAuthenticatorCache.dump(fd, fout, args);
1526 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001527 }
1528
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001529 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001530 long identityToken = clearCallingIdentity();
1531 try {
1532 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1533 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1534 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001535
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001536 if (intent.getComponent() != null &&
1537 GrantCredentialsPermissionActivity.class.getName().equals(
1538 intent.getComponent().getClassName())) {
1539 createNoCredentialsPermissionNotification(account, intent);
1540 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001541 final Integer notificationId = getSigninRequiredNotificationId(account);
1542 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001543 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1544 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001545 final String notificationTitleFormat =
1546 mContext.getText(R.string.notification_title).toString();
1547 n.setLatestEventInfo(mContext,
1548 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001549 message, PendingIntent.getActivity(
1550 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1551 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001552 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001553 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001554 } finally {
1555 restoreCallingIdentity(identityToken);
1556 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001557 }
1558
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001559 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001560 long identityToken = clearCallingIdentity();
1561 try {
1562 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001563 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001564 } finally {
1565 restoreCallingIdentity(identityToken);
1566 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001567 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001568
1569 private void checkBinderPermission(String permission) {
1570 final int uid = Binder.getCallingUid();
1571 if (mContext.checkCallingOrSelfPermission(permission) !=
1572 PackageManager.PERMISSION_GRANTED) {
1573 String msg = "caller uid " + uid + " lacks " + permission;
1574 Log.w(TAG, msg);
1575 throw new SecurityException(msg);
1576 }
1577 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1578 Log.v(TAG, "caller uid " + uid + " has " + permission);
1579 }
1580 }
1581
Fred Quintana7be59642009-08-24 18:29:25 -07001582 private boolean inSystemImage(int callerUid) {
1583 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1584 for (String name : packages) {
1585 try {
1586 PackageInfo packageInfo =
1587 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1588 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1589 return true;
1590 }
1591 } catch (PackageManager.NameNotFoundException e) {
1592 return false;
1593 }
1594 }
1595 return false;
1596 }
1597
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001598 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001599 final boolean fromAuthenticator = hasAuthenticatorUid(account.type, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001600 final boolean hasExplicitGrants = hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanab839afc2009-10-14 15:57:28 -07001601 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001602 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1603 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1604 + callerUid + ", account " + account
1605 + ": is authenticator? " + fromAuthenticator
1606 + ", has explicit permission? " + hasExplicitGrants);
1607 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001608 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001609 }
1610
Fred Quintanab839afc2009-10-14 15:57:28 -07001611 private boolean hasAuthenticatorcontextUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001612 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1613 mAuthenticatorCache.getAllServices()) {
1614 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001615 return (serviceInfo.uid == callingUid) ||
1616 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1617 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001618 }
1619 }
1620 return false;
1621 }
1622
1623 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1624 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1625 return true;
1626 }
1627 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1628 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001629 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001630 final boolean permissionGranted =
1631 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1632 if (!permissionGranted && isDebuggableMonkeyBuild) {
1633 // TODO: Skip this check when running automated tests. Replace this
1634 // with a more general solution.
1635 Log.w(TAG, "no credentials permission for usage of " + account + ", "
1636 + authTokenType + " by uid " + Binder.getCallingUid()
1637 + " but ignoring since this is a monkey build");
1638 return true;
1639 }
1640 return permissionGranted;
1641 }
1642
1643 private void checkCallingUidAgainstAuthenticator(Account account) {
1644 final int uid = Binder.getCallingUid();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001645 if (!hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001646 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1647 Log.w(TAG, msg);
1648 throw new SecurityException(msg);
1649 }
1650 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1651 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1652 }
1653 }
1654
1655 private void checkAuthenticateAccountsPermission(Account account) {
1656 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1657 checkCallingUidAgainstAuthenticator(account);
1658 }
1659
1660 private void checkReadAccountsPermission() {
1661 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1662 }
1663
1664 private void checkManageAccountsPermission() {
1665 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1666 }
1667
1668 /**
1669 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1670 * <p>
1671 * Although this is public it can only be accessed via the AccountManagerService object
1672 * which is in the system. This means we don't need to protect it with permissions.
1673 * @hide
1674 */
1675 public void grantAppPermission(Account account, String authTokenType, int uid) {
1676 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1677 db.beginTransaction();
1678 try {
1679 long accountId = getAccountId(db, account);
1680 if (accountId >= 0) {
1681 ContentValues values = new ContentValues();
1682 values.put(GRANTS_ACCOUNTS_ID, accountId);
1683 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1684 values.put(GRANTS_GRANTEE_UID, uid);
1685 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1686 db.setTransactionSuccessful();
1687 }
1688 } finally {
1689 db.endTransaction();
1690 }
1691 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1692 }
1693
1694 /**
1695 * Don't allow callers with the given uid permission to get credentials for
1696 * account/authTokenType.
1697 * <p>
1698 * Although this is public it can only be accessed via the AccountManagerService object
1699 * which is in the system. This means we don't need to protect it with permissions.
1700 * @hide
1701 */
1702 public void revokeAppPermission(Account account, String authTokenType, int uid) {
1703 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1704 db.beginTransaction();
1705 try {
1706 long accountId = getAccountId(db, account);
1707 if (accountId >= 0) {
1708 db.delete(TABLE_GRANTS,
1709 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1710 + GRANTS_GRANTEE_UID + "=?",
1711 new String[]{String.valueOf(accountId), authTokenType,
1712 String.valueOf(uid)});
1713 db.setTransactionSuccessful();
1714 }
1715 } finally {
1716 db.endTransaction();
1717 }
1718 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1719 }
Fred Quintana60307342009-03-24 22:48:12 -07001720}