blob: 770554eed67c0589f6549cda81085089aad4f106 [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 Quintanad4a1d2e2009-07-16 16:36:38 -0700285 checkAuthenticateAccountsPermission(account);
286
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700287 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700288 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700289 return readPasswordFromDatabase(account);
290 } finally {
291 restoreCallingIdentity(identityToken);
292 }
293 }
294
295 private String readPasswordFromDatabase(Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700296 if (account == null) {
297 return null;
298 }
299
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700300 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
301 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
302 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
303 new String[]{account.name, account.type}, null, null, null);
304 try {
305 if (cursor.moveToNext()) {
306 return cursor.getString(0);
307 }
308 return null;
309 } finally {
310 cursor.close();
311 }
312 }
313
314 public String getUserData(Account account, String key) {
315 checkAuthenticateAccountsPermission(account);
316 long identityToken = clearCallingIdentity();
317 try {
318 return readUserDataFromDatabase(account, key);
319 } finally {
320 restoreCallingIdentity(identityToken);
321 }
322 }
323
324 private String readUserDataFromDatabase(Account account, String key) {
Fred Quintana31957f12009-10-21 13:43:10 -0700325 if (account == null) {
326 return null;
327 }
328
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700329 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700330 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_VALUE},
331 EXTRAS_ACCOUNTS_ID
332 + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
333 + EXTRAS_KEY + "=?",
334 new String[]{account.name, account.type, key}, null, null, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700335 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700336 if (cursor.moveToNext()) {
337 return cursor.getString(0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700338 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700339 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700340 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700341 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700342 }
343 }
344
Fred Quintana97889762009-06-15 12:29:24 -0700345 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700346 long identityToken = clearCallingIdentity();
347 try {
Fred Quintana97889762009-06-15 12:29:24 -0700348 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
349 authenticatorCollection = mAuthenticatorCache.getAllServices();
350 AuthenticatorDescription[] types =
351 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700352 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700353 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700354 : authenticatorCollection) {
355 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700356 i++;
357 }
358 return types;
359 } finally {
360 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700361 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700362 }
363
Fred Quintanaa698f422009-04-08 19:14:54 -0700364 public Account[] getAccountsByType(String accountType) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700365 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700366
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700367 final String selection = accountType == null ? null : (ACCOUNTS_TYPE + "=?");
368 final String[] selectionArgs = accountType == null ? null : new String[]{accountType};
369 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_NAME_TYPE_PROJECTION,
370 selection, selectionArgs, null, null, null);
371 try {
372 int i = 0;
373 Account[] accounts = new Account[cursor.getCount()];
374 while (cursor.moveToNext()) {
375 accounts[i] = new Account(cursor.getString(1), cursor.getString(2));
376 i++;
Fred Quintana60307342009-03-24 22:48:12 -0700377 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700378 return accounts;
Fred Quintana60307342009-03-24 22:48:12 -0700379 } finally {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700380 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700381 }
382 }
383
Fred Quintanaa698f422009-04-08 19:14:54 -0700384 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700385 checkAuthenticateAccountsPermission(account);
386
Fred Quintana60307342009-03-24 22:48:12 -0700387 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700388 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700389 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700390 return insertAccountIntoDatabase(account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700391 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700392 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700393 }
394 }
395
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700396 private boolean insertAccountIntoDatabase(Account account, String password, Bundle extras) {
397 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
398 db.beginTransaction();
399 try {
Fred Quintana31957f12009-10-21 13:43:10 -0700400 if (account == null) {
401 return false;
402 }
Jim Miller50c05f32009-09-21 19:07:44 -0700403 boolean noBroadcast = false;
404 if (account.type.equals(GOOGLE_ACCOUNT_TYPE)) {
405 // Look for the 'nobroadcast' flag and remove it since we don't want it to persist
406 // in the db.
407 noBroadcast = extras.getBoolean(NO_BROADCAST_FLAG, false);
408 extras.remove(NO_BROADCAST_FLAG);
409 }
410
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700411 long numMatches = DatabaseUtils.longForQuery(db,
412 "select count(*) from " + TABLE_ACCOUNTS
413 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
414 new String[]{account.name, account.type});
415 if (numMatches > 0) {
416 return false;
417 }
418 ContentValues values = new ContentValues();
419 values.put(ACCOUNTS_NAME, account.name);
420 values.put(ACCOUNTS_TYPE, account.type);
421 values.put(ACCOUNTS_PASSWORD, password);
422 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
423 if (accountId < 0) {
424 return false;
425 }
426 if (extras != null) {
427 for (String key : extras.keySet()) {
428 final String value = extras.getString(key);
429 if (insertExtra(db, accountId, key, value) < 0) {
430 return false;
431 }
432 }
433 }
434 db.setTransactionSuccessful();
Jim Miller50c05f32009-09-21 19:07:44 -0700435 if (!noBroadcast) {
436 sendAccountsChangedBroadcast();
437 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700438 return true;
439 } finally {
440 db.endTransaction();
441 }
442 }
443
Fred Quintana60307342009-03-24 22:48:12 -0700444 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
445 ContentValues values = new ContentValues();
446 values.put(EXTRAS_KEY, key);
447 values.put(EXTRAS_ACCOUNTS_ID, accountId);
448 values.put(EXTRAS_VALUE, value);
449 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
450 }
451
Fred Quintana3084a6f2010-01-14 18:02:03 -0800452 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800453 Account account, String[] features) {
454 checkReadAccountsPermission();
455 long identityToken = clearCallingIdentity();
456 try {
457 new TestFeaturesSession(response, account, features).bind();
458 } finally {
459 restoreCallingIdentity(identityToken);
460 }
461 }
462
463 private class TestFeaturesSession extends Session {
464 private final String[] mFeatures;
465 private final Account mAccount;
466
467 public TestFeaturesSession(IAccountManagerResponse response,
468 Account account, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -0800469 super(response, account.type, false /* expectActivityLaunch */,
470 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800471 mFeatures = features;
472 mAccount = account;
473 }
474
475 public void run() throws RemoteException {
476 try {
477 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
478 } catch (RemoteException e) {
479 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
480 }
481 }
482
483 public void onResult(Bundle result) {
484 IAccountManagerResponse response = getResponseAndClose();
485 if (response != null) {
486 try {
487 if (result == null) {
488 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
489 return;
490 }
491 final Bundle newResult = new Bundle();
492 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
493 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
494 response.onResult(newResult);
495 } catch (RemoteException e) {
496 // if the caller is dead then there is no one to care about remote exceptions
497 if (Log.isLoggable(TAG, Log.VERBOSE)) {
498 Log.v(TAG, "failure while notifying response", e);
499 }
500 }
501 }
502 }
503
504 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800505 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800506 + ", " + mAccount
507 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
508 }
509 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800510
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700511 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700512 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700513 long identityToken = clearCallingIdentity();
514 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700516 } finally {
517 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700518 }
Fred Quintana60307342009-03-24 22:48:12 -0700519 }
520
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700521 private class RemoveAccountSession extends Session {
522 final Account mAccount;
523 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
Fred Quintana8570f742010-02-18 10:32:54 -0800524 super(response, account.type, false /* expectActivityLaunch */,
525 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700526 mAccount = account;
527 }
528
529 protected String toDebugString(long now) {
530 return super.toDebugString(now) + ", removeAccount"
531 + ", account " + mAccount;
532 }
533
534 public void run() throws RemoteException {
535 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
536 }
537
538 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700539 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
540 && !result.containsKey(AccountManager.KEY_INTENT)) {
541 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700542 if (removalAllowed) {
543 removeAccount(mAccount);
544 }
545 IAccountManagerResponse response = getResponseAndClose();
546 if (response != null) {
547 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700548 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700549 try {
550 response.onResult(result2);
551 } catch (RemoteException e) {
552 // ignore
553 }
554 }
555 }
556 super.onResult(result);
557 }
558 }
559
560 private void removeAccount(Account account) {
561 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
562 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
563 new String[]{account.name, account.type});
564 sendAccountsChangedBroadcast();
565 }
566
Fred Quintanaa698f422009-04-08 19:14:54 -0700567 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700568 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700569 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700570 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700571 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
572 db.beginTransaction();
573 try {
574 invalidateAuthToken(db, accountType, authToken);
575 db.setTransactionSuccessful();
576 } finally {
577 db.endTransaction();
578 }
Fred Quintana60307342009-03-24 22:48:12 -0700579 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700580 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700581 }
582 }
583
584 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700585 if (authToken == null || accountType == null) {
586 return;
587 }
Fred Quintana33269202009-04-20 16:05:10 -0700588 Cursor cursor = db.rawQuery(
589 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
590 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
591 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
592 + " FROM " + TABLE_ACCOUNTS
593 + " JOIN " + TABLE_AUTHTOKENS
594 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
595 + " = " + AUTHTOKENS_ACCOUNTS_ID
596 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
597 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
598 new String[]{authToken, accountType});
599 try {
600 while (cursor.moveToNext()) {
601 long authTokenId = cursor.getLong(0);
602 String accountName = cursor.getString(1);
603 String authTokenType = cursor.getString(2);
604 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700605 }
Fred Quintana33269202009-04-20 16:05:10 -0700606 } finally {
607 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700608 }
609 }
610
611 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700612 if (account == null || type == null) {
613 return false;
614 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700615 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700616 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
617 db.beginTransaction();
618 try {
Fred Quintana33269202009-04-20 16:05:10 -0700619 long accountId = getAccountId(db, account);
620 if (accountId < 0) {
621 return false;
622 }
623 db.delete(TABLE_AUTHTOKENS,
624 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
625 new String[]{type});
626 ContentValues values = new ContentValues();
627 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
628 values.put(AUTHTOKENS_TYPE, type);
629 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
630 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700631 db.setTransactionSuccessful();
632 return true;
633 }
634 return false;
635 } finally {
636 db.endTransaction();
637 }
638 }
639
Fred Quintana60307342009-03-24 22:48:12 -0700640 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
Fred Quintana31957f12009-10-21 13:43:10 -0700641 if (account == null || authTokenType == null) {
642 return null;
643 }
Fred Quintana60307342009-03-24 22:48:12 -0700644 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700645 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
646 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
647 + AUTHTOKENS_TYPE + "=?",
648 new String[]{account.name, account.type, authTokenType},
649 null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700650 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700651 if (cursor.moveToNext()) {
652 return cursor.getString(0);
Fred Quintana60307342009-03-24 22:48:12 -0700653 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700654 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700655 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700656 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700657 }
658 }
659
Fred Quintanaa698f422009-04-08 19:14:54 -0700660 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700661 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700662 long identityToken = clearCallingIdentity();
663 try {
Fred Quintana33269202009-04-20 16:05:10 -0700664 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700665 } finally {
666 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700667 }
Fred Quintana60307342009-03-24 22:48:12 -0700668 }
669
Fred Quintanaa698f422009-04-08 19:14:54 -0700670 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700671 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700672 long identityToken = clearCallingIdentity();
673 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700674 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700675 } finally {
676 restoreCallingIdentity(identityToken);
677 }
Fred Quintana60307342009-03-24 22:48:12 -0700678 }
679
Fred Quintanaa698f422009-04-08 19:14:54 -0700680 public void setPassword(Account account, String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700681 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700682 long identityToken = clearCallingIdentity();
683 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700684 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700685 } finally {
686 restoreCallingIdentity(identityToken);
687 }
Fred Quintana60307342009-03-24 22:48:12 -0700688 }
689
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700690 private void setPasswordInDB(Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700691 if (account == null) {
692 return;
693 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700694 ContentValues values = new ContentValues();
695 values.put(ACCOUNTS_PASSWORD, password);
696 mOpenHelper.getWritableDatabase().update(TABLE_ACCOUNTS, values,
697 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
698 new String[]{account.name, account.type});
699 sendAccountsChangedBroadcast();
700 }
701
Fred Quintana33269202009-04-20 16:05:10 -0700702 private void sendAccountsChangedBroadcast() {
703 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
704 }
705
Fred Quintanaa698f422009-04-08 19:14:54 -0700706 public void clearPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700707 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700708 long identityToken = clearCallingIdentity();
709 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700710 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700711 } finally {
712 restoreCallingIdentity(identityToken);
713 }
Fred Quintana60307342009-03-24 22:48:12 -0700714 }
715
Fred Quintanaa698f422009-04-08 19:14:54 -0700716 public void setUserData(Account account, String key, String value) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700717 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700718 long identityToken = clearCallingIdentity();
Fred Quintana31957f12009-10-21 13:43:10 -0700719 if (account == null) {
720 return;
721 }
Jim Miller50c05f32009-09-21 19:07:44 -0700722 if (account.type.equals(GOOGLE_ACCOUNT_TYPE) && key.equals("broadcast")) {
723 sendAccountsChangedBroadcast();
724 return;
725 }
Fred Quintana60307342009-03-24 22:48:12 -0700726 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700727 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700728 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700729 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700730 }
731 }
732
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700733 private void writeUserdataIntoDatabase(Account account, String key, String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700734 if (account == null || key == null) {
735 return;
736 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700737 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
738 db.beginTransaction();
739 try {
740 long accountId = getAccountId(db, account);
741 if (accountId < 0) {
742 return;
743 }
744 long extrasId = getExtrasId(db, accountId, key);
745 if (extrasId < 0 ) {
746 extrasId = insertExtra(db, accountId, key, value);
747 if (extrasId < 0) {
748 return;
749 }
750 } else {
751 ContentValues values = new ContentValues();
752 values.put(EXTRAS_VALUE, value);
753 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
754 return;
755 }
756
757 }
758 db.setTransactionSuccessful();
759 } finally {
760 db.endTransaction();
761 }
762 }
763
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700764 private void onResult(IAccountManagerResponse response, Bundle result) {
765 try {
766 response.onResult(result);
767 } catch (RemoteException e) {
768 // if the caller is dead then there is no one to care about remote
769 // exceptions
770 if (Log.isLoggable(TAG, Log.VERBOSE)) {
771 Log.v(TAG, "failure while notifying response", e);
772 }
773 }
774 }
775
Fred Quintanaa698f422009-04-08 19:14:54 -0700776 public void getAuthToken(IAccountManagerResponse response, final Account account,
777 final String authTokenType, final boolean notifyOnAuthFailure,
778 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700779 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
780 final int callerUid = Binder.getCallingUid();
781 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
782
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700783 long identityToken = clearCallingIdentity();
784 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700785 // if the caller has permission, do the peek. otherwise go the more expensive
786 // route of starting a Session
787 if (permissionGranted) {
788 String authToken = readAuthTokenFromDatabase(account, authTokenType);
789 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700790 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700791 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
792 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
793 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700794 onResult(response, result);
795 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700796 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700797 }
798
Fred Quintana8570f742010-02-18 10:32:54 -0800799 new Session(response, account.type, expectActivityLaunch,
800 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700801 protected String toDebugString(long now) {
802 if (loginOptions != null) loginOptions.keySet();
803 return super.toDebugString(now) + ", getAuthToken"
804 + ", " + account
805 + ", authTokenType " + authTokenType
806 + ", loginOptions " + loginOptions
807 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
808 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700809
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700810 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700811 // If the caller doesn't have permission then create and return the
812 // "grant permission" intent instead of the "getAuthToken" intent.
813 if (!permissionGranted) {
814 mAuthenticator.getAuthTokenLabel(this, authTokenType);
815 } else {
816 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
817 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700818 }
819
820 public void onResult(Bundle result) {
821 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700822 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700823 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
824 new AccountAuthenticatorResponse(this),
825 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700826 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700827 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700828 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700829 onResult(bundle);
830 return;
831 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700832 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700833 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700834 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
835 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700836 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700837 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700838 "the type and name should not be empty");
839 return;
840 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700841 saveAuthTokenToDatabase(new Account(name, type),
842 authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700843 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700844
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700845 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700846 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700847 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700848 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700849 intent);
850 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700851 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700852 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700853 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700854 }.bind();
855 } finally {
856 restoreCallingIdentity(identityToken);
857 }
Fred Quintana60307342009-03-24 22:48:12 -0700858 }
859
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700860 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
861 int uid = intent.getIntExtra(
862 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
863 String authTokenType = intent.getStringExtra(
864 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
865 String authTokenLabel = intent.getStringExtra(
866 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
867
868 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
869 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700870 final String titleAndSubtitle =
871 mContext.getString(R.string.permission_request_notification_with_subtitle,
872 account.name);
873 final int index = titleAndSubtitle.indexOf('\n');
874 final String title = titleAndSubtitle.substring(0, index);
875 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700876 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700877 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700878 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
879 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
880 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
881 }
882
883 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
884 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
885 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
886 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700887 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700888 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700889 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700890 }
891
892 final Context authContext;
893 try {
894 authContext = mContext.createPackageContext(
895 serviceInfo.type.packageName, 0);
896 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700897 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700898 }
899
900 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
901 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
902 intent.addCategory(
903 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
904 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
905 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
906 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
907 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
908 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
909 authContext.getString(serviceInfo.type.labelId));
910 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
911 mContext.getPackageManager().getPackagesForUid(uid));
912 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
913 return intent;
914 }
915
916 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
917 int uid) {
918 Integer id;
919 synchronized(mCredentialsPermissionNotificationIds) {
920 final Pair<Pair<Account, String>, Integer> key =
921 new Pair<Pair<Account, String>, Integer>(
922 new Pair<Account, String>(account, authTokenType), uid);
923 id = mCredentialsPermissionNotificationIds.get(key);
924 if (id == null) {
925 id = mNotificationIds.incrementAndGet();
926 mCredentialsPermissionNotificationIds.put(key, id);
927 }
928 }
929 return id;
930 }
931
932 private Integer getSigninRequiredNotificationId(Account account) {
933 Integer id;
934 synchronized(mSigninRequiredNotificationIds) {
935 id = mSigninRequiredNotificationIds.get(account);
936 if (id == null) {
937 id = mNotificationIds.incrementAndGet();
938 mSigninRequiredNotificationIds.put(account, id);
939 }
940 }
941 return id;
942 }
943
Fred Quintanaa698f422009-04-08 19:14:54 -0700944
Fred Quintana33269202009-04-20 16:05:10 -0700945 public void addAcount(final IAccountManagerResponse response, final String accountType,
946 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700947 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700948 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700949 long identityToken = clearCallingIdentity();
950 try {
Fred Quintana8570f742010-02-18 10:32:54 -0800951 new Session(response, accountType, expectActivityLaunch,
952 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700953 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -0700954 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -0700955 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700956 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700957
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700958 protected String toDebugString(long now) {
959 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -0700960 + ", accountType " + accountType
961 + ", requiredFeatures "
962 + (requiredFeatures != null
963 ? TextUtils.join(",", requiredFeatures)
964 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700965 }
966 }.bind();
967 } finally {
968 restoreCallingIdentity(identityToken);
969 }
Fred Quintana60307342009-03-24 22:48:12 -0700970 }
971
Fred Quintanaa698f422009-04-08 19:14:54 -0700972 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700973 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700974 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700975 long identityToken = clearCallingIdentity();
976 try {
Fred Quintana8570f742010-02-18 10:32:54 -0800977 new Session(response, account.type, expectActivityLaunch,
978 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700979 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700980 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700981 }
982 protected String toDebugString(long now) {
983 return super.toDebugString(now) + ", confirmCredentials"
984 + ", " + account;
985 }
986 }.bind();
987 } finally {
988 restoreCallingIdentity(identityToken);
989 }
Fred Quintana60307342009-03-24 22:48:12 -0700990 }
991
Fred Quintanaa698f422009-04-08 19:14:54 -0700992 public void updateCredentials(IAccountManagerResponse response, final Account account,
993 final String authTokenType, final boolean expectActivityLaunch,
994 final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700995 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700996 long identityToken = clearCallingIdentity();
997 try {
Fred Quintana8570f742010-02-18 10:32:54 -0800998 new Session(response, account.type, expectActivityLaunch,
999 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001000 public void run() throws RemoteException {
1001 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1002 }
1003 protected String toDebugString(long now) {
1004 if (loginOptions != null) loginOptions.keySet();
1005 return super.toDebugString(now) + ", updateCredentials"
1006 + ", " + account
1007 + ", authTokenType " + authTokenType
1008 + ", loginOptions " + loginOptions;
1009 }
1010 }.bind();
1011 } finally {
1012 restoreCallingIdentity(identityToken);
1013 }
Fred Quintana60307342009-03-24 22:48:12 -07001014 }
1015
Fred Quintanaa698f422009-04-08 19:14:54 -07001016 public void editProperties(IAccountManagerResponse response, final String accountType,
1017 final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001018 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001019 long identityToken = clearCallingIdentity();
1020 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001021 new Session(response, accountType, expectActivityLaunch,
1022 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001023 public void run() throws RemoteException {
1024 mAuthenticator.editProperties(this, mAccountType);
1025 }
1026 protected String toDebugString(long now) {
1027 return super.toDebugString(now) + ", editProperties"
1028 + ", accountType " + accountType;
1029 }
1030 }.bind();
1031 } finally {
1032 restoreCallingIdentity(identityToken);
1033 }
Fred Quintana60307342009-03-24 22:48:12 -07001034 }
1035
Fred Quintana33269202009-04-20 16:05:10 -07001036 private class GetAccountsByTypeAndFeatureSession extends Session {
1037 private final String[] mFeatures;
1038 private volatile Account[] mAccountsOfType = null;
1039 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1040 private volatile int mCurrentAccount = 0;
1041
1042 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
1043 String type, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -08001044 super(response, type, false /* expectActivityLaunch */,
1045 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001046 mFeatures = features;
1047 }
1048
1049 public void run() throws RemoteException {
1050 mAccountsOfType = getAccountsByType(mAccountType);
1051 // check whether each account matches the requested features
1052 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1053 mCurrentAccount = 0;
1054
1055 checkAccount();
1056 }
1057
1058 public void checkAccount() {
1059 if (mCurrentAccount >= mAccountsOfType.length) {
1060 sendResult();
1061 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001062 }
Fred Quintana33269202009-04-20 16:05:10 -07001063
1064 try {
1065 mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
1066 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001067 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001068 }
1069 }
1070
1071 public void onResult(Bundle result) {
1072 mNumResults++;
1073 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001074 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001075 return;
1076 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001077 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001078 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1079 }
1080 mCurrentAccount++;
1081 checkAccount();
1082 }
1083
1084 public void sendResult() {
1085 IAccountManagerResponse response = getResponseAndClose();
1086 if (response != null) {
1087 try {
1088 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1089 for (int i = 0; i < accounts.length; i++) {
1090 accounts[i] = mAccountsWithFeatures.get(i);
1091 }
1092 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001093 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001094 response.onResult(result);
1095 } catch (RemoteException e) {
1096 // if the caller is dead then there is no one to care about remote exceptions
1097 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1098 Log.v(TAG, "failure while notifying response", e);
1099 }
1100 }
1101 }
1102 }
1103
1104
1105 protected String toDebugString(long now) {
1106 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1107 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1108 }
1109 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001110
1111 public Account[] getAccounts(String type) {
1112 checkReadAccountsPermission();
1113 long identityToken = clearCallingIdentity();
1114 try {
1115 return getAccountsByType(type);
1116 } finally {
1117 restoreCallingIdentity(identityToken);
1118 }
1119 }
1120
1121 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001122 String type, String[] features) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001123 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001124 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -07001125 if (response != null) {
1126 try {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001127 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "type is null");
Fred Quintana33269202009-04-20 16:05:10 -07001128 } catch (RemoteException e) {
1129 // ignore this
1130 }
1131 }
1132 return;
1133 }
1134 long identityToken = clearCallingIdentity();
1135 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001136 if (features == null || features.length == 0) {
1137 getAccountsByType(type);
1138 return;
1139 }
Fred Quintana33269202009-04-20 16:05:10 -07001140 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1141 } finally {
1142 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001143 }
1144 }
1145
Fred Quintana60307342009-03-24 22:48:12 -07001146 private long getAccountId(SQLiteDatabase db, Account account) {
1147 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001148 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001149 try {
1150 if (cursor.moveToNext()) {
1151 return cursor.getLong(0);
1152 }
1153 return -1;
1154 } finally {
1155 cursor.close();
1156 }
1157 }
1158
1159 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1160 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1161 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1162 new String[]{key}, null, null, null);
1163 try {
1164 if (cursor.moveToNext()) {
1165 return cursor.getLong(0);
1166 }
1167 return -1;
1168 } finally {
1169 cursor.close();
1170 }
1171 }
1172
Fred Quintanaa698f422009-04-08 19:14:54 -07001173 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001174 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001175 IAccountManagerResponse mResponse;
1176 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001177 final boolean mExpectActivityLaunch;
1178 final long mCreationTime;
1179
Fred Quintana33269202009-04-20 16:05:10 -07001180 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001181 private int mNumRequestContinued = 0;
1182 private int mNumErrors = 0;
1183
Fred Quintana60307342009-03-24 22:48:12 -07001184
1185 IAccountAuthenticator mAuthenticator = null;
1186
Fred Quintana8570f742010-02-18 10:32:54 -08001187 private final boolean mStripAuthTokenFromResult;
1188
Fred Quintanaa698f422009-04-08 19:14:54 -07001189 public Session(IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001190 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001191 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001192 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001193 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana8570f742010-02-18 10:32:54 -08001194 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001195 mResponse = response;
1196 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001197 mExpectActivityLaunch = expectActivityLaunch;
1198 mCreationTime = SystemClock.elapsedRealtime();
1199 synchronized (mSessions) {
1200 mSessions.put(toString(), this);
1201 }
1202 try {
1203 response.asBinder().linkToDeath(this, 0 /* flags */);
1204 } catch (RemoteException e) {
1205 mResponse = null;
1206 binderDied();
1207 }
Fred Quintana60307342009-03-24 22:48:12 -07001208 }
1209
Fred Quintanaa698f422009-04-08 19:14:54 -07001210 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001211 if (mResponse == null) {
1212 // this session has already been closed
1213 return null;
1214 }
Fred Quintana60307342009-03-24 22:48:12 -07001215 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001216 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001217 return response;
1218 }
1219
Fred Quintanaa698f422009-04-08 19:14:54 -07001220 private void close() {
1221 synchronized (mSessions) {
1222 if (mSessions.remove(toString()) == null) {
1223 // the session was already closed, so bail out now
1224 return;
1225 }
1226 }
1227 if (mResponse != null) {
1228 // stop listening for response deaths
1229 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1230
1231 // clear this so that we don't accidentally send any further results
1232 mResponse = null;
1233 }
1234 cancelTimeout();
1235 unbind();
1236 }
1237
1238 public void binderDied() {
1239 mResponse = null;
1240 close();
1241 }
1242
1243 protected String toDebugString() {
1244 return toDebugString(SystemClock.elapsedRealtime());
1245 }
1246
1247 protected String toDebugString(long now) {
1248 return "Session: expectLaunch " + mExpectActivityLaunch
1249 + ", connected " + (mAuthenticator != null)
1250 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1251 + "/" + mNumErrors + ")"
1252 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1253 }
1254
Fred Quintana60307342009-03-24 22:48:12 -07001255 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001256 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1257 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1258 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001259 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001260 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001261 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001262 }
1263 }
1264
1265 private void unbind() {
1266 if (mAuthenticator != null) {
1267 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001268 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001269 }
1270 }
1271
1272 public void scheduleTimeout() {
1273 mMessageHandler.sendMessageDelayed(
1274 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1275 }
1276
1277 public void cancelTimeout() {
1278 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1279 }
1280
Fred Quintanab839afc2009-10-14 15:57:28 -07001281 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001282 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001283 try {
1284 run();
1285 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001286 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001287 "remote exception");
1288 }
Fred Quintana60307342009-03-24 22:48:12 -07001289 }
1290
Fred Quintanab839afc2009-10-14 15:57:28 -07001291 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001292 mAuthenticator = null;
1293 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001294 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001295 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001296 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001297 }
1298 }
1299
Fred Quintanab839afc2009-10-14 15:57:28 -07001300 public abstract void run() throws RemoteException;
1301
Fred Quintana60307342009-03-24 22:48:12 -07001302 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001303 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001304 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001305 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001306 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001307 }
1308 }
1309
Fred Quintanaa698f422009-04-08 19:14:54 -07001310 public void onResult(Bundle result) {
1311 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001312 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1313 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1314 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001315 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1316 Account account = new Account(accountName, accountType);
1317 cancelNotification(getSigninRequiredNotificationId(account));
1318 }
Fred Quintana60307342009-03-24 22:48:12 -07001319 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001320 IAccountManagerResponse response;
1321 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001322 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001323 response = mResponse;
1324 } else {
1325 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001326 }
Fred Quintana60307342009-03-24 22:48:12 -07001327 if (response != null) {
1328 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001329 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001330 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001331 "null bundle returned");
1332 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001333 if (mStripAuthTokenFromResult) {
1334 result.remove(AccountManager.KEY_AUTHTOKEN);
1335 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001336 response.onResult(result);
1337 }
Fred Quintana60307342009-03-24 22:48:12 -07001338 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001339 // if the caller is dead then there is no one to care about remote exceptions
1340 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1341 Log.v(TAG, "failure while notifying response", e);
1342 }
Fred Quintana60307342009-03-24 22:48:12 -07001343 }
1344 }
1345 }
Fred Quintana60307342009-03-24 22:48:12 -07001346
Fred Quintanaa698f422009-04-08 19:14:54 -07001347 public void onRequestContinued() {
1348 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001349 }
1350
1351 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001352 mNumErrors++;
1353 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1354 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001355 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001356 IAccountManagerResponse response = getResponseAndClose();
1357 if (response != null) {
1358 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1359 Log.v(TAG, "Session.onError: responding");
1360 }
1361 try {
1362 response.onError(errorCode, errorMessage);
1363 } catch (RemoteException e) {
1364 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1365 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1366 }
1367 }
1368 } else {
1369 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1370 Log.v(TAG, "Session.onError: already closed");
1371 }
Fred Quintana60307342009-03-24 22:48:12 -07001372 }
1373 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001374
1375 /**
1376 * find the component name for the authenticator and initiate a bind
1377 * if no authenticator or the bind fails then return false, otherwise return true
1378 */
1379 private boolean bindToAuthenticator(String authenticatorType) {
1380 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1381 mAuthenticatorCache.getServiceInfo(
1382 AuthenticatorDescription.newKey(authenticatorType));
1383 if (authenticatorInfo == null) {
1384 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1385 Log.v(TAG, "there is no authenticator for " + authenticatorType
1386 + ", bailing out");
1387 }
1388 return false;
1389 }
1390
1391 Intent intent = new Intent();
1392 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1393 intent.setComponent(authenticatorInfo.componentName);
1394 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1395 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1396 }
1397 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1398 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1399 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1400 }
1401 return false;
1402 }
1403
1404
1405 return true;
1406 }
Fred Quintana60307342009-03-24 22:48:12 -07001407 }
1408
1409 private class MessageHandler extends Handler {
1410 MessageHandler(Looper looper) {
1411 super(looper);
1412 }
Costin Manolache3348f142009-09-29 18:58:36 -07001413
Fred Quintana60307342009-03-24 22:48:12 -07001414 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001415 switch (msg.what) {
1416 case MESSAGE_TIMED_OUT:
1417 Session session = (Session)msg.obj;
1418 session.onTimedOut();
1419 break;
1420
1421 default:
1422 throw new IllegalStateException("unhandled message: " + msg.what);
1423 }
1424 }
1425 }
1426
Oscar Montemayora8529f62009-11-18 10:14:20 -08001427 private static String getDatabaseName() {
1428 if(Environment.isEncryptedFilesystemEnabled()) {
1429 // Hard-coded path in case of encrypted file system
1430 return Environment.getSystemSecureDirectory().getPath() + File.separator + DATABASE_NAME;
1431 } else {
1432 // Regular path in case of non-encrypted file system
1433 return DATABASE_NAME;
1434 }
1435 }
1436
Fred Quintana60307342009-03-24 22:48:12 -07001437 private class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001438
Fred Quintana60307342009-03-24 22:48:12 -07001439 public DatabaseHelper(Context context) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001440 super(context, AccountManagerService.getDatabaseName(), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001441 }
1442
1443 @Override
1444 public void onCreate(SQLiteDatabase db) {
1445 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1446 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1447 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1448 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1449 + ACCOUNTS_PASSWORD + " TEXT, "
1450 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1451
1452 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1453 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1454 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1455 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1456 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1457 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1458
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001459 createGrantsTable(db);
1460
Fred Quintana60307342009-03-24 22:48:12 -07001461 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1462 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1463 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1464 + EXTRAS_KEY + " TEXT NOT NULL, "
1465 + EXTRAS_VALUE + " TEXT, "
1466 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1467
1468 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1469 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1470 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001471
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001472 createAccountsDeletionTrigger(db);
1473 }
1474
1475 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001476 db.execSQL(""
1477 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1478 + " BEGIN"
1479 + " DELETE FROM " + TABLE_AUTHTOKENS
1480 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1481 + " DELETE FROM " + TABLE_EXTRAS
1482 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001483 + " DELETE FROM " + TABLE_GRANTS
1484 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001485 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001486 }
1487
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001488 private void createGrantsTable(SQLiteDatabase db) {
1489 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1490 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1491 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1492 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1493 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1494 + "," + GRANTS_GRANTEE_UID + "))");
1495 }
1496
Fred Quintana60307342009-03-24 22:48:12 -07001497 @Override
1498 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001499 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001500
Fred Quintanaa698f422009-04-08 19:14:54 -07001501 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001502 // no longer need to do anything since the work is done
1503 // when upgrading from version 2
1504 oldVersion++;
1505 }
1506
1507 if (oldVersion == 2) {
1508 createGrantsTable(db);
1509 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1510 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001511 oldVersion++;
1512 }
Costin Manolache3348f142009-09-29 18:58:36 -07001513
1514 if (oldVersion == 3) {
1515 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1516 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1517 oldVersion++;
1518 }
Fred Quintana60307342009-03-24 22:48:12 -07001519 }
1520
1521 @Override
1522 public void onOpen(SQLiteDatabase db) {
1523 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1524 }
1525 }
1526
1527 private void setMetaValue(String key, String value) {
1528 ContentValues values = new ContentValues();
1529 values.put(META_KEY, key);
1530 values.put(META_VALUE, value);
1531 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1532 }
1533
1534 private String getMetaValue(String key) {
1535 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1536 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1537 try {
1538 if (c.moveToNext()) {
1539 return c.getString(0);
1540 }
1541 return null;
1542 } finally {
1543 c.close();
1544 }
1545 }
1546
1547 private class SimWatcher extends BroadcastReceiver {
1548 public SimWatcher(Context context) {
1549 // Re-scan the SIM card when the SIM state changes, and also if
1550 // the disk recovers from a full state (we may have failed to handle
1551 // things properly while the disk was full).
1552 final IntentFilter filter = new IntentFilter();
1553 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1554 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1555 context.registerReceiver(this, filter);
1556 }
Costin Manolache3348f142009-09-29 18:58:36 -07001557
Fred Quintana60307342009-03-24 22:48:12 -07001558 /**
1559 * Compare the IMSI to the one stored in the login service's
1560 * database. If they differ, erase all passwords and
1561 * authtokens (and store the new IMSI).
1562 */
1563 @Override
1564 public void onReceive(Context context, Intent intent) {
Doug Zongker885cfc232009-10-21 16:52:44 -07001565 // Check IMSI on every update; nothing happens if the IMSI
1566 // is missing or unchanged.
1567 TelephonyManager telephonyManager =
1568 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1569 if (telephonyManager == null) {
1570 Log.w(TAG, "failed to get TelephonyManager");
1571 return;
1572 }
1573 String imsi = telephonyManager.getSubscriberId();
1574
1575 // If the subscriber ID is an empty string, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001576 if (TextUtils.isEmpty(imsi)) return;
1577
Doug Zongker885cfc232009-10-21 16:52:44 -07001578 // If the current IMSI matches what's stored, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001579 String storedImsi = getMetaValue("imsi");
Fred Quintana60307342009-03-24 22:48:12 -07001580 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1581 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1582 }
Doug Zongker885cfc232009-10-21 16:52:44 -07001583 if (imsi.equals(storedImsi)) return;
1584
1585 // If a CDMA phone is unprovisioned, getSubscriberId()
1586 // will return a different value, but we *don't* erase the
1587 // passwords. We only erase them if it has a different
1588 // subscriber ID once it's provisioned.
1589 if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
1590 IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
1591 if (service == null) {
1592 Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
1593 return;
1594 }
1595 ITelephony telephony = ITelephony.Stub.asInterface(service);
1596 if (telephony == null) {
1597 Log.w(TAG, "failed to get ITelephony interface");
1598 return;
1599 }
1600 boolean needsProvisioning;
1601 try {
1602 needsProvisioning = telephony.getCdmaNeedsProvisioning();
1603 } catch (RemoteException e) {
1604 Log.w(TAG, "exception while checking provisioning", e);
1605 // default to NOT wiping out the passwords
1606 needsProvisioning = true;
1607 }
1608 if (needsProvisioning) {
1609 // if the phone needs re-provisioning, don't do anything.
1610 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1611 Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
1612 storedImsi);
1613 }
1614 return;
1615 }
1616 }
Fred Quintana60307342009-03-24 22:48:12 -07001617
jsh5b462472009-09-01 16:13:55 -07001618 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001619 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1620 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001621 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1622 db.beginTransaction();
1623 try {
1624 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1625 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001626 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001627 db.setTransactionSuccessful();
1628 } finally {
1629 db.endTransaction();
1630 }
1631 }
1632 setMetaValue("imsi", imsi);
1633 }
1634 }
1635
1636 public IBinder onBind(Intent intent) {
1637 return asBinder();
1638 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001639
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001640 /**
1641 * Searches array of arguments for the specified string
1642 * @param args array of argument strings
1643 * @param value value to search for
1644 * @return true if the value is contained in the array
1645 */
1646 private static boolean scanArgs(String[] args, String value) {
1647 if (args != null) {
1648 for (String arg : args) {
1649 if (value.equals(arg)) {
1650 return true;
1651 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001652 }
1653 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001654 return false;
1655 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001656
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001657 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1658 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001659
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001660 if (isCheckinRequest) {
1661 // This is a checkin request. *Only* upload the account types and the count of each.
1662 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1663
1664 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1665 null, null, ACCOUNTS_TYPE, null, null);
1666 try {
1667 while (cursor.moveToNext()) {
1668 // print type,count
1669 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1670 }
1671 } finally {
1672 if (cursor != null) {
1673 cursor.close();
1674 }
1675 }
1676 } else {
Fred Quintana307da1a2010-01-21 14:24:20 -08001677 Account[] accounts = getAccounts(null /* type */);
1678 fout.println("Accounts: " + accounts.length);
1679 for (Account account : accounts) {
1680 fout.println(" " + account);
1681 }
1682
1683 fout.println();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001684 synchronized (mSessions) {
1685 final long now = SystemClock.elapsedRealtime();
Fred Quintana307da1a2010-01-21 14:24:20 -08001686 fout.println("Active Sessions: " + mSessions.size());
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001687 for (Session session : mSessions.values()) {
1688 fout.println(" " + session.toDebugString(now));
1689 }
1690 }
1691
1692 fout.println();
1693 mAuthenticatorCache.dump(fd, fout, args);
1694 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001695 }
1696
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001697 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001698 long identityToken = clearCallingIdentity();
1699 try {
1700 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1701 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1702 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001703
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001704 if (intent.getComponent() != null &&
1705 GrantCredentialsPermissionActivity.class.getName().equals(
1706 intent.getComponent().getClassName())) {
1707 createNoCredentialsPermissionNotification(account, intent);
1708 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001709 final Integer notificationId = getSigninRequiredNotificationId(account);
1710 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001711 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1712 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001713 final String notificationTitleFormat =
1714 mContext.getText(R.string.notification_title).toString();
1715 n.setLatestEventInfo(mContext,
1716 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001717 message, PendingIntent.getActivity(
1718 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1719 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001720 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001721 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001722 } finally {
1723 restoreCallingIdentity(identityToken);
1724 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001725 }
1726
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001727 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001728 long identityToken = clearCallingIdentity();
1729 try {
1730 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001731 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001732 } finally {
1733 restoreCallingIdentity(identityToken);
1734 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001735 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001736
1737 private void checkBinderPermission(String permission) {
1738 final int uid = Binder.getCallingUid();
1739 if (mContext.checkCallingOrSelfPermission(permission) !=
1740 PackageManager.PERMISSION_GRANTED) {
1741 String msg = "caller uid " + uid + " lacks " + permission;
1742 Log.w(TAG, msg);
1743 throw new SecurityException(msg);
1744 }
1745 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1746 Log.v(TAG, "caller uid " + uid + " has " + permission);
1747 }
1748 }
1749
Fred Quintana7be59642009-08-24 18:29:25 -07001750 private boolean inSystemImage(int callerUid) {
1751 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1752 for (String name : packages) {
1753 try {
1754 PackageInfo packageInfo =
1755 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1756 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1757 return true;
1758 }
1759 } catch (PackageManager.NameNotFoundException e) {
1760 return false;
1761 }
1762 }
1763 return false;
1764 }
1765
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001766 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001767 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07001768 final boolean fromAuthenticator = account != null
1769 && hasAuthenticatorUid(account.type, callerUid);
1770 final boolean hasExplicitGrants = account != null
1771 && hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001772 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1773 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1774 + callerUid + ", account " + account
1775 + ": is authenticator? " + fromAuthenticator
1776 + ", has explicit permission? " + hasExplicitGrants);
1777 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001778 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001779 }
1780
Fred Quintana1a231912009-10-15 11:31:30 -07001781 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001782 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1783 mAuthenticatorCache.getAllServices()) {
1784 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001785 return (serviceInfo.uid == callingUid) ||
1786 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1787 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001788 }
1789 }
1790 return false;
1791 }
1792
1793 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1794 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1795 return true;
1796 }
1797 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1798 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001799 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001800 final boolean permissionGranted =
1801 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1802 if (!permissionGranted && isDebuggableMonkeyBuild) {
1803 // TODO: Skip this check when running automated tests. Replace this
1804 // with a more general solution.
Fred Quintana751fdc02010-02-09 14:13:18 -08001805 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001806 + authTokenType + " by uid " + Binder.getCallingUid()
1807 + " but ignoring since this is a monkey build");
1808 return true;
1809 }
1810 return permissionGranted;
1811 }
1812
1813 private void checkCallingUidAgainstAuthenticator(Account account) {
1814 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07001815 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001816 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1817 Log.w(TAG, msg);
1818 throw new SecurityException(msg);
1819 }
1820 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1821 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1822 }
1823 }
1824
1825 private void checkAuthenticateAccountsPermission(Account account) {
1826 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1827 checkCallingUidAgainstAuthenticator(account);
1828 }
1829
1830 private void checkReadAccountsPermission() {
1831 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1832 }
1833
1834 private void checkManageAccountsPermission() {
1835 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1836 }
1837
1838 /**
1839 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1840 * <p>
1841 * Although this is public it can only be accessed via the AccountManagerService object
1842 * which is in the system. This means we don't need to protect it with permissions.
1843 * @hide
1844 */
1845 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001846 if (account == null || authTokenType == null) {
1847 return;
1848 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001849 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1850 db.beginTransaction();
1851 try {
1852 long accountId = getAccountId(db, account);
1853 if (accountId >= 0) {
1854 ContentValues values = new ContentValues();
1855 values.put(GRANTS_ACCOUNTS_ID, accountId);
1856 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1857 values.put(GRANTS_GRANTEE_UID, uid);
1858 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1859 db.setTransactionSuccessful();
1860 }
1861 } finally {
1862 db.endTransaction();
1863 }
1864 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1865 }
1866
1867 /**
1868 * Don't allow callers with the given uid permission to get credentials for
1869 * account/authTokenType.
1870 * <p>
1871 * Although this is public it can only be accessed via the AccountManagerService object
1872 * which is in the system. This means we don't need to protect it with permissions.
1873 * @hide
1874 */
1875 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001876 if (account == null || authTokenType == null) {
1877 return;
1878 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001879 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1880 db.beginTransaction();
1881 try {
1882 long accountId = getAccountId(db, account);
1883 if (accountId >= 0) {
1884 db.delete(TABLE_GRANTS,
1885 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1886 + GRANTS_GRANTEE_UID + "=?",
1887 new String[]{String.valueOf(accountId), authTokenType,
1888 String.valueOf(uid)});
1889 db.setTransactionSuccessful();
1890 }
1891 } finally {
1892 db.endTransaction();
1893 }
1894 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1895 }
Fred Quintana60307342009-03-24 22:48:12 -07001896}