blob: 8471df9b03d266dfd33e1a2b098d06fbb6f04c67 [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();
Fred Quintana743dfad2010-07-15 10:59:25 -0700402 if (account == null) {
403 return false;
404 }
405 final boolean noBroadcast = account.type.equals(GOOGLE_ACCOUNT_TYPE)
406 && extras != null && extras.getBoolean(NO_BROADCAST_FLAG, false);
407 // Remove the 'nobroadcast' flag since we don't want it to persist in the db. It is instead
408 // used as a control signal to indicate whether or not this insertion should result in
409 // an accounts changed broadcast being sent.
410 if (extras != null) {
411 extras.remove(NO_BROADCAST_FLAG);
412 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700413 db.beginTransaction();
414 try {
415 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();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700439 } finally {
440 db.endTransaction();
441 }
Fred Quintana743dfad2010-07-15 10:59:25 -0700442 if (!noBroadcast) {
443 sendAccountsChangedBroadcast();
444 }
445 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700446 }
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();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800523
524 cancelNotification(getSigninRequiredNotificationId(account));
525 synchronized(mCredentialsPermissionNotificationIds) {
526 for (Pair<Pair<Account, String>, Integer> pair:
527 mCredentialsPermissionNotificationIds.keySet()) {
528 if (account.equals(pair.first.first)) {
529 int id = mCredentialsPermissionNotificationIds.get(pair);
530 cancelNotification(id);
531 }
532 }
533 }
534
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700535 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700536 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700537 } finally {
538 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700539 }
Fred Quintana60307342009-03-24 22:48:12 -0700540 }
541
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700542 private class RemoveAccountSession extends Session {
543 final Account mAccount;
544 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
Fred Quintana8570f742010-02-18 10:32:54 -0800545 super(response, account.type, false /* expectActivityLaunch */,
546 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700547 mAccount = account;
548 }
549
550 protected String toDebugString(long now) {
551 return super.toDebugString(now) + ", removeAccount"
552 + ", account " + mAccount;
553 }
554
555 public void run() throws RemoteException {
556 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
557 }
558
559 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700560 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
561 && !result.containsKey(AccountManager.KEY_INTENT)) {
562 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700563 if (removalAllowed) {
564 removeAccount(mAccount);
565 }
566 IAccountManagerResponse response = getResponseAndClose();
567 if (response != null) {
568 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700569 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700570 try {
571 response.onResult(result2);
572 } catch (RemoteException e) {
573 // ignore
574 }
575 }
576 }
577 super.onResult(result);
578 }
579 }
580
581 private void removeAccount(Account account) {
582 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
583 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
584 new String[]{account.name, account.type});
585 sendAccountsChangedBroadcast();
586 }
587
Fred Quintanaa698f422009-04-08 19:14:54 -0700588 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700589 if (accountType == null) throw new IllegalArgumentException("accountType is null");
590 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800591 checkManageAccountsOrUseCredentialsPermissions();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700592 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700593 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700594 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
595 db.beginTransaction();
596 try {
597 invalidateAuthToken(db, accountType, authToken);
598 db.setTransactionSuccessful();
599 } finally {
600 db.endTransaction();
601 }
Fred Quintana60307342009-03-24 22:48:12 -0700602 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700603 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700604 }
605 }
606
607 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700608 if (authToken == null || accountType == null) {
609 return;
610 }
Fred Quintana33269202009-04-20 16:05:10 -0700611 Cursor cursor = db.rawQuery(
612 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
613 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
614 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
615 + " FROM " + TABLE_ACCOUNTS
616 + " JOIN " + TABLE_AUTHTOKENS
617 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
618 + " = " + AUTHTOKENS_ACCOUNTS_ID
619 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
620 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
621 new String[]{authToken, accountType});
622 try {
623 while (cursor.moveToNext()) {
624 long authTokenId = cursor.getLong(0);
625 String accountName = cursor.getString(1);
626 String authTokenType = cursor.getString(2);
627 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700628 }
Fred Quintana33269202009-04-20 16:05:10 -0700629 } finally {
630 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700631 }
632 }
633
634 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700635 if (account == null || type == null) {
636 return false;
637 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700638 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700639 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
640 db.beginTransaction();
641 try {
Fred Quintana33269202009-04-20 16:05:10 -0700642 long accountId = getAccountId(db, account);
643 if (accountId < 0) {
644 return false;
645 }
646 db.delete(TABLE_AUTHTOKENS,
647 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
648 new String[]{type});
649 ContentValues values = new ContentValues();
650 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
651 values.put(AUTHTOKENS_TYPE, type);
652 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
653 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700654 db.setTransactionSuccessful();
655 return true;
656 }
657 return false;
658 } finally {
659 db.endTransaction();
660 }
661 }
662
Fred Quintana60307342009-03-24 22:48:12 -0700663 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
Fred Quintana31957f12009-10-21 13:43:10 -0700664 if (account == null || authTokenType == null) {
665 return null;
666 }
Fred Quintana60307342009-03-24 22:48:12 -0700667 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700668 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
669 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
670 + AUTHTOKENS_TYPE + "=?",
671 new String[]{account.name, account.type, authTokenType},
672 null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700673 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700674 if (cursor.moveToNext()) {
675 return cursor.getString(0);
Fred Quintana60307342009-03-24 22:48:12 -0700676 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700677 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700678 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700679 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700680 }
681 }
682
Fred Quintanaa698f422009-04-08 19:14:54 -0700683 public String peekAuthToken(Account account, String authTokenType) {
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 Quintana33269202009-04-20 16:05:10 -0700689 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700690 } finally {
691 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700692 }
Fred Quintana60307342009-03-24 22:48:12 -0700693 }
694
Fred Quintanaa698f422009-04-08 19:14:54 -0700695 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana382601f2010-03-25 12:25:10 -0700696 if (account == null) throw new IllegalArgumentException("account is null");
697 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700698 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700699 long identityToken = clearCallingIdentity();
700 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700701 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700702 } finally {
703 restoreCallingIdentity(identityToken);
704 }
Fred Quintana60307342009-03-24 22:48:12 -0700705 }
706
Fred Quintanaa698f422009-04-08 19:14:54 -0700707 public void setPassword(Account account, String password) {
Fred Quintana382601f2010-03-25 12:25:10 -0700708 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700709 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700710 long identityToken = clearCallingIdentity();
711 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700712 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700713 } finally {
714 restoreCallingIdentity(identityToken);
715 }
Fred Quintana60307342009-03-24 22:48:12 -0700716 }
717
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700718 private void setPasswordInDB(Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700719 if (account == null) {
720 return;
721 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800722 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
723 db.beginTransaction();
724 try {
725 final ContentValues values = new ContentValues();
726 values.put(ACCOUNTS_PASSWORD, password);
727 final long accountId = getAccountId(db, account);
728 if (accountId >= 0) {
729 final String[] argsAccountId = {String.valueOf(accountId)};
730 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
731 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
732 db.setTransactionSuccessful();
733 }
734 } finally {
735 db.endTransaction();
736 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700737 sendAccountsChangedBroadcast();
738 }
739
Fred Quintana33269202009-04-20 16:05:10 -0700740 private void sendAccountsChangedBroadcast() {
741 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
742 }
743
Fred Quintanaa698f422009-04-08 19:14:54 -0700744 public void clearPassword(Account account) {
Fred Quintana382601f2010-03-25 12:25:10 -0700745 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700746 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700747 long identityToken = clearCallingIdentity();
748 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700749 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700750 } finally {
751 restoreCallingIdentity(identityToken);
752 }
Fred Quintana60307342009-03-24 22:48:12 -0700753 }
754
Fred Quintanaa698f422009-04-08 19:14:54 -0700755 public void setUserData(Account account, String key, String value) {
Fred Quintana382601f2010-03-25 12:25:10 -0700756 if (key == null) throw new IllegalArgumentException("key is null");
757 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700758 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700759 long identityToken = clearCallingIdentity();
Fred Quintana31957f12009-10-21 13:43:10 -0700760 if (account == null) {
761 return;
762 }
Jim Miller50c05f32009-09-21 19:07:44 -0700763 if (account.type.equals(GOOGLE_ACCOUNT_TYPE) && key.equals("broadcast")) {
764 sendAccountsChangedBroadcast();
765 return;
766 }
Fred Quintana60307342009-03-24 22:48:12 -0700767 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700768 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700769 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700770 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700771 }
772 }
773
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700774 private void writeUserdataIntoDatabase(Account account, String key, String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700775 if (account == null || key == null) {
776 return;
777 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700778 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
779 db.beginTransaction();
780 try {
781 long accountId = getAccountId(db, account);
782 if (accountId < 0) {
783 return;
784 }
785 long extrasId = getExtrasId(db, accountId, key);
786 if (extrasId < 0 ) {
787 extrasId = insertExtra(db, accountId, key, value);
788 if (extrasId < 0) {
789 return;
790 }
791 } else {
792 ContentValues values = new ContentValues();
793 values.put(EXTRAS_VALUE, value);
794 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
795 return;
796 }
797
798 }
799 db.setTransactionSuccessful();
800 } finally {
801 db.endTransaction();
802 }
803 }
804
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700805 private void onResult(IAccountManagerResponse response, Bundle result) {
806 try {
807 response.onResult(result);
808 } catch (RemoteException e) {
809 // if the caller is dead then there is no one to care about remote
810 // exceptions
811 if (Log.isLoggable(TAG, Log.VERBOSE)) {
812 Log.v(TAG, "failure while notifying response", e);
813 }
814 }
815 }
816
Fred Quintanaa698f422009-04-08 19:14:54 -0700817 public void getAuthToken(IAccountManagerResponse response, final Account account,
818 final String authTokenType, final boolean notifyOnAuthFailure,
819 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintana382601f2010-03-25 12:25:10 -0700820 if (response == null) throw new IllegalArgumentException("response is null");
821 if (account == null) throw new IllegalArgumentException("account is null");
822 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700823 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
824 final int callerUid = Binder.getCallingUid();
825 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
826
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700827 long identityToken = clearCallingIdentity();
828 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700829 // if the caller has permission, do the peek. otherwise go the more expensive
830 // route of starting a Session
831 if (permissionGranted) {
832 String authToken = readAuthTokenFromDatabase(account, authTokenType);
833 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700834 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700835 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
836 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
837 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700838 onResult(response, result);
839 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700840 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700841 }
842
Fred Quintana8570f742010-02-18 10:32:54 -0800843 new Session(response, account.type, expectActivityLaunch,
844 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700845 protected String toDebugString(long now) {
846 if (loginOptions != null) loginOptions.keySet();
847 return super.toDebugString(now) + ", getAuthToken"
848 + ", " + account
849 + ", authTokenType " + authTokenType
850 + ", loginOptions " + loginOptions
851 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
852 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700853
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700854 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700855 // If the caller doesn't have permission then create and return the
856 // "grant permission" intent instead of the "getAuthToken" intent.
857 if (!permissionGranted) {
858 mAuthenticator.getAuthTokenLabel(this, authTokenType);
859 } else {
860 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
861 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700862 }
863
864 public void onResult(Bundle result) {
865 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700866 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700867 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
868 new AccountAuthenticatorResponse(this),
869 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700870 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700871 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700872 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700873 onResult(bundle);
874 return;
875 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700876 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700877 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700878 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
879 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700880 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700881 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700882 "the type and name should not be empty");
883 return;
884 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700885 saveAuthTokenToDatabase(new Account(name, type),
886 authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700887 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700888
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700889 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700890 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700891 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700892 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700893 intent);
894 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700895 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700896 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700897 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700898 }.bind();
899 } finally {
900 restoreCallingIdentity(identityToken);
901 }
Fred Quintana60307342009-03-24 22:48:12 -0700902 }
903
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700904 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
905 int uid = intent.getIntExtra(
906 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
907 String authTokenType = intent.getStringExtra(
908 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
909 String authTokenLabel = intent.getStringExtra(
910 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
911
912 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
913 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700914 final String titleAndSubtitle =
915 mContext.getString(R.string.permission_request_notification_with_subtitle,
916 account.name);
917 final int index = titleAndSubtitle.indexOf('\n');
918 final String title = titleAndSubtitle.substring(0, index);
919 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700920 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700921 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700922 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
923 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
924 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
925 }
926
927 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
928 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
929 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
930 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700931 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700932 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700933 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700934 }
935
936 final Context authContext;
937 try {
938 authContext = mContext.createPackageContext(
939 serviceInfo.type.packageName, 0);
940 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700941 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700942 }
943
944 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
945 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
946 intent.addCategory(
947 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
948 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
949 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
950 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
951 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
952 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
953 authContext.getString(serviceInfo.type.labelId));
954 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
955 mContext.getPackageManager().getPackagesForUid(uid));
956 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
957 return intent;
958 }
959
960 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
961 int uid) {
962 Integer id;
963 synchronized(mCredentialsPermissionNotificationIds) {
964 final Pair<Pair<Account, String>, Integer> key =
965 new Pair<Pair<Account, String>, Integer>(
966 new Pair<Account, String>(account, authTokenType), uid);
967 id = mCredentialsPermissionNotificationIds.get(key);
968 if (id == null) {
969 id = mNotificationIds.incrementAndGet();
970 mCredentialsPermissionNotificationIds.put(key, id);
971 }
972 }
973 return id;
974 }
975
976 private Integer getSigninRequiredNotificationId(Account account) {
977 Integer id;
978 synchronized(mSigninRequiredNotificationIds) {
979 id = mSigninRequiredNotificationIds.get(account);
980 if (id == null) {
981 id = mNotificationIds.incrementAndGet();
982 mSigninRequiredNotificationIds.put(account, id);
983 }
984 }
985 return id;
986 }
987
Fred Quintanaa698f422009-04-08 19:14:54 -0700988
Fred Quintana33269202009-04-20 16:05:10 -0700989 public void addAcount(final IAccountManagerResponse response, final String accountType,
990 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700991 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintana382601f2010-03-25 12:25:10 -0700992 if (response == null) throw new IllegalArgumentException("response is null");
993 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700994 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700995 long identityToken = clearCallingIdentity();
996 try {
Fred Quintana8570f742010-02-18 10:32:54 -0800997 new Session(response, accountType, expectActivityLaunch,
998 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700999 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001000 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001001 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001002 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001003
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001004 protected String toDebugString(long now) {
1005 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001006 + ", accountType " + accountType
1007 + ", requiredFeatures "
1008 + (requiredFeatures != null
1009 ? TextUtils.join(",", requiredFeatures)
1010 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001011 }
1012 }.bind();
1013 } finally {
1014 restoreCallingIdentity(identityToken);
1015 }
Fred Quintana60307342009-03-24 22:48:12 -07001016 }
1017
Fred Quintanaa698f422009-04-08 19:14:54 -07001018 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001019 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintana382601f2010-03-25 12:25:10 -07001020 if (response == null) throw new IllegalArgumentException("response is null");
1021 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001022 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001023 long identityToken = clearCallingIdentity();
1024 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001025 new Session(response, account.type, expectActivityLaunch,
1026 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001027 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001028 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001029 }
1030 protected String toDebugString(long now) {
1031 return super.toDebugString(now) + ", confirmCredentials"
1032 + ", " + account;
1033 }
1034 }.bind();
1035 } finally {
1036 restoreCallingIdentity(identityToken);
1037 }
Fred Quintana60307342009-03-24 22:48:12 -07001038 }
1039
Fred Quintanaa698f422009-04-08 19:14:54 -07001040 public void updateCredentials(IAccountManagerResponse response, final Account account,
1041 final String authTokenType, final boolean expectActivityLaunch,
1042 final Bundle loginOptions) {
Fred Quintana382601f2010-03-25 12:25:10 -07001043 if (response == null) throw new IllegalArgumentException("response is null");
1044 if (account == null) throw new IllegalArgumentException("account is null");
1045 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001046 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001047 long identityToken = clearCallingIdentity();
1048 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001049 new Session(response, account.type, expectActivityLaunch,
1050 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001051 public void run() throws RemoteException {
1052 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1053 }
1054 protected String toDebugString(long now) {
1055 if (loginOptions != null) loginOptions.keySet();
1056 return super.toDebugString(now) + ", updateCredentials"
1057 + ", " + account
1058 + ", authTokenType " + authTokenType
1059 + ", loginOptions " + loginOptions;
1060 }
1061 }.bind();
1062 } finally {
1063 restoreCallingIdentity(identityToken);
1064 }
Fred Quintana60307342009-03-24 22:48:12 -07001065 }
1066
Fred Quintanaa698f422009-04-08 19:14:54 -07001067 public void editProperties(IAccountManagerResponse response, final String accountType,
1068 final boolean expectActivityLaunch) {
Fred Quintana382601f2010-03-25 12:25:10 -07001069 if (response == null) throw new IllegalArgumentException("response is null");
1070 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001071 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001072 long identityToken = clearCallingIdentity();
1073 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001074 new Session(response, accountType, expectActivityLaunch,
1075 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001076 public void run() throws RemoteException {
1077 mAuthenticator.editProperties(this, mAccountType);
1078 }
1079 protected String toDebugString(long now) {
1080 return super.toDebugString(now) + ", editProperties"
1081 + ", accountType " + accountType;
1082 }
1083 }.bind();
1084 } finally {
1085 restoreCallingIdentity(identityToken);
1086 }
Fred Quintana60307342009-03-24 22:48:12 -07001087 }
1088
Fred Quintana33269202009-04-20 16:05:10 -07001089 private class GetAccountsByTypeAndFeatureSession extends Session {
1090 private final String[] mFeatures;
1091 private volatile Account[] mAccountsOfType = null;
1092 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1093 private volatile int mCurrentAccount = 0;
1094
1095 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
1096 String type, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -08001097 super(response, type, false /* expectActivityLaunch */,
1098 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001099 mFeatures = features;
1100 }
1101
1102 public void run() throws RemoteException {
1103 mAccountsOfType = getAccountsByType(mAccountType);
1104 // check whether each account matches the requested features
1105 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1106 mCurrentAccount = 0;
1107
1108 checkAccount();
1109 }
1110
1111 public void checkAccount() {
1112 if (mCurrentAccount >= mAccountsOfType.length) {
1113 sendResult();
1114 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001115 }
Fred Quintana33269202009-04-20 16:05:10 -07001116
Fred Quintana29e94b82010-03-10 12:11:51 -08001117 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1118 if (accountAuthenticator == null) {
1119 // It is possible that the authenticator has died, which is indicated by
1120 // mAuthenticator being set to null. If this happens then just abort.
1121 // There is no need to send back a result or error in this case since
1122 // that already happened when mAuthenticator was cleared.
1123 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1124 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1125 + " connected to the authenticator, " + toDebugString());
1126 }
1127 return;
1128 }
Fred Quintana33269202009-04-20 16:05:10 -07001129 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001130 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001131 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001132 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001133 }
1134 }
1135
1136 public void onResult(Bundle result) {
1137 mNumResults++;
1138 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001139 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001140 return;
1141 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001142 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001143 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1144 }
1145 mCurrentAccount++;
1146 checkAccount();
1147 }
1148
1149 public void sendResult() {
1150 IAccountManagerResponse response = getResponseAndClose();
1151 if (response != null) {
1152 try {
1153 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1154 for (int i = 0; i < accounts.length; i++) {
1155 accounts[i] = mAccountsWithFeatures.get(i);
1156 }
1157 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001158 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001159 response.onResult(result);
1160 } catch (RemoteException e) {
1161 // if the caller is dead then there is no one to care about remote exceptions
1162 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1163 Log.v(TAG, "failure while notifying response", e);
1164 }
1165 }
1166 }
1167 }
1168
1169
1170 protected String toDebugString(long now) {
1171 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1172 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1173 }
1174 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001175
1176 public Account[] getAccounts(String type) {
1177 checkReadAccountsPermission();
1178 long identityToken = clearCallingIdentity();
1179 try {
1180 return getAccountsByType(type);
1181 } finally {
1182 restoreCallingIdentity(identityToken);
1183 }
1184 }
1185
1186 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001187 String type, String[] features) {
Fred Quintana382601f2010-03-25 12:25:10 -07001188 if (response == null) throw new IllegalArgumentException("response is null");
1189 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001190 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001191 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -07001192 if (response != null) {
1193 try {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001194 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "type is null");
Fred Quintana33269202009-04-20 16:05:10 -07001195 } catch (RemoteException e) {
1196 // ignore this
1197 }
1198 }
1199 return;
1200 }
1201 long identityToken = clearCallingIdentity();
1202 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001203 if (features == null || features.length == 0) {
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001204 Account[] accounts = getAccountsByType(type);
1205 Bundle result = new Bundle();
1206 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1207 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001208 return;
1209 }
Fred Quintana33269202009-04-20 16:05:10 -07001210 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1211 } finally {
1212 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001213 }
1214 }
1215
Fred Quintana60307342009-03-24 22:48:12 -07001216 private long getAccountId(SQLiteDatabase db, Account account) {
1217 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001218 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001219 try {
1220 if (cursor.moveToNext()) {
1221 return cursor.getLong(0);
1222 }
1223 return -1;
1224 } finally {
1225 cursor.close();
1226 }
1227 }
1228
1229 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1230 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1231 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1232 new String[]{key}, null, null, null);
1233 try {
1234 if (cursor.moveToNext()) {
1235 return cursor.getLong(0);
1236 }
1237 return -1;
1238 } finally {
1239 cursor.close();
1240 }
1241 }
1242
Fred Quintanaa698f422009-04-08 19:14:54 -07001243 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001244 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001245 IAccountManagerResponse mResponse;
1246 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001247 final boolean mExpectActivityLaunch;
1248 final long mCreationTime;
1249
Fred Quintana33269202009-04-20 16:05:10 -07001250 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001251 private int mNumRequestContinued = 0;
1252 private int mNumErrors = 0;
1253
Fred Quintana60307342009-03-24 22:48:12 -07001254
1255 IAccountAuthenticator mAuthenticator = null;
1256
Fred Quintana8570f742010-02-18 10:32:54 -08001257 private final boolean mStripAuthTokenFromResult;
1258
Fred Quintanaa698f422009-04-08 19:14:54 -07001259 public Session(IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001260 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001261 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001262 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001263 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana8570f742010-02-18 10:32:54 -08001264 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001265 mResponse = response;
1266 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001267 mExpectActivityLaunch = expectActivityLaunch;
1268 mCreationTime = SystemClock.elapsedRealtime();
1269 synchronized (mSessions) {
1270 mSessions.put(toString(), this);
1271 }
1272 try {
1273 response.asBinder().linkToDeath(this, 0 /* flags */);
1274 } catch (RemoteException e) {
1275 mResponse = null;
1276 binderDied();
1277 }
Fred Quintana60307342009-03-24 22:48:12 -07001278 }
1279
Fred Quintanaa698f422009-04-08 19:14:54 -07001280 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001281 if (mResponse == null) {
1282 // this session has already been closed
1283 return null;
1284 }
Fred Quintana60307342009-03-24 22:48:12 -07001285 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001286 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001287 return response;
1288 }
1289
Fred Quintanaa698f422009-04-08 19:14:54 -07001290 private void close() {
1291 synchronized (mSessions) {
1292 if (mSessions.remove(toString()) == null) {
1293 // the session was already closed, so bail out now
1294 return;
1295 }
1296 }
1297 if (mResponse != null) {
1298 // stop listening for response deaths
1299 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1300
1301 // clear this so that we don't accidentally send any further results
1302 mResponse = null;
1303 }
1304 cancelTimeout();
1305 unbind();
1306 }
1307
1308 public void binderDied() {
1309 mResponse = null;
1310 close();
1311 }
1312
1313 protected String toDebugString() {
1314 return toDebugString(SystemClock.elapsedRealtime());
1315 }
1316
1317 protected String toDebugString(long now) {
1318 return "Session: expectLaunch " + mExpectActivityLaunch
1319 + ", connected " + (mAuthenticator != null)
1320 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1321 + "/" + mNumErrors + ")"
1322 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1323 }
1324
Fred Quintana60307342009-03-24 22:48:12 -07001325 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001326 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1327 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1328 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001329 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001330 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001331 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001332 }
1333 }
1334
1335 private void unbind() {
1336 if (mAuthenticator != null) {
1337 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001338 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001339 }
1340 }
1341
1342 public void scheduleTimeout() {
1343 mMessageHandler.sendMessageDelayed(
1344 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1345 }
1346
1347 public void cancelTimeout() {
1348 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1349 }
1350
Fred Quintanab839afc2009-10-14 15:57:28 -07001351 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001352 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001353 try {
1354 run();
1355 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001356 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001357 "remote exception");
1358 }
Fred Quintana60307342009-03-24 22:48:12 -07001359 }
1360
Fred Quintanab839afc2009-10-14 15:57:28 -07001361 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001362 mAuthenticator = null;
1363 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001364 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001365 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001366 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001367 }
1368 }
1369
Fred Quintanab839afc2009-10-14 15:57:28 -07001370 public abstract void run() throws RemoteException;
1371
Fred Quintana60307342009-03-24 22:48:12 -07001372 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001373 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001374 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001375 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001376 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001377 }
1378 }
1379
Fred Quintanaa698f422009-04-08 19:14:54 -07001380 public void onResult(Bundle result) {
1381 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001382 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1383 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1384 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001385 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1386 Account account = new Account(accountName, accountType);
1387 cancelNotification(getSigninRequiredNotificationId(account));
1388 }
Fred Quintana60307342009-03-24 22:48:12 -07001389 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001390 IAccountManagerResponse response;
1391 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001392 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001393 response = mResponse;
1394 } else {
1395 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001396 }
Fred Quintana60307342009-03-24 22:48:12 -07001397 if (response != null) {
1398 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001399 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001400 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001401 "null bundle returned");
1402 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001403 if (mStripAuthTokenFromResult) {
1404 result.remove(AccountManager.KEY_AUTHTOKEN);
1405 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001406 response.onResult(result);
1407 }
Fred Quintana60307342009-03-24 22:48:12 -07001408 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001409 // if the caller is dead then there is no one to care about remote exceptions
1410 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1411 Log.v(TAG, "failure while notifying response", e);
1412 }
Fred Quintana60307342009-03-24 22:48:12 -07001413 }
1414 }
1415 }
Fred Quintana60307342009-03-24 22:48:12 -07001416
Fred Quintanaa698f422009-04-08 19:14:54 -07001417 public void onRequestContinued() {
1418 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001419 }
1420
1421 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001422 mNumErrors++;
1423 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1424 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001425 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001426 IAccountManagerResponse response = getResponseAndClose();
1427 if (response != null) {
1428 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1429 Log.v(TAG, "Session.onError: responding");
1430 }
1431 try {
1432 response.onError(errorCode, errorMessage);
1433 } catch (RemoteException e) {
1434 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1435 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1436 }
1437 }
1438 } else {
1439 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1440 Log.v(TAG, "Session.onError: already closed");
1441 }
Fred Quintana60307342009-03-24 22:48:12 -07001442 }
1443 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001444
1445 /**
1446 * find the component name for the authenticator and initiate a bind
1447 * if no authenticator or the bind fails then return false, otherwise return true
1448 */
1449 private boolean bindToAuthenticator(String authenticatorType) {
1450 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1451 mAuthenticatorCache.getServiceInfo(
1452 AuthenticatorDescription.newKey(authenticatorType));
1453 if (authenticatorInfo == null) {
1454 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1455 Log.v(TAG, "there is no authenticator for " + authenticatorType
1456 + ", bailing out");
1457 }
1458 return false;
1459 }
1460
1461 Intent intent = new Intent();
1462 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1463 intent.setComponent(authenticatorInfo.componentName);
1464 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1465 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1466 }
1467 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1468 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1469 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1470 }
1471 return false;
1472 }
1473
1474
1475 return true;
1476 }
Fred Quintana60307342009-03-24 22:48:12 -07001477 }
1478
1479 private class MessageHandler extends Handler {
1480 MessageHandler(Looper looper) {
1481 super(looper);
1482 }
Costin Manolache3348f142009-09-29 18:58:36 -07001483
Fred Quintana60307342009-03-24 22:48:12 -07001484 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001485 switch (msg.what) {
1486 case MESSAGE_TIMED_OUT:
1487 Session session = (Session)msg.obj;
1488 session.onTimedOut();
1489 break;
1490
1491 default:
1492 throw new IllegalStateException("unhandled message: " + msg.what);
1493 }
1494 }
1495 }
1496
Oscar Montemayora8529f62009-11-18 10:14:20 -08001497 private static String getDatabaseName() {
1498 if(Environment.isEncryptedFilesystemEnabled()) {
1499 // Hard-coded path in case of encrypted file system
1500 return Environment.getSystemSecureDirectory().getPath() + File.separator + DATABASE_NAME;
1501 } else {
1502 // Regular path in case of non-encrypted file system
1503 return DATABASE_NAME;
1504 }
1505 }
1506
Fred Quintana60307342009-03-24 22:48:12 -07001507 private class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001508
Fred Quintana60307342009-03-24 22:48:12 -07001509 public DatabaseHelper(Context context) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001510 super(context, AccountManagerService.getDatabaseName(), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001511 }
1512
1513 @Override
1514 public void onCreate(SQLiteDatabase db) {
1515 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1516 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1517 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1518 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1519 + ACCOUNTS_PASSWORD + " TEXT, "
1520 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1521
1522 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1523 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1524 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1525 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1526 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1527 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1528
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001529 createGrantsTable(db);
1530
Fred Quintana60307342009-03-24 22:48:12 -07001531 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1532 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1533 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1534 + EXTRAS_KEY + " TEXT NOT NULL, "
1535 + EXTRAS_VALUE + " TEXT, "
1536 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1537
1538 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1539 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1540 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001541
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001542 createAccountsDeletionTrigger(db);
1543 }
1544
1545 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001546 db.execSQL(""
1547 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1548 + " BEGIN"
1549 + " DELETE FROM " + TABLE_AUTHTOKENS
1550 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1551 + " DELETE FROM " + TABLE_EXTRAS
1552 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001553 + " DELETE FROM " + TABLE_GRANTS
1554 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001555 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001556 }
1557
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001558 private void createGrantsTable(SQLiteDatabase db) {
1559 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1560 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1561 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1562 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1563 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1564 + "," + GRANTS_GRANTEE_UID + "))");
1565 }
1566
Fred Quintana60307342009-03-24 22:48:12 -07001567 @Override
1568 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001569 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001570
Fred Quintanaa698f422009-04-08 19:14:54 -07001571 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001572 // no longer need to do anything since the work is done
1573 // when upgrading from version 2
1574 oldVersion++;
1575 }
1576
1577 if (oldVersion == 2) {
1578 createGrantsTable(db);
1579 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1580 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001581 oldVersion++;
1582 }
Costin Manolache3348f142009-09-29 18:58:36 -07001583
1584 if (oldVersion == 3) {
1585 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1586 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1587 oldVersion++;
1588 }
Fred Quintana60307342009-03-24 22:48:12 -07001589 }
1590
1591 @Override
1592 public void onOpen(SQLiteDatabase db) {
1593 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1594 }
1595 }
1596
1597 private void setMetaValue(String key, String value) {
1598 ContentValues values = new ContentValues();
1599 values.put(META_KEY, key);
1600 values.put(META_VALUE, value);
1601 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1602 }
1603
1604 private String getMetaValue(String key) {
1605 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1606 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1607 try {
1608 if (c.moveToNext()) {
1609 return c.getString(0);
1610 }
1611 return null;
1612 } finally {
1613 c.close();
1614 }
1615 }
1616
1617 private class SimWatcher extends BroadcastReceiver {
1618 public SimWatcher(Context context) {
1619 // Re-scan the SIM card when the SIM state changes, and also if
1620 // the disk recovers from a full state (we may have failed to handle
1621 // things properly while the disk was full).
1622 final IntentFilter filter = new IntentFilter();
1623 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1624 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1625 context.registerReceiver(this, filter);
1626 }
Costin Manolache3348f142009-09-29 18:58:36 -07001627
Fred Quintana60307342009-03-24 22:48:12 -07001628 /**
1629 * Compare the IMSI to the one stored in the login service's
1630 * database. If they differ, erase all passwords and
1631 * authtokens (and store the new IMSI).
1632 */
1633 @Override
1634 public void onReceive(Context context, Intent intent) {
Doug Zongker885cfc232009-10-21 16:52:44 -07001635 // Check IMSI on every update; nothing happens if the IMSI
1636 // is missing or unchanged.
1637 TelephonyManager telephonyManager =
1638 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1639 if (telephonyManager == null) {
1640 Log.w(TAG, "failed to get TelephonyManager");
1641 return;
1642 }
1643 String imsi = telephonyManager.getSubscriberId();
1644
1645 // If the subscriber ID is an empty string, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001646 if (TextUtils.isEmpty(imsi)) return;
1647
Doug Zongker885cfc232009-10-21 16:52:44 -07001648 // If the current IMSI matches what's stored, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001649 String storedImsi = getMetaValue("imsi");
Fred Quintana60307342009-03-24 22:48:12 -07001650 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1651 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1652 }
Doug Zongker885cfc232009-10-21 16:52:44 -07001653 if (imsi.equals(storedImsi)) return;
1654
1655 // If a CDMA phone is unprovisioned, getSubscriberId()
1656 // will return a different value, but we *don't* erase the
1657 // passwords. We only erase them if it has a different
1658 // subscriber ID once it's provisioned.
1659 if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
1660 IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
1661 if (service == null) {
1662 Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
1663 return;
1664 }
1665 ITelephony telephony = ITelephony.Stub.asInterface(service);
1666 if (telephony == null) {
1667 Log.w(TAG, "failed to get ITelephony interface");
1668 return;
1669 }
1670 boolean needsProvisioning;
1671 try {
Wink Saville4d8ae852010-05-24 17:50:32 -07001672 needsProvisioning = telephony.needsOtaServiceProvisioning();
Doug Zongker885cfc232009-10-21 16:52:44 -07001673 } catch (RemoteException e) {
1674 Log.w(TAG, "exception while checking provisioning", e);
1675 // default to NOT wiping out the passwords
1676 needsProvisioning = true;
1677 }
1678 if (needsProvisioning) {
1679 // if the phone needs re-provisioning, don't do anything.
1680 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1681 Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
1682 storedImsi);
1683 }
1684 return;
1685 }
1686 }
Fred Quintana60307342009-03-24 22:48:12 -07001687
jsh5b462472009-09-01 16:13:55 -07001688 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001689 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1690 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001691 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1692 db.beginTransaction();
1693 try {
1694 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1695 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana60307342009-03-24 22:48:12 -07001696 db.setTransactionSuccessful();
1697 } finally {
1698 db.endTransaction();
1699 }
Fred Quintana743dfad2010-07-15 10:59:25 -07001700 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001701 }
1702 setMetaValue("imsi", imsi);
1703 }
1704 }
1705
1706 public IBinder onBind(Intent intent) {
1707 return asBinder();
1708 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001709
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001710 /**
1711 * Searches array of arguments for the specified string
1712 * @param args array of argument strings
1713 * @param value value to search for
1714 * @return true if the value is contained in the array
1715 */
1716 private static boolean scanArgs(String[] args, String value) {
1717 if (args != null) {
1718 for (String arg : args) {
1719 if (value.equals(arg)) {
1720 return true;
1721 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001722 }
1723 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001724 return false;
1725 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001726
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001727 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1728 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001729
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001730 if (isCheckinRequest) {
1731 // This is a checkin request. *Only* upload the account types and the count of each.
1732 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1733
1734 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1735 null, null, ACCOUNTS_TYPE, null, null);
1736 try {
1737 while (cursor.moveToNext()) {
1738 // print type,count
1739 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1740 }
1741 } finally {
1742 if (cursor != null) {
1743 cursor.close();
1744 }
1745 }
1746 } else {
Fred Quintanac2e46912010-03-15 16:10:44 -07001747 Account[] accounts = getAccountsByType(null /* type */);
Fred Quintana307da1a2010-01-21 14:24:20 -08001748 fout.println("Accounts: " + accounts.length);
1749 for (Account account : accounts) {
1750 fout.println(" " + account);
1751 }
1752
1753 fout.println();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001754 synchronized (mSessions) {
1755 final long now = SystemClock.elapsedRealtime();
Fred Quintana307da1a2010-01-21 14:24:20 -08001756 fout.println("Active Sessions: " + mSessions.size());
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001757 for (Session session : mSessions.values()) {
1758 fout.println(" " + session.toDebugString(now));
1759 }
1760 }
1761
1762 fout.println();
1763 mAuthenticatorCache.dump(fd, fout, args);
1764 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001765 }
1766
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001767 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001768 long identityToken = clearCallingIdentity();
1769 try {
1770 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1771 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1772 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001773
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001774 if (intent.getComponent() != null &&
1775 GrantCredentialsPermissionActivity.class.getName().equals(
1776 intent.getComponent().getClassName())) {
1777 createNoCredentialsPermissionNotification(account, intent);
1778 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001779 final Integer notificationId = getSigninRequiredNotificationId(account);
1780 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001781 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1782 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001783 final String notificationTitleFormat =
1784 mContext.getText(R.string.notification_title).toString();
1785 n.setLatestEventInfo(mContext,
1786 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001787 message, PendingIntent.getActivity(
1788 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1789 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001790 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001791 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001792 } finally {
1793 restoreCallingIdentity(identityToken);
1794 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001795 }
1796
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001797 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001798 long identityToken = clearCallingIdentity();
1799 try {
1800 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001801 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001802 } finally {
1803 restoreCallingIdentity(identityToken);
1804 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001805 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001806
Fred Quintanab38eb142010-02-24 13:40:54 -08001807 /** Succeeds if any of the specified permissions are granted. */
1808 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001809 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08001810
1811 for (String perm : permissions) {
1812 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
1813 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1814 Log.v(TAG, "caller uid " + uid + " has " + perm);
1815 }
1816 return;
1817 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001818 }
Fred Quintanab38eb142010-02-24 13:40:54 -08001819
1820 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
1821 Log.w(TAG, msg);
1822 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001823 }
1824
Fred Quintana7be59642009-08-24 18:29:25 -07001825 private boolean inSystemImage(int callerUid) {
1826 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1827 for (String name : packages) {
1828 try {
1829 PackageInfo packageInfo =
1830 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1831 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1832 return true;
1833 }
1834 } catch (PackageManager.NameNotFoundException e) {
1835 return false;
1836 }
1837 }
1838 return false;
1839 }
1840
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001841 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001842 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07001843 final boolean fromAuthenticator = account != null
1844 && hasAuthenticatorUid(account.type, callerUid);
1845 final boolean hasExplicitGrants = account != null
1846 && hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001847 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1848 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1849 + callerUid + ", account " + account
1850 + ": is authenticator? " + fromAuthenticator
1851 + ", has explicit permission? " + hasExplicitGrants);
1852 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001853 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001854 }
1855
Fred Quintana1a231912009-10-15 11:31:30 -07001856 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001857 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1858 mAuthenticatorCache.getAllServices()) {
1859 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001860 return (serviceInfo.uid == callingUid) ||
1861 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1862 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001863 }
1864 }
1865 return false;
1866 }
1867
1868 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1869 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1870 return true;
1871 }
1872 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1873 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001874 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001875 final boolean permissionGranted =
1876 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1877 if (!permissionGranted && isDebuggableMonkeyBuild) {
1878 // TODO: Skip this check when running automated tests. Replace this
1879 // with a more general solution.
Fred Quintana751fdc02010-02-09 14:13:18 -08001880 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001881 + authTokenType + " by uid " + Binder.getCallingUid()
1882 + " but ignoring since this is a monkey build");
1883 return true;
1884 }
1885 return permissionGranted;
1886 }
1887
1888 private void checkCallingUidAgainstAuthenticator(Account account) {
1889 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07001890 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001891 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1892 Log.w(TAG, msg);
1893 throw new SecurityException(msg);
1894 }
1895 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1896 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1897 }
1898 }
1899
1900 private void checkAuthenticateAccountsPermission(Account account) {
1901 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1902 checkCallingUidAgainstAuthenticator(account);
1903 }
1904
1905 private void checkReadAccountsPermission() {
1906 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1907 }
1908
1909 private void checkManageAccountsPermission() {
1910 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1911 }
1912
Fred Quintanab38eb142010-02-24 13:40:54 -08001913 private void checkManageAccountsOrUseCredentialsPermissions() {
1914 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
1915 Manifest.permission.USE_CREDENTIALS);
1916 }
1917
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001918 /**
1919 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1920 * <p>
1921 * Although this is public it can only be accessed via the AccountManagerService object
1922 * which is in the system. This means we don't need to protect it with permissions.
1923 * @hide
1924 */
1925 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07001926 if (account == null || authTokenType == null) {
1927 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07001928 return;
1929 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001930 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1931 db.beginTransaction();
1932 try {
1933 long accountId = getAccountId(db, account);
1934 if (accountId >= 0) {
1935 ContentValues values = new ContentValues();
1936 values.put(GRANTS_ACCOUNTS_ID, accountId);
1937 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1938 values.put(GRANTS_GRANTEE_UID, uid);
1939 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1940 db.setTransactionSuccessful();
1941 }
1942 } finally {
1943 db.endTransaction();
1944 }
1945 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1946 }
1947
1948 /**
1949 * Don't allow callers with the given uid permission to get credentials for
1950 * account/authTokenType.
1951 * <p>
1952 * Although this is public it can only be accessed via the AccountManagerService object
1953 * which is in the system. This means we don't need to protect it with permissions.
1954 * @hide
1955 */
1956 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07001957 if (account == null || authTokenType == null) {
1958 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07001959 return;
1960 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001961 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1962 db.beginTransaction();
1963 try {
1964 long accountId = getAccountId(db, account);
1965 if (accountId >= 0) {
1966 db.delete(TABLE_GRANTS,
1967 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1968 + GRANTS_GRANTEE_UID + "=?",
1969 new String[]{String.valueOf(accountId), authTokenType,
1970 String.valueOf(uid)});
1971 db.setTransactionSuccessful();
1972 }
1973 } finally {
1974 db.endTransaction();
1975 }
1976 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1977 }
Fred Quintana60307342009-03-24 22:48:12 -07001978}