blob: 9a8cc15a60e4be491a047699f07ab86530a71e5c [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
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
20import android.app.Notification;
21import android.app.NotificationManager;
22import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070023import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070024import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070025import android.content.ContentValues;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070029import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070030import android.content.pm.ApplicationInfo;
31import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070032import android.content.pm.PackageManager;
33import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070034import android.content.pm.RegisteredServicesCacheListener;
Fred Quintana60307342009-03-24 22:48:12 -070035import android.database.Cursor;
36import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070039import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070040import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080041import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070042import android.os.Handler;
43import android.os.HandlerThread;
44import android.os.IBinder;
45import android.os.Looper;
46import android.os.Message;
47import android.os.RemoteException;
Doug Zongker885cfc232009-10-21 16:52:44 -070048import android.os.ServiceManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070049import android.os.SystemClock;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070050import android.os.SystemProperties;
Fred Quintana60307342009-03-24 22:48:12 -070051import android.telephony.TelephonyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070052import android.text.TextUtils;
53import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070054import android.util.Pair;
Fred Quintana60307342009-03-24 22:48:12 -070055
Oscar Montemayora8529f62009-11-18 10:14:20 -080056import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070057import java.io.FileDescriptor;
58import java.io.PrintWriter;
59import java.util.ArrayList;
60import java.util.Collection;
Fred Quintanaa698f422009-04-08 19:14:54 -070061import java.util.LinkedHashMap;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070062import java.util.HashMap;
63import java.util.concurrent.atomic.AtomicInteger;
64import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070065
Fred Quintana26fc5eb2009-04-09 15:05:50 -070066import com.android.internal.R;
Doug Zongker885cfc232009-10-21 16:52:44 -070067import com.android.internal.telephony.ITelephony;
68import com.android.internal.telephony.TelephonyIntents;
Fred Quintana60307342009-03-24 22:48:12 -070069
70/**
71 * A system service that provides account, password, and authtoken management for all
72 * accounts on the device. Some of these calls are implemented with the help of the corresponding
73 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
74 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
75 * AccountManager accountManager =
76 * (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE)
Fred Quintana33269202009-04-20 16:05:10 -070077 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070078 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070079public class AccountManagerService
80 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080081 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Costin Manolache3348f142009-09-29 18:58:36 -070082 private static final String GOOGLE_ACCOUNT_TYPE = "com.google";
Jim Miller50c05f32009-09-21 19:07:44 -070083
84 private static final String NO_BROADCAST_FLAG = "nobroadcast";
85
Fred Quintana60307342009-03-24 22:48:12 -070086 private static final String TAG = "AccountManagerService";
87
88 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
89 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070090 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070091
92 private final Context mContext;
93
94 private HandlerThread mMessageThread;
95 private final MessageHandler mMessageHandler;
96
97 // Messages that can be sent on mHandler
98 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -070099
100 private final AccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700101 private final DatabaseHelper mOpenHelper;
102 private final SimWatcher mSimWatcher;
103
104 private static final String TABLE_ACCOUNTS = "accounts";
105 private static final String ACCOUNTS_ID = "_id";
106 private static final String ACCOUNTS_NAME = "name";
107 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700108 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700109 private static final String ACCOUNTS_PASSWORD = "password";
110
111 private static final String TABLE_AUTHTOKENS = "authtokens";
112 private static final String AUTHTOKENS_ID = "_id";
113 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
114 private static final String AUTHTOKENS_TYPE = "type";
115 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
116
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700117 private static final String TABLE_GRANTS = "grants";
118 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
119 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
120 private static final String GRANTS_GRANTEE_UID = "uid";
121
Fred Quintana60307342009-03-24 22:48:12 -0700122 private static final String TABLE_EXTRAS = "extras";
123 private static final String EXTRAS_ID = "_id";
124 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
125 private static final String EXTRAS_KEY = "key";
126 private static final String EXTRAS_VALUE = "value";
127
128 private static final String TABLE_META = "meta";
129 private static final String META_KEY = "key";
130 private static final String META_VALUE = "value";
131
132 private static final String[] ACCOUNT_NAME_TYPE_PROJECTION =
133 new String[]{ACCOUNTS_ID, ACCOUNTS_NAME, ACCOUNTS_TYPE};
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700134 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
135 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700136 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700137
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700138 private static final String COUNT_OF_MATCHING_GRANTS = ""
139 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
140 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
141 + " AND " + GRANTS_GRANTEE_UID + "=?"
142 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
143 + " AND " + ACCOUNTS_NAME + "=?"
144 + " AND " + ACCOUNTS_TYPE + "=?";
145
Fred Quintanaa698f422009-04-08 19:14:54 -0700146 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700147 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
148
149 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
150 mCredentialsPermissionNotificationIds =
151 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
152 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
153 new HashMap<Account, Integer>();
154 private static AtomicReference<AccountManagerService> sThis =
155 new AtomicReference<AccountManagerService>();
156
157 private static final boolean isDebuggableMonkeyBuild =
Ying Wang42c98ad2010-01-04 18:51:25 -0800158 SystemProperties.getBoolean("ro.monkey", false);
Fred Quintana31957f12009-10-21 13:43:10 -0700159 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700160
161 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700162 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700163 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
164 }
165
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700166 /**
167 * This should only be called by system code. One should only call this after the service
168 * has started.
169 * @return a reference to the AccountManagerService instance
170 * @hide
171 */
172 public static AccountManagerService getSingleton() {
173 return sThis.get();
174 }
Fred Quintana60307342009-03-24 22:48:12 -0700175
176 public class AuthTokenKey {
177 public final Account mAccount;
178 public final String mAuthTokenType;
179 private final int mHashCode;
180
181 public AuthTokenKey(Account account, String authTokenType) {
182 mAccount = account;
183 mAuthTokenType = authTokenType;
184 mHashCode = computeHashCode();
185 }
186
187 public boolean equals(Object o) {
188 if (o == this) {
189 return true;
190 }
191 if (!(o instanceof AuthTokenKey)) {
192 return false;
193 }
194 AuthTokenKey other = (AuthTokenKey)o;
195 if (!mAccount.equals(other.mAccount)) {
196 return false;
197 }
198 return (mAuthTokenType == null)
199 ? other.mAuthTokenType == null
200 : mAuthTokenType.equals(other.mAuthTokenType);
201 }
202
203 private int computeHashCode() {
204 int result = 17;
205 result = 31 * result + mAccount.hashCode();
206 result = 31 * result + ((mAuthTokenType == null) ? 0 : mAuthTokenType.hashCode());
207 return result;
208 }
209
210 public int hashCode() {
211 return mHashCode;
212 }
213 }
214
215 public AccountManagerService(Context context) {
216 mContext = context;
217
218 mOpenHelper = new DatabaseHelper(mContext);
219
220 mMessageThread = new HandlerThread("AccountManagerService");
221 mMessageThread.start();
222 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
223
224 mAuthenticatorCache = new AccountAuthenticatorCache(mContext);
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800225 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700226
Doug Zongker885cfc232009-10-21 16:52:44 -0700227 mSimWatcher = new SimWatcher(mContext);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700228 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800229
230 validateAccounts();
231 }
232
233 private void validateAccounts() {
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 Quintana3ecd5f42009-09-17 12:42:35 -0700258 }
259
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800260 public void onServiceChanged(AuthenticatorDescription desc, boolean removed) {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700261 boolean accountDeleted = false;
262 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
263 Cursor cursor = db.query(TABLE_ACCOUNTS,
264 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800265 ACCOUNTS_TYPE + "=?", new String[]{desc.type}, null, null, null);
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700266 try {
267 while (cursor.moveToNext()) {
268 final long accountId = cursor.getLong(0);
269 final String accountType = cursor.getString(1);
270 final String accountName = cursor.getString(2);
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800271 Log.d(TAG, "deleting account " + accountName + " because type "
272 + accountType + " no longer has a registered authenticator");
273 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
274 accountDeleted = true;
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700275 }
276 } finally {
277 cursor.close();
278 if (accountDeleted) {
279 sendAccountsChangedBroadcast();
280 }
281 }
Fred Quintana60307342009-03-24 22:48:12 -0700282 }
283
Fred Quintanaa698f422009-04-08 19:14:54 -0700284 public String getPassword(Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700285 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700286 checkAuthenticateAccountsPermission(account);
287
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700288 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700289 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700290 return readPasswordFromDatabase(account);
291 } finally {
292 restoreCallingIdentity(identityToken);
293 }
294 }
295
296 private String readPasswordFromDatabase(Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700297 if (account == null) {
298 return null;
299 }
300
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700301 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
302 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
303 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
304 new String[]{account.name, account.type}, null, null, null);
305 try {
306 if (cursor.moveToNext()) {
307 return cursor.getString(0);
308 }
309 return null;
310 } finally {
311 cursor.close();
312 }
313 }
314
315 public String getUserData(Account account, String key) {
Fred Quintana382601f2010-03-25 12:25:10 -0700316 if (account == null) throw new IllegalArgumentException("account is null");
317 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700318 checkAuthenticateAccountsPermission(account);
319 long identityToken = clearCallingIdentity();
320 try {
321 return readUserDataFromDatabase(account, key);
322 } finally {
323 restoreCallingIdentity(identityToken);
324 }
325 }
326
327 private String readUserDataFromDatabase(Account account, String key) {
Fred Quintana31957f12009-10-21 13:43:10 -0700328 if (account == null) {
329 return null;
330 }
331
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700332 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700333 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_VALUE},
334 EXTRAS_ACCOUNTS_ID
335 + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
336 + EXTRAS_KEY + "=?",
337 new String[]{account.name, account.type, key}, null, null, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700338 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700339 if (cursor.moveToNext()) {
340 return cursor.getString(0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700341 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700342 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700343 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700344 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700345 }
346 }
347
Fred Quintana97889762009-06-15 12:29:24 -0700348 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700349 long identityToken = clearCallingIdentity();
350 try {
Fred Quintana97889762009-06-15 12:29:24 -0700351 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
352 authenticatorCollection = mAuthenticatorCache.getAllServices();
353 AuthenticatorDescription[] types =
354 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700355 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700356 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700357 : authenticatorCollection) {
358 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700359 i++;
360 }
361 return types;
362 } finally {
363 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700364 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700365 }
366
Fred Quintanaa698f422009-04-08 19:14:54 -0700367 public Account[] getAccountsByType(String accountType) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700368 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700369
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700370 final String selection = accountType == null ? null : (ACCOUNTS_TYPE + "=?");
371 final String[] selectionArgs = accountType == null ? null : new String[]{accountType};
372 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_NAME_TYPE_PROJECTION,
373 selection, selectionArgs, null, null, null);
374 try {
375 int i = 0;
376 Account[] accounts = new Account[cursor.getCount()];
377 while (cursor.moveToNext()) {
378 accounts[i] = new Account(cursor.getString(1), cursor.getString(2));
379 i++;
Fred Quintana60307342009-03-24 22:48:12 -0700380 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700381 return accounts;
Fred Quintana60307342009-03-24 22:48:12 -0700382 } finally {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700383 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700384 }
385 }
386
Fred Quintanaa698f422009-04-08 19:14:54 -0700387 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana382601f2010-03-25 12:25:10 -0700388 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700389 checkAuthenticateAccountsPermission(account);
390
Fred Quintana60307342009-03-24 22:48:12 -0700391 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700392 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700393 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700394 return insertAccountIntoDatabase(account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700395 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700396 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700397 }
398 }
399
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700400 private boolean insertAccountIntoDatabase(Account account, String password, Bundle extras) {
401 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
402 db.beginTransaction();
403 try {
Fred Quintana31957f12009-10-21 13:43:10 -0700404 if (account == null) {
405 return false;
406 }
Jim Miller50c05f32009-09-21 19:07:44 -0700407 boolean noBroadcast = false;
408 if (account.type.equals(GOOGLE_ACCOUNT_TYPE)) {
409 // Look for the 'nobroadcast' flag and remove it since we don't want it to persist
410 // in the db.
411 noBroadcast = extras.getBoolean(NO_BROADCAST_FLAG, false);
412 extras.remove(NO_BROADCAST_FLAG);
413 }
414
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700415 long numMatches = DatabaseUtils.longForQuery(db,
416 "select count(*) from " + TABLE_ACCOUNTS
417 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
418 new String[]{account.name, account.type});
419 if (numMatches > 0) {
420 return false;
421 }
422 ContentValues values = new ContentValues();
423 values.put(ACCOUNTS_NAME, account.name);
424 values.put(ACCOUNTS_TYPE, account.type);
425 values.put(ACCOUNTS_PASSWORD, password);
426 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
427 if (accountId < 0) {
428 return false;
429 }
430 if (extras != null) {
431 for (String key : extras.keySet()) {
432 final String value = extras.getString(key);
433 if (insertExtra(db, accountId, key, value) < 0) {
434 return false;
435 }
436 }
437 }
438 db.setTransactionSuccessful();
Jim Miller50c05f32009-09-21 19:07:44 -0700439 if (!noBroadcast) {
440 sendAccountsChangedBroadcast();
441 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700442 return true;
443 } finally {
444 db.endTransaction();
445 }
446 }
447
Fred Quintana60307342009-03-24 22:48:12 -0700448 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
449 ContentValues values = new ContentValues();
450 values.put(EXTRAS_KEY, key);
451 values.put(EXTRAS_ACCOUNTS_ID, accountId);
452 values.put(EXTRAS_VALUE, value);
453 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
454 }
455
Fred Quintana3084a6f2010-01-14 18:02:03 -0800456 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800457 Account account, String[] features) {
Fred Quintana382601f2010-03-25 12:25:10 -0700458 if (response == null) throw new IllegalArgumentException("response is null");
459 if (account == null) throw new IllegalArgumentException("account is null");
460 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800461 checkReadAccountsPermission();
462 long identityToken = clearCallingIdentity();
463 try {
464 new TestFeaturesSession(response, account, features).bind();
465 } finally {
466 restoreCallingIdentity(identityToken);
467 }
468 }
469
470 private class TestFeaturesSession extends Session {
471 private final String[] mFeatures;
472 private final Account mAccount;
473
474 public TestFeaturesSession(IAccountManagerResponse response,
475 Account account, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -0800476 super(response, account.type, false /* expectActivityLaunch */,
477 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800478 mFeatures = features;
479 mAccount = account;
480 }
481
482 public void run() throws RemoteException {
483 try {
484 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
485 } catch (RemoteException e) {
486 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
487 }
488 }
489
490 public void onResult(Bundle result) {
491 IAccountManagerResponse response = getResponseAndClose();
492 if (response != null) {
493 try {
494 if (result == null) {
495 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
496 return;
497 }
498 final Bundle newResult = new Bundle();
499 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
500 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
501 response.onResult(newResult);
502 } catch (RemoteException e) {
503 // if the caller is dead then there is no one to care about remote exceptions
504 if (Log.isLoggable(TAG, Log.VERBOSE)) {
505 Log.v(TAG, "failure while notifying response", e);
506 }
507 }
508 }
509 }
510
511 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800512 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800513 + ", " + mAccount
514 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
515 }
516 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800517
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700518 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700519 if (response == null) throw new IllegalArgumentException("response is null");
520 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700521 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700522 long identityToken = clearCallingIdentity();
523 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700524 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700525 } finally {
526 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700527 }
Fred Quintana60307342009-03-24 22:48:12 -0700528 }
529
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700530 private class RemoveAccountSession extends Session {
531 final Account mAccount;
532 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
Fred Quintana8570f742010-02-18 10:32:54 -0800533 super(response, account.type, false /* expectActivityLaunch */,
534 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700535 mAccount = account;
536 }
537
538 protected String toDebugString(long now) {
539 return super.toDebugString(now) + ", removeAccount"
540 + ", account " + mAccount;
541 }
542
543 public void run() throws RemoteException {
544 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
545 }
546
547 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700548 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
549 && !result.containsKey(AccountManager.KEY_INTENT)) {
550 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700551 if (removalAllowed) {
552 removeAccount(mAccount);
553 }
554 IAccountManagerResponse response = getResponseAndClose();
555 if (response != null) {
556 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700557 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700558 try {
559 response.onResult(result2);
560 } catch (RemoteException e) {
561 // ignore
562 }
563 }
564 }
565 super.onResult(result);
566 }
567 }
568
569 private void removeAccount(Account account) {
570 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
571 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
572 new String[]{account.name, account.type});
573 sendAccountsChangedBroadcast();
574 }
575
Fred Quintanaa698f422009-04-08 19:14:54 -0700576 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700577 if (accountType == null) throw new IllegalArgumentException("accountType is null");
578 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800579 checkManageAccountsOrUseCredentialsPermissions();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700580 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700581 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700582 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
583 db.beginTransaction();
584 try {
585 invalidateAuthToken(db, accountType, authToken);
586 db.setTransactionSuccessful();
587 } finally {
588 db.endTransaction();
589 }
Fred Quintana60307342009-03-24 22:48:12 -0700590 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700591 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700592 }
593 }
594
595 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700596 if (authToken == null || accountType == null) {
597 return;
598 }
Fred Quintana33269202009-04-20 16:05:10 -0700599 Cursor cursor = db.rawQuery(
600 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
601 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
602 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
603 + " FROM " + TABLE_ACCOUNTS
604 + " JOIN " + TABLE_AUTHTOKENS
605 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
606 + " = " + AUTHTOKENS_ACCOUNTS_ID
607 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
608 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
609 new String[]{authToken, accountType});
610 try {
611 while (cursor.moveToNext()) {
612 long authTokenId = cursor.getLong(0);
613 String accountName = cursor.getString(1);
614 String authTokenType = cursor.getString(2);
615 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700616 }
Fred Quintana33269202009-04-20 16:05:10 -0700617 } finally {
618 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700619 }
620 }
621
622 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700623 if (account == null || type == null) {
624 return false;
625 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700626 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700627 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
628 db.beginTransaction();
629 try {
Fred Quintana33269202009-04-20 16:05:10 -0700630 long accountId = getAccountId(db, account);
631 if (accountId < 0) {
632 return false;
633 }
634 db.delete(TABLE_AUTHTOKENS,
635 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
636 new String[]{type});
637 ContentValues values = new ContentValues();
638 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
639 values.put(AUTHTOKENS_TYPE, type);
640 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
641 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700642 db.setTransactionSuccessful();
643 return true;
644 }
645 return false;
646 } finally {
647 db.endTransaction();
648 }
649 }
650
Fred Quintana60307342009-03-24 22:48:12 -0700651 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
Fred Quintana31957f12009-10-21 13:43:10 -0700652 if (account == null || authTokenType == null) {
653 return null;
654 }
Fred Quintana60307342009-03-24 22:48:12 -0700655 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700656 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
657 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
658 + AUTHTOKENS_TYPE + "=?",
659 new String[]{account.name, account.type, authTokenType},
660 null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700661 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700662 if (cursor.moveToNext()) {
663 return cursor.getString(0);
Fred Quintana60307342009-03-24 22:48:12 -0700664 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700665 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700666 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700667 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700668 }
669 }
670
Fred Quintanaa698f422009-04-08 19:14:54 -0700671 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana382601f2010-03-25 12:25:10 -0700672 if (account == null) throw new IllegalArgumentException("account is null");
673 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700674 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700675 long identityToken = clearCallingIdentity();
676 try {
Fred Quintana33269202009-04-20 16:05:10 -0700677 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700678 } finally {
679 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700680 }
Fred Quintana60307342009-03-24 22:48:12 -0700681 }
682
Fred Quintanaa698f422009-04-08 19:14:54 -0700683 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700684 if (account == null) throw new IllegalArgumentException("account is null");
685 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700686 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700687 long identityToken = clearCallingIdentity();
688 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700689 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700690 } finally {
691 restoreCallingIdentity(identityToken);
692 }
Fred Quintana60307342009-03-24 22:48:12 -0700693 }
694
Fred Quintanaa698f422009-04-08 19:14:54 -0700695 public void setPassword(Account account, String password) {
Fred Quintana382601f2010-03-25 12:25:10 -0700696 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700697 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700698 long identityToken = clearCallingIdentity();
699 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700700 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700701 } finally {
702 restoreCallingIdentity(identityToken);
703 }
Fred Quintana60307342009-03-24 22:48:12 -0700704 }
705
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700706 private void setPasswordInDB(Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700707 if (account == null) {
708 return;
709 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800710 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
711 db.beginTransaction();
712 try {
713 final ContentValues values = new ContentValues();
714 values.put(ACCOUNTS_PASSWORD, password);
715 final long accountId = getAccountId(db, account);
716 if (accountId >= 0) {
717 final String[] argsAccountId = {String.valueOf(accountId)};
718 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
719 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
720 db.setTransactionSuccessful();
721 }
722 } finally {
723 db.endTransaction();
724 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700725 sendAccountsChangedBroadcast();
726 }
727
Fred Quintana33269202009-04-20 16:05:10 -0700728 private void sendAccountsChangedBroadcast() {
729 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
730 }
731
Fred Quintanaa698f422009-04-08 19:14:54 -0700732 public void clearPassword(Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700733 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700734 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700735 long identityToken = clearCallingIdentity();
736 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700737 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700738 } finally {
739 restoreCallingIdentity(identityToken);
740 }
Fred Quintana60307342009-03-24 22:48:12 -0700741 }
742
Fred Quintanaa698f422009-04-08 19:14:54 -0700743 public void setUserData(Account account, String key, String value) {
Fred Quintana382601f2010-03-25 12:25:10 -0700744 if (key == null) throw new IllegalArgumentException("key is null");
745 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700746 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700747 long identityToken = clearCallingIdentity();
Fred Quintana31957f12009-10-21 13:43:10 -0700748 if (account == null) {
749 return;
750 }
Jim Miller50c05f32009-09-21 19:07:44 -0700751 if (account.type.equals(GOOGLE_ACCOUNT_TYPE) && key.equals("broadcast")) {
752 sendAccountsChangedBroadcast();
753 return;
754 }
Fred Quintana60307342009-03-24 22:48:12 -0700755 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700756 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700757 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700758 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700759 }
760 }
761
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700762 private void writeUserdataIntoDatabase(Account account, String key, String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700763 if (account == null || key == null) {
764 return;
765 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700766 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
767 db.beginTransaction();
768 try {
769 long accountId = getAccountId(db, account);
770 if (accountId < 0) {
771 return;
772 }
773 long extrasId = getExtrasId(db, accountId, key);
774 if (extrasId < 0 ) {
775 extrasId = insertExtra(db, accountId, key, value);
776 if (extrasId < 0) {
777 return;
778 }
779 } else {
780 ContentValues values = new ContentValues();
781 values.put(EXTRAS_VALUE, value);
782 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
783 return;
784 }
785
786 }
787 db.setTransactionSuccessful();
788 } finally {
789 db.endTransaction();
790 }
791 }
792
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700793 private void onResult(IAccountManagerResponse response, Bundle result) {
794 try {
795 response.onResult(result);
796 } catch (RemoteException e) {
797 // if the caller is dead then there is no one to care about remote
798 // exceptions
799 if (Log.isLoggable(TAG, Log.VERBOSE)) {
800 Log.v(TAG, "failure while notifying response", e);
801 }
802 }
803 }
804
Costin Manolache5d275bb2010-12-02 16:44:46 -0800805 void getAuthTokenLabel(final IAccountManagerResponse response,
806 final Account account, final String authTokenType) {
807 if (account == null) throw new IllegalArgumentException("account is null");
808 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
809
810 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
811
812 long identityToken = clearCallingIdentity();
813 try {
814 new Session(response, account.type, false,
815 false /* stripAuthTokenFromResult */) {
816 protected String toDebugString(long now) {
817 return super.toDebugString(now) + ", getAuthTokenLabel"
818 + ", " + account
819 + ", authTokenType " + authTokenType;
820 }
821
822 public void run() throws RemoteException {
823 mAuthenticator.getAuthTokenLabel(this, authTokenType);
824 }
825
826 public void onResult(Bundle result) {
827 if (result != null) {
828 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
829 Bundle bundle = new Bundle();
830 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
831 super.onResult(bundle);
832 return;
833 } else {
834 super.onResult(result);
835 }
836 }
837 }.bind();
838 } finally {
839 restoreCallingIdentity(identityToken);
840 }
841 }
842
Fred Quintanaa698f422009-04-08 19:14:54 -0700843 public void getAuthToken(IAccountManagerResponse response, final Account account,
844 final String authTokenType, final boolean notifyOnAuthFailure,
845 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintana382601f2010-03-25 12:25:10 -0700846 if (response == null) throw new IllegalArgumentException("response is null");
847 if (account == null) throw new IllegalArgumentException("account is null");
848 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700849 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
850 final int callerUid = Binder.getCallingUid();
851 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
852
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700853 long identityToken = clearCallingIdentity();
854 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700855 // if the caller has permission, do the peek. otherwise go the more expensive
856 // route of starting a Session
857 if (permissionGranted) {
858 String authToken = readAuthTokenFromDatabase(account, authTokenType);
859 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700860 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700861 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
862 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
863 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700864 onResult(response, result);
865 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700866 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700867 }
868
Fred Quintana8570f742010-02-18 10:32:54 -0800869 new Session(response, account.type, expectActivityLaunch,
870 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700871 protected String toDebugString(long now) {
872 if (loginOptions != null) loginOptions.keySet();
873 return super.toDebugString(now) + ", getAuthToken"
874 + ", " + account
875 + ", authTokenType " + authTokenType
876 + ", loginOptions " + loginOptions
877 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
878 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700879
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700880 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700881 // If the caller doesn't have permission then create and return the
882 // "grant permission" intent instead of the "getAuthToken" intent.
883 if (!permissionGranted) {
884 mAuthenticator.getAuthTokenLabel(this, authTokenType);
885 } else {
886 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
887 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700888 }
889
890 public void onResult(Bundle result) {
891 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700892 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700893 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
894 new AccountAuthenticatorResponse(this),
895 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700896 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700897 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700898 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700899 onResult(bundle);
900 return;
901 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700902 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700903 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700904 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
905 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700906 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700907 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700908 "the type and name should not be empty");
909 return;
910 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700911 saveAuthTokenToDatabase(new Account(name, type),
912 authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700913 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700914
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700915 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700916 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700917 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700918 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700919 intent);
920 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700921 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700922 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700923 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700924 }.bind();
925 } finally {
926 restoreCallingIdentity(identityToken);
927 }
Fred Quintana60307342009-03-24 22:48:12 -0700928 }
929
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700930 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
931 int uid = intent.getIntExtra(
932 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
933 String authTokenType = intent.getStringExtra(
934 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
935 String authTokenLabel = intent.getStringExtra(
936 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
937
938 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
939 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700940 final String titleAndSubtitle =
941 mContext.getString(R.string.permission_request_notification_with_subtitle,
942 account.name);
943 final int index = titleAndSubtitle.indexOf('\n');
944 final String title = titleAndSubtitle.substring(0, index);
945 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700946 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700947 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700948 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
949 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
950 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
951 }
952
Costin Manolache5d275bb2010-12-02 16:44:46 -0800953 String getAccountLabel(String accountType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700954 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
Costin Manolache5d275bb2010-12-02 16:44:46 -0800955 mAuthenticatorCache.getServiceInfo(
956 AuthenticatorDescription.newKey(accountType));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700957 if (serviceInfo == null) {
Costin Manolache5d275bb2010-12-02 16:44:46 -0800958 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700959 }
960
961 final Context authContext;
962 try {
963 authContext = mContext.createPackageContext(
Costin Manolache5d275bb2010-12-02 16:44:46 -0800964 serviceInfo.type.packageName, 0);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700965 } catch (PackageManager.NameNotFoundException e) {
Costin Manolache5d275bb2010-12-02 16:44:46 -0800966 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700967 }
Costin Manolache5d275bb2010-12-02 16:44:46 -0800968 return authContext.getString(serviceInfo.type.labelId);
969 }
970
971 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
972 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700973
974 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700975 intent.addCategory(
976 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5d275bb2010-12-02 16:44:46 -0800977
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700978 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700979 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
980 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700981 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5d275bb2010-12-02 16:44:46 -0800982
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700983 return intent;
984 }
985
986 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
987 int uid) {
988 Integer id;
989 synchronized(mCredentialsPermissionNotificationIds) {
990 final Pair<Pair<Account, String>, Integer> key =
991 new Pair<Pair<Account, String>, Integer>(
992 new Pair<Account, String>(account, authTokenType), uid);
993 id = mCredentialsPermissionNotificationIds.get(key);
994 if (id == null) {
995 id = mNotificationIds.incrementAndGet();
996 mCredentialsPermissionNotificationIds.put(key, id);
997 }
998 }
999 return id;
1000 }
1001
1002 private Integer getSigninRequiredNotificationId(Account account) {
1003 Integer id;
1004 synchronized(mSigninRequiredNotificationIds) {
1005 id = mSigninRequiredNotificationIds.get(account);
1006 if (id == null) {
1007 id = mNotificationIds.incrementAndGet();
1008 mSigninRequiredNotificationIds.put(account, id);
1009 }
1010 }
1011 return id;
1012 }
1013
Fred Quintanaa698f422009-04-08 19:14:54 -07001014
Fred Quintana33269202009-04-20 16:05:10 -07001015 public void addAcount(final IAccountManagerResponse response, final String accountType,
1016 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -07001017 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintana382601f2010-03-25 12:25:10 -07001018 if (response == null) throw new IllegalArgumentException("response is null");
1019 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001020 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001021 long identityToken = clearCallingIdentity();
1022 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001023 new Session(response, accountType, expectActivityLaunch,
1024 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001025 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001026 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001027 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001028 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001029
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001030 protected String toDebugString(long now) {
1031 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001032 + ", accountType " + accountType
1033 + ", requiredFeatures "
1034 + (requiredFeatures != null
1035 ? TextUtils.join(",", requiredFeatures)
1036 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001037 }
1038 }.bind();
1039 } finally {
1040 restoreCallingIdentity(identityToken);
1041 }
Fred Quintana60307342009-03-24 22:48:12 -07001042 }
1043
Fred Quintanaa698f422009-04-08 19:14:54 -07001044 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001045 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintana382601f2010-03-25 12:25:10 -07001046 if (response == null) throw new IllegalArgumentException("response is null");
1047 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001048 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001049 long identityToken = clearCallingIdentity();
1050 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001051 new Session(response, account.type, expectActivityLaunch,
1052 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001053 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001054 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001055 }
1056 protected String toDebugString(long now) {
1057 return super.toDebugString(now) + ", confirmCredentials"
1058 + ", " + account;
1059 }
1060 }.bind();
1061 } finally {
1062 restoreCallingIdentity(identityToken);
1063 }
Fred Quintana60307342009-03-24 22:48:12 -07001064 }
1065
Fred Quintanaa698f422009-04-08 19:14:54 -07001066 public void updateCredentials(IAccountManagerResponse response, final Account account,
1067 final String authTokenType, final boolean expectActivityLaunch,
1068 final Bundle loginOptions) {
Fred Quintana382601f2010-03-25 12:25:10 -07001069 if (response == null) throw new IllegalArgumentException("response is null");
1070 if (account == null) throw new IllegalArgumentException("account is null");
1071 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001072 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001073 long identityToken = clearCallingIdentity();
1074 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001075 new Session(response, account.type, expectActivityLaunch,
1076 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001077 public void run() throws RemoteException {
1078 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1079 }
1080 protected String toDebugString(long now) {
1081 if (loginOptions != null) loginOptions.keySet();
1082 return super.toDebugString(now) + ", updateCredentials"
1083 + ", " + account
1084 + ", authTokenType " + authTokenType
1085 + ", loginOptions " + loginOptions;
1086 }
1087 }.bind();
1088 } finally {
1089 restoreCallingIdentity(identityToken);
1090 }
Fred Quintana60307342009-03-24 22:48:12 -07001091 }
1092
Fred Quintanaa698f422009-04-08 19:14:54 -07001093 public void editProperties(IAccountManagerResponse response, final String accountType,
1094 final boolean expectActivityLaunch) {
Fred Quintana382601f2010-03-25 12:25:10 -07001095 if (response == null) throw new IllegalArgumentException("response is null");
1096 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001097 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001098 long identityToken = clearCallingIdentity();
1099 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001100 new Session(response, accountType, expectActivityLaunch,
1101 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001102 public void run() throws RemoteException {
1103 mAuthenticator.editProperties(this, mAccountType);
1104 }
1105 protected String toDebugString(long now) {
1106 return super.toDebugString(now) + ", editProperties"
1107 + ", accountType " + accountType;
1108 }
1109 }.bind();
1110 } finally {
1111 restoreCallingIdentity(identityToken);
1112 }
Fred Quintana60307342009-03-24 22:48:12 -07001113 }
1114
Fred Quintana33269202009-04-20 16:05:10 -07001115 private class GetAccountsByTypeAndFeatureSession extends Session {
1116 private final String[] mFeatures;
1117 private volatile Account[] mAccountsOfType = null;
1118 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1119 private volatile int mCurrentAccount = 0;
1120
1121 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
1122 String type, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -08001123 super(response, type, false /* expectActivityLaunch */,
1124 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001125 mFeatures = features;
1126 }
1127
1128 public void run() throws RemoteException {
1129 mAccountsOfType = getAccountsByType(mAccountType);
1130 // check whether each account matches the requested features
1131 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1132 mCurrentAccount = 0;
1133
1134 checkAccount();
1135 }
1136
1137 public void checkAccount() {
1138 if (mCurrentAccount >= mAccountsOfType.length) {
1139 sendResult();
1140 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001141 }
Fred Quintana33269202009-04-20 16:05:10 -07001142
Fred Quintana29e94b82010-03-10 12:11:51 -08001143 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1144 if (accountAuthenticator == null) {
1145 // It is possible that the authenticator has died, which is indicated by
1146 // mAuthenticator being set to null. If this happens then just abort.
1147 // There is no need to send back a result or error in this case since
1148 // that already happened when mAuthenticator was cleared.
1149 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1150 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1151 + " connected to the authenticator, " + toDebugString());
1152 }
1153 return;
1154 }
Fred Quintana33269202009-04-20 16:05:10 -07001155 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001156 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001157 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001158 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001159 }
1160 }
1161
1162 public void onResult(Bundle result) {
1163 mNumResults++;
1164 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001165 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001166 return;
1167 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001168 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001169 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1170 }
1171 mCurrentAccount++;
1172 checkAccount();
1173 }
1174
1175 public void sendResult() {
1176 IAccountManagerResponse response = getResponseAndClose();
1177 if (response != null) {
1178 try {
1179 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1180 for (int i = 0; i < accounts.length; i++) {
1181 accounts[i] = mAccountsWithFeatures.get(i);
1182 }
1183 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001184 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001185 response.onResult(result);
1186 } catch (RemoteException e) {
1187 // if the caller is dead then there is no one to care about remote exceptions
1188 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1189 Log.v(TAG, "failure while notifying response", e);
1190 }
1191 }
1192 }
1193 }
1194
1195
1196 protected String toDebugString(long now) {
1197 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1198 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1199 }
1200 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001201
1202 public Account[] getAccounts(String type) {
1203 checkReadAccountsPermission();
1204 long identityToken = clearCallingIdentity();
1205 try {
1206 return getAccountsByType(type);
1207 } finally {
1208 restoreCallingIdentity(identityToken);
1209 }
1210 }
1211
1212 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001213 String type, String[] features) {
Fred Quintana382601f2010-03-25 12:25:10 -07001214 if (response == null) throw new IllegalArgumentException("response is null");
1215 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001216 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001217 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -07001218 if (response != null) {
1219 try {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001220 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "type is null");
Fred Quintana33269202009-04-20 16:05:10 -07001221 } catch (RemoteException e) {
1222 // ignore this
1223 }
1224 }
1225 return;
1226 }
1227 long identityToken = clearCallingIdentity();
1228 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001229 if (features == null || features.length == 0) {
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001230 Account[] accounts = getAccountsByType(type);
1231 Bundle result = new Bundle();
1232 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1233 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001234 return;
1235 }
Fred Quintana33269202009-04-20 16:05:10 -07001236 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1237 } finally {
1238 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001239 }
1240 }
1241
Fred Quintana60307342009-03-24 22:48:12 -07001242 private long getAccountId(SQLiteDatabase db, Account account) {
1243 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001244 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001245 try {
1246 if (cursor.moveToNext()) {
1247 return cursor.getLong(0);
1248 }
1249 return -1;
1250 } finally {
1251 cursor.close();
1252 }
1253 }
1254
1255 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1256 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1257 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1258 new String[]{key}, null, null, null);
1259 try {
1260 if (cursor.moveToNext()) {
1261 return cursor.getLong(0);
1262 }
1263 return -1;
1264 } finally {
1265 cursor.close();
1266 }
1267 }
1268
Fred Quintanaa698f422009-04-08 19:14:54 -07001269 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001270 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001271 IAccountManagerResponse mResponse;
1272 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001273 final boolean mExpectActivityLaunch;
1274 final long mCreationTime;
1275
Fred Quintana33269202009-04-20 16:05:10 -07001276 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001277 private int mNumRequestContinued = 0;
1278 private int mNumErrors = 0;
1279
Fred Quintana60307342009-03-24 22:48:12 -07001280
1281 IAccountAuthenticator mAuthenticator = null;
1282
Fred Quintana8570f742010-02-18 10:32:54 -08001283 private final boolean mStripAuthTokenFromResult;
1284
Fred Quintanaa698f422009-04-08 19:14:54 -07001285 public Session(IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001286 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001287 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001288 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001289 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana8570f742010-02-18 10:32:54 -08001290 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001291 mResponse = response;
1292 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001293 mExpectActivityLaunch = expectActivityLaunch;
1294 mCreationTime = SystemClock.elapsedRealtime();
1295 synchronized (mSessions) {
1296 mSessions.put(toString(), this);
1297 }
1298 try {
1299 response.asBinder().linkToDeath(this, 0 /* flags */);
1300 } catch (RemoteException e) {
1301 mResponse = null;
1302 binderDied();
1303 }
Fred Quintana60307342009-03-24 22:48:12 -07001304 }
1305
Fred Quintanaa698f422009-04-08 19:14:54 -07001306 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001307 if (mResponse == null) {
1308 // this session has already been closed
1309 return null;
1310 }
Fred Quintana60307342009-03-24 22:48:12 -07001311 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001312 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001313 return response;
1314 }
1315
Fred Quintanaa698f422009-04-08 19:14:54 -07001316 private void close() {
1317 synchronized (mSessions) {
1318 if (mSessions.remove(toString()) == null) {
1319 // the session was already closed, so bail out now
1320 return;
1321 }
1322 }
1323 if (mResponse != null) {
1324 // stop listening for response deaths
1325 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1326
1327 // clear this so that we don't accidentally send any further results
1328 mResponse = null;
1329 }
1330 cancelTimeout();
1331 unbind();
1332 }
1333
1334 public void binderDied() {
1335 mResponse = null;
1336 close();
1337 }
1338
1339 protected String toDebugString() {
1340 return toDebugString(SystemClock.elapsedRealtime());
1341 }
1342
1343 protected String toDebugString(long now) {
1344 return "Session: expectLaunch " + mExpectActivityLaunch
1345 + ", connected " + (mAuthenticator != null)
1346 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1347 + "/" + mNumErrors + ")"
1348 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1349 }
1350
Fred Quintana60307342009-03-24 22:48:12 -07001351 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001352 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1353 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1354 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001355 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001356 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001357 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001358 }
1359 }
1360
1361 private void unbind() {
1362 if (mAuthenticator != null) {
1363 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001364 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001365 }
1366 }
1367
1368 public void scheduleTimeout() {
1369 mMessageHandler.sendMessageDelayed(
1370 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1371 }
1372
1373 public void cancelTimeout() {
1374 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1375 }
1376
Fred Quintanab839afc2009-10-14 15:57:28 -07001377 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001378 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001379 try {
1380 run();
1381 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001382 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001383 "remote exception");
1384 }
Fred Quintana60307342009-03-24 22:48:12 -07001385 }
1386
Fred Quintanab839afc2009-10-14 15:57:28 -07001387 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001388 mAuthenticator = null;
1389 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001390 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001391 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001392 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001393 }
1394 }
1395
Fred Quintanab839afc2009-10-14 15:57:28 -07001396 public abstract void run() throws RemoteException;
1397
Fred Quintana60307342009-03-24 22:48:12 -07001398 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001399 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001400 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001401 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001402 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001403 }
1404 }
1405
Fred Quintanaa698f422009-04-08 19:14:54 -07001406 public void onResult(Bundle result) {
1407 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001408 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1409 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1410 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001411 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1412 Account account = new Account(accountName, accountType);
1413 cancelNotification(getSigninRequiredNotificationId(account));
1414 }
Fred Quintana60307342009-03-24 22:48:12 -07001415 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001416 IAccountManagerResponse response;
1417 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001418 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001419 response = mResponse;
1420 } else {
1421 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001422 }
Fred Quintana60307342009-03-24 22:48:12 -07001423 if (response != null) {
1424 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001425 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001426 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001427 "null bundle returned");
1428 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001429 if (mStripAuthTokenFromResult) {
1430 result.remove(AccountManager.KEY_AUTHTOKEN);
1431 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001432 response.onResult(result);
1433 }
Fred Quintana60307342009-03-24 22:48:12 -07001434 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001435 // if the caller is dead then there is no one to care about remote exceptions
1436 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1437 Log.v(TAG, "failure while notifying response", e);
1438 }
Fred Quintana60307342009-03-24 22:48:12 -07001439 }
1440 }
1441 }
Fred Quintana60307342009-03-24 22:48:12 -07001442
Fred Quintanaa698f422009-04-08 19:14:54 -07001443 public void onRequestContinued() {
1444 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001445 }
1446
1447 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001448 mNumErrors++;
1449 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1450 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001451 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001452 IAccountManagerResponse response = getResponseAndClose();
1453 if (response != null) {
1454 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1455 Log.v(TAG, "Session.onError: responding");
1456 }
1457 try {
1458 response.onError(errorCode, errorMessage);
1459 } catch (RemoteException e) {
1460 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1461 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1462 }
1463 }
1464 } else {
1465 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1466 Log.v(TAG, "Session.onError: already closed");
1467 }
Fred Quintana60307342009-03-24 22:48:12 -07001468 }
1469 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001470
1471 /**
1472 * find the component name for the authenticator and initiate a bind
1473 * if no authenticator or the bind fails then return false, otherwise return true
1474 */
1475 private boolean bindToAuthenticator(String authenticatorType) {
1476 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1477 mAuthenticatorCache.getServiceInfo(
1478 AuthenticatorDescription.newKey(authenticatorType));
1479 if (authenticatorInfo == null) {
1480 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1481 Log.v(TAG, "there is no authenticator for " + authenticatorType
1482 + ", bailing out");
1483 }
1484 return false;
1485 }
1486
1487 Intent intent = new Intent();
1488 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1489 intent.setComponent(authenticatorInfo.componentName);
1490 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1491 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1492 }
1493 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1494 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1495 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1496 }
1497 return false;
1498 }
1499
1500
1501 return true;
1502 }
Fred Quintana60307342009-03-24 22:48:12 -07001503 }
1504
1505 private class MessageHandler extends Handler {
1506 MessageHandler(Looper looper) {
1507 super(looper);
1508 }
Costin Manolache3348f142009-09-29 18:58:36 -07001509
Fred Quintana60307342009-03-24 22:48:12 -07001510 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001511 switch (msg.what) {
1512 case MESSAGE_TIMED_OUT:
1513 Session session = (Session)msg.obj;
1514 session.onTimedOut();
1515 break;
1516
1517 default:
1518 throw new IllegalStateException("unhandled message: " + msg.what);
1519 }
1520 }
1521 }
1522
Oscar Montemayora8529f62009-11-18 10:14:20 -08001523 private static String getDatabaseName() {
1524 if(Environment.isEncryptedFilesystemEnabled()) {
1525 // Hard-coded path in case of encrypted file system
1526 return Environment.getSystemSecureDirectory().getPath() + File.separator + DATABASE_NAME;
1527 } else {
1528 // Regular path in case of non-encrypted file system
1529 return DATABASE_NAME;
1530 }
1531 }
1532
Fred Quintana60307342009-03-24 22:48:12 -07001533 private class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001534
Fred Quintana60307342009-03-24 22:48:12 -07001535 public DatabaseHelper(Context context) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001536 super(context, AccountManagerService.getDatabaseName(), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001537 }
1538
1539 @Override
1540 public void onCreate(SQLiteDatabase db) {
1541 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1542 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1543 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1544 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1545 + ACCOUNTS_PASSWORD + " TEXT, "
1546 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1547
1548 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1549 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1550 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1551 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1552 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1553 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1554
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001555 createGrantsTable(db);
1556
Fred Quintana60307342009-03-24 22:48:12 -07001557 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1558 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1559 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1560 + EXTRAS_KEY + " TEXT NOT NULL, "
1561 + EXTRAS_VALUE + " TEXT, "
1562 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1563
1564 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1565 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1566 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001567
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001568 createAccountsDeletionTrigger(db);
1569 }
1570
1571 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001572 db.execSQL(""
1573 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1574 + " BEGIN"
1575 + " DELETE FROM " + TABLE_AUTHTOKENS
1576 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1577 + " DELETE FROM " + TABLE_EXTRAS
1578 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001579 + " DELETE FROM " + TABLE_GRANTS
1580 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001581 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001582 }
1583
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001584 private void createGrantsTable(SQLiteDatabase db) {
1585 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1586 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1587 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1588 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1589 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1590 + "," + GRANTS_GRANTEE_UID + "))");
1591 }
1592
Fred Quintana60307342009-03-24 22:48:12 -07001593 @Override
1594 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001595 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001596
Fred Quintanaa698f422009-04-08 19:14:54 -07001597 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001598 // no longer need to do anything since the work is done
1599 // when upgrading from version 2
1600 oldVersion++;
1601 }
1602
1603 if (oldVersion == 2) {
1604 createGrantsTable(db);
1605 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1606 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001607 oldVersion++;
1608 }
Costin Manolache3348f142009-09-29 18:58:36 -07001609
1610 if (oldVersion == 3) {
1611 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1612 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1613 oldVersion++;
1614 }
Fred Quintana60307342009-03-24 22:48:12 -07001615 }
1616
1617 @Override
1618 public void onOpen(SQLiteDatabase db) {
1619 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1620 }
1621 }
1622
1623 private void setMetaValue(String key, String value) {
1624 ContentValues values = new ContentValues();
1625 values.put(META_KEY, key);
1626 values.put(META_VALUE, value);
1627 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1628 }
1629
1630 private String getMetaValue(String key) {
1631 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1632 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1633 try {
1634 if (c.moveToNext()) {
1635 return c.getString(0);
1636 }
1637 return null;
1638 } finally {
1639 c.close();
1640 }
1641 }
1642
1643 private class SimWatcher extends BroadcastReceiver {
1644 public SimWatcher(Context context) {
1645 // Re-scan the SIM card when the SIM state changes, and also if
1646 // the disk recovers from a full state (we may have failed to handle
1647 // things properly while the disk was full).
1648 final IntentFilter filter = new IntentFilter();
1649 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1650 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1651 context.registerReceiver(this, filter);
1652 }
Costin Manolache3348f142009-09-29 18:58:36 -07001653
Fred Quintana60307342009-03-24 22:48:12 -07001654 /**
1655 * Compare the IMSI to the one stored in the login service's
1656 * database. If they differ, erase all passwords and
1657 * authtokens (and store the new IMSI).
1658 */
1659 @Override
1660 public void onReceive(Context context, Intent intent) {
Doug Zongker885cfc232009-10-21 16:52:44 -07001661 // Check IMSI on every update; nothing happens if the IMSI
1662 // is missing or unchanged.
1663 TelephonyManager telephonyManager =
1664 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1665 if (telephonyManager == null) {
1666 Log.w(TAG, "failed to get TelephonyManager");
1667 return;
1668 }
1669 String imsi = telephonyManager.getSubscriberId();
1670
1671 // If the subscriber ID is an empty string, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001672 if (TextUtils.isEmpty(imsi)) return;
1673
Doug Zongker885cfc232009-10-21 16:52:44 -07001674 // If the current IMSI matches what's stored, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001675 String storedImsi = getMetaValue("imsi");
Fred Quintana60307342009-03-24 22:48:12 -07001676 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1677 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1678 }
Doug Zongker885cfc232009-10-21 16:52:44 -07001679 if (imsi.equals(storedImsi)) return;
1680
1681 // If a CDMA phone is unprovisioned, getSubscriberId()
1682 // will return a different value, but we *don't* erase the
1683 // passwords. We only erase them if it has a different
1684 // subscriber ID once it's provisioned.
1685 if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
1686 IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
1687 if (service == null) {
1688 Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
1689 return;
1690 }
1691 ITelephony telephony = ITelephony.Stub.asInterface(service);
1692 if (telephony == null) {
1693 Log.w(TAG, "failed to get ITelephony interface");
1694 return;
1695 }
1696 boolean needsProvisioning;
1697 try {
1698 needsProvisioning = telephony.getCdmaNeedsProvisioning();
1699 } catch (RemoteException e) {
1700 Log.w(TAG, "exception while checking provisioning", e);
1701 // default to NOT wiping out the passwords
1702 needsProvisioning = true;
1703 }
1704 if (needsProvisioning) {
1705 // if the phone needs re-provisioning, don't do anything.
1706 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1707 Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
1708 storedImsi);
1709 }
1710 return;
1711 }
1712 }
Fred Quintana60307342009-03-24 22:48:12 -07001713
jsh5b462472009-09-01 16:13:55 -07001714 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001715 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1716 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001717 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1718 db.beginTransaction();
1719 try {
1720 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1721 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001722 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001723 db.setTransactionSuccessful();
1724 } finally {
1725 db.endTransaction();
1726 }
1727 }
1728 setMetaValue("imsi", imsi);
1729 }
1730 }
1731
1732 public IBinder onBind(Intent intent) {
1733 return asBinder();
1734 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001735
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001736 /**
1737 * Searches array of arguments for the specified string
1738 * @param args array of argument strings
1739 * @param value value to search for
1740 * @return true if the value is contained in the array
1741 */
1742 private static boolean scanArgs(String[] args, String value) {
1743 if (args != null) {
1744 for (String arg : args) {
1745 if (value.equals(arg)) {
1746 return true;
1747 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001748 }
1749 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001750 return false;
1751 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001752
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001753 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1754 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001755
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001756 if (isCheckinRequest) {
1757 // This is a checkin request. *Only* upload the account types and the count of each.
1758 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1759
1760 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1761 null, null, ACCOUNTS_TYPE, null, null);
1762 try {
1763 while (cursor.moveToNext()) {
1764 // print type,count
1765 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1766 }
1767 } finally {
1768 if (cursor != null) {
1769 cursor.close();
1770 }
1771 }
1772 } else {
Fred Quintanac2e46912010-03-15 16:10:44 -07001773 Account[] accounts = getAccountsByType(null /* type */);
Fred Quintana307da1a2010-01-21 14:24:20 -08001774 fout.println("Accounts: " + accounts.length);
1775 for (Account account : accounts) {
1776 fout.println(" " + account);
1777 }
1778
1779 fout.println();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001780 synchronized (mSessions) {
1781 final long now = SystemClock.elapsedRealtime();
Fred Quintana307da1a2010-01-21 14:24:20 -08001782 fout.println("Active Sessions: " + mSessions.size());
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001783 for (Session session : mSessions.values()) {
1784 fout.println(" " + session.toDebugString(now));
1785 }
1786 }
1787
1788 fout.println();
1789 mAuthenticatorCache.dump(fd, fout, args);
1790 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001791 }
1792
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001793 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001794 long identityToken = clearCallingIdentity();
1795 try {
1796 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1797 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1798 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001799
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001800 if (intent.getComponent() != null &&
1801 GrantCredentialsPermissionActivity.class.getName().equals(
1802 intent.getComponent().getClassName())) {
1803 createNoCredentialsPermissionNotification(account, intent);
1804 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001805 final Integer notificationId = getSigninRequiredNotificationId(account);
1806 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001807 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1808 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001809 final String notificationTitleFormat =
1810 mContext.getText(R.string.notification_title).toString();
1811 n.setLatestEventInfo(mContext,
1812 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001813 message, PendingIntent.getActivity(
1814 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1815 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001816 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001817 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001818 } finally {
1819 restoreCallingIdentity(identityToken);
1820 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001821 }
1822
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001823 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001824 long identityToken = clearCallingIdentity();
1825 try {
1826 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001827 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001828 } finally {
1829 restoreCallingIdentity(identityToken);
1830 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001831 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001832
Fred Quintanab38eb142010-02-24 13:40:54 -08001833 /** Succeeds if any of the specified permissions are granted. */
1834 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001835 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08001836
1837 for (String perm : permissions) {
1838 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
1839 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1840 Log.v(TAG, "caller uid " + uid + " has " + perm);
1841 }
1842 return;
1843 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001844 }
Fred Quintanab38eb142010-02-24 13:40:54 -08001845
1846 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
1847 Log.w(TAG, msg);
1848 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001849 }
1850
Fred Quintana7be59642009-08-24 18:29:25 -07001851 private boolean inSystemImage(int callerUid) {
1852 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1853 for (String name : packages) {
1854 try {
1855 PackageInfo packageInfo =
1856 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1857 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1858 return true;
1859 }
1860 } catch (PackageManager.NameNotFoundException e) {
1861 return false;
1862 }
1863 }
1864 return false;
1865 }
1866
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001867 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001868 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07001869 final boolean fromAuthenticator = account != null
1870 && hasAuthenticatorUid(account.type, callerUid);
1871 final boolean hasExplicitGrants = account != null
1872 && hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001873 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1874 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1875 + callerUid + ", account " + account
1876 + ": is authenticator? " + fromAuthenticator
1877 + ", has explicit permission? " + hasExplicitGrants);
1878 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001879 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001880 }
1881
Fred Quintana1a231912009-10-15 11:31:30 -07001882 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001883 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1884 mAuthenticatorCache.getAllServices()) {
1885 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001886 return (serviceInfo.uid == callingUid) ||
1887 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1888 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001889 }
1890 }
1891 return false;
1892 }
1893
1894 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1895 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1896 return true;
1897 }
1898 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1899 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001900 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001901 final boolean permissionGranted =
1902 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1903 if (!permissionGranted && isDebuggableMonkeyBuild) {
1904 // TODO: Skip this check when running automated tests. Replace this
1905 // with a more general solution.
Fred Quintana751fdc02010-02-09 14:13:18 -08001906 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001907 + authTokenType + " by uid " + Binder.getCallingUid()
1908 + " but ignoring since this is a monkey build");
1909 return true;
1910 }
1911 return permissionGranted;
1912 }
1913
1914 private void checkCallingUidAgainstAuthenticator(Account account) {
1915 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07001916 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001917 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1918 Log.w(TAG, msg);
1919 throw new SecurityException(msg);
1920 }
1921 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1922 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1923 }
1924 }
1925
1926 private void checkAuthenticateAccountsPermission(Account account) {
1927 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1928 checkCallingUidAgainstAuthenticator(account);
1929 }
1930
1931 private void checkReadAccountsPermission() {
1932 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1933 }
1934
1935 private void checkManageAccountsPermission() {
1936 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1937 }
1938
Fred Quintanab38eb142010-02-24 13:40:54 -08001939 private void checkManageAccountsOrUseCredentialsPermissions() {
1940 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
1941 Manifest.permission.USE_CREDENTIALS);
1942 }
1943
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001944 /**
1945 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1946 * <p>
1947 * Although this is public it can only be accessed via the AccountManagerService object
1948 * which is in the system. This means we don't need to protect it with permissions.
1949 * @hide
1950 */
1951 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07001952 if (account == null || authTokenType == null) {
1953 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07001954 return;
1955 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001956 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1957 db.beginTransaction();
1958 try {
1959 long accountId = getAccountId(db, account);
1960 if (accountId >= 0) {
1961 ContentValues values = new ContentValues();
1962 values.put(GRANTS_ACCOUNTS_ID, accountId);
1963 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1964 values.put(GRANTS_GRANTEE_UID, uid);
1965 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1966 db.setTransactionSuccessful();
1967 }
1968 } finally {
1969 db.endTransaction();
1970 }
1971 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1972 }
1973
1974 /**
1975 * Don't allow callers with the given uid permission to get credentials for
1976 * account/authTokenType.
1977 * <p>
1978 * Although this is public it can only be accessed via the AccountManagerService object
1979 * which is in the system. This means we don't need to protect it with permissions.
1980 * @hide
1981 */
1982 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07001983 if (account == null || authTokenType == null) {
1984 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07001985 return;
1986 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001987 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1988 db.beginTransaction();
1989 try {
1990 long accountId = getAccountId(db, account);
1991 if (accountId >= 0) {
1992 db.delete(TABLE_GRANTS,
1993 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1994 + GRANTS_GRANTEE_UID + "=?",
1995 new String[]{String.valueOf(accountId), authTokenType,
1996 String.valueOf(uid)});
1997 db.setTransactionSuccessful();
1998 }
1999 } finally {
2000 db.endTransaction();
2001 }
2002 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
2003 }
Fred Quintana60307342009-03-24 22:48:12 -07002004}