blob: ee26d3c79a39294a589b04a3cbeafd3ccaa44f3c [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) {
469 super(response, account.type, false /* expectActivityLaunch */);
470 mFeatures = features;
471 mAccount = account;
472 }
473
474 public void run() throws RemoteException {
475 try {
476 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
477 } catch (RemoteException e) {
478 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
479 }
480 }
481
482 public void onResult(Bundle result) {
483 IAccountManagerResponse response = getResponseAndClose();
484 if (response != null) {
485 try {
486 if (result == null) {
487 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
488 return;
489 }
490 final Bundle newResult = new Bundle();
491 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
492 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
493 response.onResult(newResult);
494 } catch (RemoteException e) {
495 // if the caller is dead then there is no one to care about remote exceptions
496 if (Log.isLoggable(TAG, Log.VERBOSE)) {
497 Log.v(TAG, "failure while notifying response", e);
498 }
499 }
500 }
501 }
502
503 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800504 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800505 + ", " + mAccount
506 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
507 }
508 }
509
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700510 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700511 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700512 long identityToken = clearCallingIdentity();
513 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700514 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700515 } finally {
516 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700517 }
Fred Quintana60307342009-03-24 22:48:12 -0700518 }
519
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700520 private class RemoveAccountSession extends Session {
521 final Account mAccount;
522 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
523 super(response, account.type, false /* expectActivityLaunch */);
524 mAccount = account;
525 }
526
527 protected String toDebugString(long now) {
528 return super.toDebugString(now) + ", removeAccount"
529 + ", account " + mAccount;
530 }
531
532 public void run() throws RemoteException {
533 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
534 }
535
536 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700537 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
538 && !result.containsKey(AccountManager.KEY_INTENT)) {
539 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700540 if (removalAllowed) {
541 removeAccount(mAccount);
542 }
543 IAccountManagerResponse response = getResponseAndClose();
544 if (response != null) {
545 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700546 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700547 try {
548 response.onResult(result2);
549 } catch (RemoteException e) {
550 // ignore
551 }
552 }
553 }
554 super.onResult(result);
555 }
556 }
557
558 private void removeAccount(Account account) {
559 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
560 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
561 new String[]{account.name, account.type});
562 sendAccountsChangedBroadcast();
563 }
564
Fred Quintanaa698f422009-04-08 19:14:54 -0700565 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700566 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700567 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700568 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700569 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
570 db.beginTransaction();
571 try {
572 invalidateAuthToken(db, accountType, authToken);
573 db.setTransactionSuccessful();
574 } finally {
575 db.endTransaction();
576 }
Fred Quintana60307342009-03-24 22:48:12 -0700577 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700578 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700579 }
580 }
581
582 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700583 if (authToken == null || accountType == null) {
584 return;
585 }
Fred Quintana33269202009-04-20 16:05:10 -0700586 Cursor cursor = db.rawQuery(
587 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
588 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
589 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
590 + " FROM " + TABLE_ACCOUNTS
591 + " JOIN " + TABLE_AUTHTOKENS
592 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
593 + " = " + AUTHTOKENS_ACCOUNTS_ID
594 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
595 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
596 new String[]{authToken, accountType});
597 try {
598 while (cursor.moveToNext()) {
599 long authTokenId = cursor.getLong(0);
600 String accountName = cursor.getString(1);
601 String authTokenType = cursor.getString(2);
602 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700603 }
Fred Quintana33269202009-04-20 16:05:10 -0700604 } finally {
605 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700606 }
607 }
608
609 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700610 if (account == null || type == null) {
611 return false;
612 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700613 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700614 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
615 db.beginTransaction();
616 try {
Fred Quintana33269202009-04-20 16:05:10 -0700617 long accountId = getAccountId(db, account);
618 if (accountId < 0) {
619 return false;
620 }
621 db.delete(TABLE_AUTHTOKENS,
622 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
623 new String[]{type});
624 ContentValues values = new ContentValues();
625 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
626 values.put(AUTHTOKENS_TYPE, type);
627 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
628 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700629 db.setTransactionSuccessful();
630 return true;
631 }
632 return false;
633 } finally {
634 db.endTransaction();
635 }
636 }
637
Fred Quintana60307342009-03-24 22:48:12 -0700638 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
Fred Quintana31957f12009-10-21 13:43:10 -0700639 if (account == null || authTokenType == null) {
640 return null;
641 }
Fred Quintana60307342009-03-24 22:48:12 -0700642 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700643 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
644 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
645 + AUTHTOKENS_TYPE + "=?",
646 new String[]{account.name, account.type, authTokenType},
647 null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700648 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700649 if (cursor.moveToNext()) {
650 return cursor.getString(0);
Fred Quintana60307342009-03-24 22:48:12 -0700651 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700652 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700653 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700654 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700655 }
656 }
657
Fred Quintanaa698f422009-04-08 19:14:54 -0700658 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700659 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700660 long identityToken = clearCallingIdentity();
661 try {
Fred Quintana33269202009-04-20 16:05:10 -0700662 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700663 } finally {
664 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700665 }
Fred Quintana60307342009-03-24 22:48:12 -0700666 }
667
Fred Quintanaa698f422009-04-08 19:14:54 -0700668 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700669 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700670 long identityToken = clearCallingIdentity();
671 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700672 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700673 } finally {
674 restoreCallingIdentity(identityToken);
675 }
Fred Quintana60307342009-03-24 22:48:12 -0700676 }
677
Fred Quintanaa698f422009-04-08 19:14:54 -0700678 public void setPassword(Account account, String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700679 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700680 long identityToken = clearCallingIdentity();
681 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700682 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700683 } finally {
684 restoreCallingIdentity(identityToken);
685 }
Fred Quintana60307342009-03-24 22:48:12 -0700686 }
687
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700688 private void setPasswordInDB(Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700689 if (account == null) {
690 return;
691 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700692 ContentValues values = new ContentValues();
693 values.put(ACCOUNTS_PASSWORD, password);
694 mOpenHelper.getWritableDatabase().update(TABLE_ACCOUNTS, values,
695 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
696 new String[]{account.name, account.type});
697 sendAccountsChangedBroadcast();
698 }
699
Fred Quintana33269202009-04-20 16:05:10 -0700700 private void sendAccountsChangedBroadcast() {
701 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
702 }
703
Fred Quintanaa698f422009-04-08 19:14:54 -0700704 public void clearPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700705 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700706 long identityToken = clearCallingIdentity();
707 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700708 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700709 } finally {
710 restoreCallingIdentity(identityToken);
711 }
Fred Quintana60307342009-03-24 22:48:12 -0700712 }
713
Fred Quintanaa698f422009-04-08 19:14:54 -0700714 public void setUserData(Account account, String key, String value) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700715 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700716 long identityToken = clearCallingIdentity();
Fred Quintana31957f12009-10-21 13:43:10 -0700717 if (account == null) {
718 return;
719 }
Jim Miller50c05f32009-09-21 19:07:44 -0700720 if (account.type.equals(GOOGLE_ACCOUNT_TYPE) && key.equals("broadcast")) {
721 sendAccountsChangedBroadcast();
722 return;
723 }
Fred Quintana60307342009-03-24 22:48:12 -0700724 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700725 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700726 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700727 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700728 }
729 }
730
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700731 private void writeUserdataIntoDatabase(Account account, String key, String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700732 if (account == null || key == null) {
733 return;
734 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700735 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
736 db.beginTransaction();
737 try {
738 long accountId = getAccountId(db, account);
739 if (accountId < 0) {
740 return;
741 }
742 long extrasId = getExtrasId(db, accountId, key);
743 if (extrasId < 0 ) {
744 extrasId = insertExtra(db, accountId, key, value);
745 if (extrasId < 0) {
746 return;
747 }
748 } else {
749 ContentValues values = new ContentValues();
750 values.put(EXTRAS_VALUE, value);
751 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
752 return;
753 }
754
755 }
756 db.setTransactionSuccessful();
757 } finally {
758 db.endTransaction();
759 }
760 }
761
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700762 private void onResult(IAccountManagerResponse response, Bundle result) {
763 try {
764 response.onResult(result);
765 } catch (RemoteException e) {
766 // if the caller is dead then there is no one to care about remote
767 // exceptions
768 if (Log.isLoggable(TAG, Log.VERBOSE)) {
769 Log.v(TAG, "failure while notifying response", e);
770 }
771 }
772 }
773
Fred Quintanaa698f422009-04-08 19:14:54 -0700774 public void getAuthToken(IAccountManagerResponse response, final Account account,
775 final String authTokenType, final boolean notifyOnAuthFailure,
776 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700777 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
778 final int callerUid = Binder.getCallingUid();
779 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
780
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700781 long identityToken = clearCallingIdentity();
782 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700783 // if the caller has permission, do the peek. otherwise go the more expensive
784 // route of starting a Session
785 if (permissionGranted) {
786 String authToken = readAuthTokenFromDatabase(account, authTokenType);
787 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700788 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700789 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
790 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
791 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700792 onResult(response, result);
793 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700794 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700795 }
796
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700797 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700798 protected String toDebugString(long now) {
799 if (loginOptions != null) loginOptions.keySet();
800 return super.toDebugString(now) + ", getAuthToken"
801 + ", " + account
802 + ", authTokenType " + authTokenType
803 + ", loginOptions " + loginOptions
804 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
805 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700806
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700807 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700808 // If the caller doesn't have permission then create and return the
809 // "grant permission" intent instead of the "getAuthToken" intent.
810 if (!permissionGranted) {
811 mAuthenticator.getAuthTokenLabel(this, authTokenType);
812 } else {
813 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
814 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700815 }
816
817 public void onResult(Bundle result) {
818 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700819 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700820 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
821 new AccountAuthenticatorResponse(this),
822 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700823 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700824 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700825 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700826 onResult(bundle);
827 return;
828 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700829 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700830 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700831 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
832 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700833 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700834 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700835 "the type and name should not be empty");
836 return;
837 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700838 saveAuthTokenToDatabase(new Account(name, type),
839 authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700840 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700841
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700842 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700843 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700844 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700845 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700846 intent);
847 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700848 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700849 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700850 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700851 }.bind();
852 } finally {
853 restoreCallingIdentity(identityToken);
854 }
Fred Quintana60307342009-03-24 22:48:12 -0700855 }
856
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700857 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
858 int uid = intent.getIntExtra(
859 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
860 String authTokenType = intent.getStringExtra(
861 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
862 String authTokenLabel = intent.getStringExtra(
863 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
864
865 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
866 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700867 final String titleAndSubtitle =
868 mContext.getString(R.string.permission_request_notification_with_subtitle,
869 account.name);
870 final int index = titleAndSubtitle.indexOf('\n');
871 final String title = titleAndSubtitle.substring(0, index);
872 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700873 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700874 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700875 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
876 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
877 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
878 }
879
880 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
881 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
882 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
883 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700884 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700885 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700886 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700887 }
888
889 final Context authContext;
890 try {
891 authContext = mContext.createPackageContext(
892 serviceInfo.type.packageName, 0);
893 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700894 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700895 }
896
897 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
898 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
899 intent.addCategory(
900 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
901 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
902 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
903 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
904 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
905 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
906 authContext.getString(serviceInfo.type.labelId));
907 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
908 mContext.getPackageManager().getPackagesForUid(uid));
909 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
910 return intent;
911 }
912
913 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
914 int uid) {
915 Integer id;
916 synchronized(mCredentialsPermissionNotificationIds) {
917 final Pair<Pair<Account, String>, Integer> key =
918 new Pair<Pair<Account, String>, Integer>(
919 new Pair<Account, String>(account, authTokenType), uid);
920 id = mCredentialsPermissionNotificationIds.get(key);
921 if (id == null) {
922 id = mNotificationIds.incrementAndGet();
923 mCredentialsPermissionNotificationIds.put(key, id);
924 }
925 }
926 return id;
927 }
928
929 private Integer getSigninRequiredNotificationId(Account account) {
930 Integer id;
931 synchronized(mSigninRequiredNotificationIds) {
932 id = mSigninRequiredNotificationIds.get(account);
933 if (id == null) {
934 id = mNotificationIds.incrementAndGet();
935 mSigninRequiredNotificationIds.put(account, id);
936 }
937 }
938 return id;
939 }
940
Fred Quintanaa698f422009-04-08 19:14:54 -0700941
Fred Quintana33269202009-04-20 16:05:10 -0700942 public void addAcount(final IAccountManagerResponse response, final String accountType,
943 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700944 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700945 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700946 long identityToken = clearCallingIdentity();
947 try {
948 new Session(response, accountType, expectActivityLaunch) {
949 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -0700950 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -0700951 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700952 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700953
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700954 protected String toDebugString(long now) {
955 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -0700956 + ", accountType " + accountType
957 + ", requiredFeatures "
958 + (requiredFeatures != null
959 ? TextUtils.join(",", requiredFeatures)
960 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700961 }
962 }.bind();
963 } finally {
964 restoreCallingIdentity(identityToken);
965 }
Fred Quintana60307342009-03-24 22:48:12 -0700966 }
967
Fred Quintanaa698f422009-04-08 19:14:54 -0700968 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700969 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700970 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700971 long identityToken = clearCallingIdentity();
972 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700973 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700974 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700975 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700976 }
977 protected String toDebugString(long now) {
978 return super.toDebugString(now) + ", confirmCredentials"
979 + ", " + account;
980 }
981 }.bind();
982 } finally {
983 restoreCallingIdentity(identityToken);
984 }
Fred Quintana60307342009-03-24 22:48:12 -0700985 }
986
Fred Quintanaa698f422009-04-08 19:14:54 -0700987 public void updateCredentials(IAccountManagerResponse response, final Account account,
988 final String authTokenType, final boolean expectActivityLaunch,
989 final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700990 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700991 long identityToken = clearCallingIdentity();
992 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700993 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700994 public void run() throws RemoteException {
995 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
996 }
997 protected String toDebugString(long now) {
998 if (loginOptions != null) loginOptions.keySet();
999 return super.toDebugString(now) + ", updateCredentials"
1000 + ", " + account
1001 + ", authTokenType " + authTokenType
1002 + ", loginOptions " + loginOptions;
1003 }
1004 }.bind();
1005 } finally {
1006 restoreCallingIdentity(identityToken);
1007 }
Fred Quintana60307342009-03-24 22:48:12 -07001008 }
1009
Fred Quintanaa698f422009-04-08 19:14:54 -07001010 public void editProperties(IAccountManagerResponse response, final String accountType,
1011 final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001012 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001013 long identityToken = clearCallingIdentity();
1014 try {
1015 new Session(response, accountType, expectActivityLaunch) {
1016 public void run() throws RemoteException {
1017 mAuthenticator.editProperties(this, mAccountType);
1018 }
1019 protected String toDebugString(long now) {
1020 return super.toDebugString(now) + ", editProperties"
1021 + ", accountType " + accountType;
1022 }
1023 }.bind();
1024 } finally {
1025 restoreCallingIdentity(identityToken);
1026 }
Fred Quintana60307342009-03-24 22:48:12 -07001027 }
1028
Fred Quintana33269202009-04-20 16:05:10 -07001029 private class GetAccountsByTypeAndFeatureSession extends Session {
1030 private final String[] mFeatures;
1031 private volatile Account[] mAccountsOfType = null;
1032 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1033 private volatile int mCurrentAccount = 0;
1034
1035 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
1036 String type, String[] features) {
1037 super(response, type, false /* expectActivityLaunch */);
1038 mFeatures = features;
1039 }
1040
1041 public void run() throws RemoteException {
1042 mAccountsOfType = getAccountsByType(mAccountType);
1043 // check whether each account matches the requested features
1044 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1045 mCurrentAccount = 0;
1046
1047 checkAccount();
1048 }
1049
1050 public void checkAccount() {
1051 if (mCurrentAccount >= mAccountsOfType.length) {
1052 sendResult();
1053 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001054 }
Fred Quintana33269202009-04-20 16:05:10 -07001055
1056 try {
1057 mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
1058 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001059 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001060 }
1061 }
1062
1063 public void onResult(Bundle result) {
1064 mNumResults++;
1065 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001066 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001067 return;
1068 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001069 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001070 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1071 }
1072 mCurrentAccount++;
1073 checkAccount();
1074 }
1075
1076 public void sendResult() {
1077 IAccountManagerResponse response = getResponseAndClose();
1078 if (response != null) {
1079 try {
1080 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1081 for (int i = 0; i < accounts.length; i++) {
1082 accounts[i] = mAccountsWithFeatures.get(i);
1083 }
1084 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001085 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001086 response.onResult(result);
1087 } catch (RemoteException e) {
1088 // if the caller is dead then there is no one to care about remote exceptions
1089 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1090 Log.v(TAG, "failure while notifying response", e);
1091 }
1092 }
1093 }
1094 }
1095
1096
1097 protected String toDebugString(long now) {
1098 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1099 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1100 }
1101 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001102
1103 public Account[] getAccounts(String type) {
1104 checkReadAccountsPermission();
1105 long identityToken = clearCallingIdentity();
1106 try {
1107 return getAccountsByType(type);
1108 } finally {
1109 restoreCallingIdentity(identityToken);
1110 }
1111 }
1112
1113 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001114 String type, String[] features) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001115 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001116 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -07001117 if (response != null) {
1118 try {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001119 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "type is null");
Fred Quintana33269202009-04-20 16:05:10 -07001120 } catch (RemoteException e) {
1121 // ignore this
1122 }
1123 }
1124 return;
1125 }
1126 long identityToken = clearCallingIdentity();
1127 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001128 if (features == null || features.length == 0) {
1129 getAccountsByType(type);
1130 return;
1131 }
Fred Quintana33269202009-04-20 16:05:10 -07001132 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1133 } finally {
1134 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001135 }
1136 }
1137
Fred Quintana60307342009-03-24 22:48:12 -07001138 private long getAccountId(SQLiteDatabase db, Account account) {
1139 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001140 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001141 try {
1142 if (cursor.moveToNext()) {
1143 return cursor.getLong(0);
1144 }
1145 return -1;
1146 } finally {
1147 cursor.close();
1148 }
1149 }
1150
1151 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1152 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1153 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1154 new String[]{key}, null, null, null);
1155 try {
1156 if (cursor.moveToNext()) {
1157 return cursor.getLong(0);
1158 }
1159 return -1;
1160 } finally {
1161 cursor.close();
1162 }
1163 }
1164
Fred Quintanaa698f422009-04-08 19:14:54 -07001165 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001166 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001167 IAccountManagerResponse mResponse;
1168 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001169 final boolean mExpectActivityLaunch;
1170 final long mCreationTime;
1171
Fred Quintana33269202009-04-20 16:05:10 -07001172 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001173 private int mNumRequestContinued = 0;
1174 private int mNumErrors = 0;
1175
Fred Quintana60307342009-03-24 22:48:12 -07001176
1177 IAccountAuthenticator mAuthenticator = null;
1178
Fred Quintanaa698f422009-04-08 19:14:54 -07001179 public Session(IAccountManagerResponse response, String accountType,
1180 boolean expectActivityLaunch) {
Fred Quintana60307342009-03-24 22:48:12 -07001181 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001182 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001183 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana60307342009-03-24 22:48:12 -07001184 mResponse = response;
1185 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001186 mExpectActivityLaunch = expectActivityLaunch;
1187 mCreationTime = SystemClock.elapsedRealtime();
1188 synchronized (mSessions) {
1189 mSessions.put(toString(), this);
1190 }
1191 try {
1192 response.asBinder().linkToDeath(this, 0 /* flags */);
1193 } catch (RemoteException e) {
1194 mResponse = null;
1195 binderDied();
1196 }
Fred Quintana60307342009-03-24 22:48:12 -07001197 }
1198
Fred Quintanaa698f422009-04-08 19:14:54 -07001199 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001200 if (mResponse == null) {
1201 // this session has already been closed
1202 return null;
1203 }
Fred Quintana60307342009-03-24 22:48:12 -07001204 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001205 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001206 return response;
1207 }
1208
Fred Quintanaa698f422009-04-08 19:14:54 -07001209 private void close() {
1210 synchronized (mSessions) {
1211 if (mSessions.remove(toString()) == null) {
1212 // the session was already closed, so bail out now
1213 return;
1214 }
1215 }
1216 if (mResponse != null) {
1217 // stop listening for response deaths
1218 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1219
1220 // clear this so that we don't accidentally send any further results
1221 mResponse = null;
1222 }
1223 cancelTimeout();
1224 unbind();
1225 }
1226
1227 public void binderDied() {
1228 mResponse = null;
1229 close();
1230 }
1231
1232 protected String toDebugString() {
1233 return toDebugString(SystemClock.elapsedRealtime());
1234 }
1235
1236 protected String toDebugString(long now) {
1237 return "Session: expectLaunch " + mExpectActivityLaunch
1238 + ", connected " + (mAuthenticator != null)
1239 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1240 + "/" + mNumErrors + ")"
1241 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1242 }
1243
Fred Quintana60307342009-03-24 22:48:12 -07001244 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001245 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1246 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1247 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001248 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001249 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001250 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001251 }
1252 }
1253
1254 private void unbind() {
1255 if (mAuthenticator != null) {
1256 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001257 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001258 }
1259 }
1260
1261 public void scheduleTimeout() {
1262 mMessageHandler.sendMessageDelayed(
1263 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1264 }
1265
1266 public void cancelTimeout() {
1267 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1268 }
1269
Fred Quintanab839afc2009-10-14 15:57:28 -07001270 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001271 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001272 try {
1273 run();
1274 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001275 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001276 "remote exception");
1277 }
Fred Quintana60307342009-03-24 22:48:12 -07001278 }
1279
Fred Quintanab839afc2009-10-14 15:57:28 -07001280 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001281 mAuthenticator = null;
1282 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001283 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001284 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001285 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001286 }
1287 }
1288
Fred Quintanab839afc2009-10-14 15:57:28 -07001289 public abstract void run() throws RemoteException;
1290
Fred Quintana60307342009-03-24 22:48:12 -07001291 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001292 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001293 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001294 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001295 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001296 }
1297 }
1298
Fred Quintanaa698f422009-04-08 19:14:54 -07001299 public void onResult(Bundle result) {
1300 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001301 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1302 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1303 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001304 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1305 Account account = new Account(accountName, accountType);
1306 cancelNotification(getSigninRequiredNotificationId(account));
1307 }
Fred Quintana60307342009-03-24 22:48:12 -07001308 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001309 IAccountManagerResponse response;
1310 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001311 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001312 response = mResponse;
1313 } else {
1314 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001315 }
Fred Quintana60307342009-03-24 22:48:12 -07001316 if (response != null) {
1317 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001318 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001319 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001320 "null bundle returned");
1321 } else {
1322 response.onResult(result);
1323 }
Fred Quintana60307342009-03-24 22:48:12 -07001324 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001325 // if the caller is dead then there is no one to care about remote exceptions
1326 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1327 Log.v(TAG, "failure while notifying response", e);
1328 }
Fred Quintana60307342009-03-24 22:48:12 -07001329 }
1330 }
1331 }
Fred Quintana60307342009-03-24 22:48:12 -07001332
Fred Quintanaa698f422009-04-08 19:14:54 -07001333 public void onRequestContinued() {
1334 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001335 }
1336
1337 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001338 mNumErrors++;
1339 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1340 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001341 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001342 IAccountManagerResponse response = getResponseAndClose();
1343 if (response != null) {
1344 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1345 Log.v(TAG, "Session.onError: responding");
1346 }
1347 try {
1348 response.onError(errorCode, errorMessage);
1349 } catch (RemoteException e) {
1350 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1351 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1352 }
1353 }
1354 } else {
1355 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1356 Log.v(TAG, "Session.onError: already closed");
1357 }
Fred Quintana60307342009-03-24 22:48:12 -07001358 }
1359 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001360
1361 /**
1362 * find the component name for the authenticator and initiate a bind
1363 * if no authenticator or the bind fails then return false, otherwise return true
1364 */
1365 private boolean bindToAuthenticator(String authenticatorType) {
1366 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1367 mAuthenticatorCache.getServiceInfo(
1368 AuthenticatorDescription.newKey(authenticatorType));
1369 if (authenticatorInfo == null) {
1370 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1371 Log.v(TAG, "there is no authenticator for " + authenticatorType
1372 + ", bailing out");
1373 }
1374 return false;
1375 }
1376
1377 Intent intent = new Intent();
1378 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1379 intent.setComponent(authenticatorInfo.componentName);
1380 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1381 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1382 }
1383 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1384 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1385 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1386 }
1387 return false;
1388 }
1389
1390
1391 return true;
1392 }
Fred Quintana60307342009-03-24 22:48:12 -07001393 }
1394
1395 private class MessageHandler extends Handler {
1396 MessageHandler(Looper looper) {
1397 super(looper);
1398 }
Costin Manolache3348f142009-09-29 18:58:36 -07001399
Fred Quintana60307342009-03-24 22:48:12 -07001400 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001401 switch (msg.what) {
1402 case MESSAGE_TIMED_OUT:
1403 Session session = (Session)msg.obj;
1404 session.onTimedOut();
1405 break;
1406
1407 default:
1408 throw new IllegalStateException("unhandled message: " + msg.what);
1409 }
1410 }
1411 }
1412
Oscar Montemayora8529f62009-11-18 10:14:20 -08001413 private static String getDatabaseName() {
1414 if(Environment.isEncryptedFilesystemEnabled()) {
1415 // Hard-coded path in case of encrypted file system
1416 return Environment.getSystemSecureDirectory().getPath() + File.separator + DATABASE_NAME;
1417 } else {
1418 // Regular path in case of non-encrypted file system
1419 return DATABASE_NAME;
1420 }
1421 }
1422
Fred Quintana60307342009-03-24 22:48:12 -07001423 private class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001424
Fred Quintana60307342009-03-24 22:48:12 -07001425 public DatabaseHelper(Context context) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001426 super(context, AccountManagerService.getDatabaseName(), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001427 }
1428
1429 @Override
1430 public void onCreate(SQLiteDatabase db) {
1431 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1432 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1433 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1434 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1435 + ACCOUNTS_PASSWORD + " TEXT, "
1436 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1437
1438 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1439 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1440 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1441 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1442 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1443 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1444
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001445 createGrantsTable(db);
1446
Fred Quintana60307342009-03-24 22:48:12 -07001447 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1448 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1449 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1450 + EXTRAS_KEY + " TEXT NOT NULL, "
1451 + EXTRAS_VALUE + " TEXT, "
1452 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1453
1454 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1455 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1456 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001457
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001458 createAccountsDeletionTrigger(db);
1459 }
1460
1461 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001462 db.execSQL(""
1463 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1464 + " BEGIN"
1465 + " DELETE FROM " + TABLE_AUTHTOKENS
1466 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1467 + " DELETE FROM " + TABLE_EXTRAS
1468 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001469 + " DELETE FROM " + TABLE_GRANTS
1470 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001471 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001472 }
1473
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001474 private void createGrantsTable(SQLiteDatabase db) {
1475 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1476 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1477 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1478 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1479 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1480 + "," + GRANTS_GRANTEE_UID + "))");
1481 }
1482
Fred Quintana60307342009-03-24 22:48:12 -07001483 @Override
1484 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001485 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001486
Fred Quintanaa698f422009-04-08 19:14:54 -07001487 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001488 // no longer need to do anything since the work is done
1489 // when upgrading from version 2
1490 oldVersion++;
1491 }
1492
1493 if (oldVersion == 2) {
1494 createGrantsTable(db);
1495 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1496 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001497 oldVersion++;
1498 }
Costin Manolache3348f142009-09-29 18:58:36 -07001499
1500 if (oldVersion == 3) {
1501 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1502 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1503 oldVersion++;
1504 }
Fred Quintana60307342009-03-24 22:48:12 -07001505 }
1506
1507 @Override
1508 public void onOpen(SQLiteDatabase db) {
1509 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1510 }
1511 }
1512
1513 private void setMetaValue(String key, String value) {
1514 ContentValues values = new ContentValues();
1515 values.put(META_KEY, key);
1516 values.put(META_VALUE, value);
1517 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1518 }
1519
1520 private String getMetaValue(String key) {
1521 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1522 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1523 try {
1524 if (c.moveToNext()) {
1525 return c.getString(0);
1526 }
1527 return null;
1528 } finally {
1529 c.close();
1530 }
1531 }
1532
1533 private class SimWatcher extends BroadcastReceiver {
1534 public SimWatcher(Context context) {
1535 // Re-scan the SIM card when the SIM state changes, and also if
1536 // the disk recovers from a full state (we may have failed to handle
1537 // things properly while the disk was full).
1538 final IntentFilter filter = new IntentFilter();
1539 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1540 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1541 context.registerReceiver(this, filter);
1542 }
Costin Manolache3348f142009-09-29 18:58:36 -07001543
Fred Quintana60307342009-03-24 22:48:12 -07001544 /**
1545 * Compare the IMSI to the one stored in the login service's
1546 * database. If they differ, erase all passwords and
1547 * authtokens (and store the new IMSI).
1548 */
1549 @Override
1550 public void onReceive(Context context, Intent intent) {
Doug Zongker885cfc232009-10-21 16:52:44 -07001551 // Check IMSI on every update; nothing happens if the IMSI
1552 // is missing or unchanged.
1553 TelephonyManager telephonyManager =
1554 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1555 if (telephonyManager == null) {
1556 Log.w(TAG, "failed to get TelephonyManager");
1557 return;
1558 }
1559 String imsi = telephonyManager.getSubscriberId();
1560
1561 // If the subscriber ID is an empty string, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001562 if (TextUtils.isEmpty(imsi)) return;
1563
Doug Zongker885cfc232009-10-21 16:52:44 -07001564 // If the current IMSI matches what's stored, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001565 String storedImsi = getMetaValue("imsi");
Fred Quintana60307342009-03-24 22:48:12 -07001566 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1567 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1568 }
Doug Zongker885cfc232009-10-21 16:52:44 -07001569 if (imsi.equals(storedImsi)) return;
1570
1571 // If a CDMA phone is unprovisioned, getSubscriberId()
1572 // will return a different value, but we *don't* erase the
1573 // passwords. We only erase them if it has a different
1574 // subscriber ID once it's provisioned.
1575 if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
1576 IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
1577 if (service == null) {
1578 Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
1579 return;
1580 }
1581 ITelephony telephony = ITelephony.Stub.asInterface(service);
1582 if (telephony == null) {
1583 Log.w(TAG, "failed to get ITelephony interface");
1584 return;
1585 }
1586 boolean needsProvisioning;
1587 try {
1588 needsProvisioning = telephony.getCdmaNeedsProvisioning();
1589 } catch (RemoteException e) {
1590 Log.w(TAG, "exception while checking provisioning", e);
1591 // default to NOT wiping out the passwords
1592 needsProvisioning = true;
1593 }
1594 if (needsProvisioning) {
1595 // if the phone needs re-provisioning, don't do anything.
1596 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1597 Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
1598 storedImsi);
1599 }
1600 return;
1601 }
1602 }
Fred Quintana60307342009-03-24 22:48:12 -07001603
jsh5b462472009-09-01 16:13:55 -07001604 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001605 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1606 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001607 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1608 db.beginTransaction();
1609 try {
1610 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1611 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001612 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001613 db.setTransactionSuccessful();
1614 } finally {
1615 db.endTransaction();
1616 }
1617 }
1618 setMetaValue("imsi", imsi);
1619 }
1620 }
1621
1622 public IBinder onBind(Intent intent) {
1623 return asBinder();
1624 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001625
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001626 /**
1627 * Searches array of arguments for the specified string
1628 * @param args array of argument strings
1629 * @param value value to search for
1630 * @return true if the value is contained in the array
1631 */
1632 private static boolean scanArgs(String[] args, String value) {
1633 if (args != null) {
1634 for (String arg : args) {
1635 if (value.equals(arg)) {
1636 return true;
1637 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001638 }
1639 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001640 return false;
1641 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001642
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001643 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1644 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001645
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001646 if (isCheckinRequest) {
1647 // This is a checkin request. *Only* upload the account types and the count of each.
1648 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1649
1650 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1651 null, null, ACCOUNTS_TYPE, null, null);
1652 try {
1653 while (cursor.moveToNext()) {
1654 // print type,count
1655 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1656 }
1657 } finally {
1658 if (cursor != null) {
1659 cursor.close();
1660 }
1661 }
1662 } else {
1663 synchronized (mSessions) {
1664 final long now = SystemClock.elapsedRealtime();
1665 fout.println("AccountManagerService: " + mSessions.size() + " sessions");
1666 for (Session session : mSessions.values()) {
1667 fout.println(" " + session.toDebugString(now));
1668 }
1669 }
1670
1671 fout.println();
1672 mAuthenticatorCache.dump(fd, fout, args);
1673 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001674 }
1675
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001676 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001677 long identityToken = clearCallingIdentity();
1678 try {
1679 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1680 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1681 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001682
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001683 if (intent.getComponent() != null &&
1684 GrantCredentialsPermissionActivity.class.getName().equals(
1685 intent.getComponent().getClassName())) {
1686 createNoCredentialsPermissionNotification(account, intent);
1687 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001688 final Integer notificationId = getSigninRequiredNotificationId(account);
1689 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001690 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1691 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001692 final String notificationTitleFormat =
1693 mContext.getText(R.string.notification_title).toString();
1694 n.setLatestEventInfo(mContext,
1695 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001696 message, PendingIntent.getActivity(
1697 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1698 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001699 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001700 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001701 } finally {
1702 restoreCallingIdentity(identityToken);
1703 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001704 }
1705
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001706 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001707 long identityToken = clearCallingIdentity();
1708 try {
1709 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001710 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001711 } finally {
1712 restoreCallingIdentity(identityToken);
1713 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001714 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001715
1716 private void checkBinderPermission(String permission) {
1717 final int uid = Binder.getCallingUid();
1718 if (mContext.checkCallingOrSelfPermission(permission) !=
1719 PackageManager.PERMISSION_GRANTED) {
1720 String msg = "caller uid " + uid + " lacks " + permission;
1721 Log.w(TAG, msg);
1722 throw new SecurityException(msg);
1723 }
1724 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1725 Log.v(TAG, "caller uid " + uid + " has " + permission);
1726 }
1727 }
1728
Fred Quintana7be59642009-08-24 18:29:25 -07001729 private boolean inSystemImage(int callerUid) {
1730 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1731 for (String name : packages) {
1732 try {
1733 PackageInfo packageInfo =
1734 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1735 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1736 return true;
1737 }
1738 } catch (PackageManager.NameNotFoundException e) {
1739 return false;
1740 }
1741 }
1742 return false;
1743 }
1744
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001745 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001746 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07001747 final boolean fromAuthenticator = account != null
1748 && hasAuthenticatorUid(account.type, callerUid);
1749 final boolean hasExplicitGrants = account != null
1750 && hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001751 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1752 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1753 + callerUid + ", account " + account
1754 + ": is authenticator? " + fromAuthenticator
1755 + ", has explicit permission? " + hasExplicitGrants);
1756 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001757 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001758 }
1759
Fred Quintana1a231912009-10-15 11:31:30 -07001760 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001761 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1762 mAuthenticatorCache.getAllServices()) {
1763 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001764 return (serviceInfo.uid == callingUid) ||
1765 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1766 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001767 }
1768 }
1769 return false;
1770 }
1771
1772 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1773 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1774 return true;
1775 }
1776 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1777 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001778 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001779 final boolean permissionGranted =
1780 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1781 if (!permissionGranted && isDebuggableMonkeyBuild) {
1782 // TODO: Skip this check when running automated tests. Replace this
1783 // with a more general solution.
1784 Log.w(TAG, "no credentials permission for usage of " + account + ", "
1785 + authTokenType + " by uid " + Binder.getCallingUid()
1786 + " but ignoring since this is a monkey build");
1787 return true;
1788 }
1789 return permissionGranted;
1790 }
1791
1792 private void checkCallingUidAgainstAuthenticator(Account account) {
1793 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07001794 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001795 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1796 Log.w(TAG, msg);
1797 throw new SecurityException(msg);
1798 }
1799 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1800 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1801 }
1802 }
1803
1804 private void checkAuthenticateAccountsPermission(Account account) {
1805 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1806 checkCallingUidAgainstAuthenticator(account);
1807 }
1808
1809 private void checkReadAccountsPermission() {
1810 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1811 }
1812
1813 private void checkManageAccountsPermission() {
1814 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1815 }
1816
1817 /**
1818 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1819 * <p>
1820 * Although this is public it can only be accessed via the AccountManagerService object
1821 * which is in the system. This means we don't need to protect it with permissions.
1822 * @hide
1823 */
1824 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001825 if (account == null || authTokenType == null) {
1826 return;
1827 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001828 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1829 db.beginTransaction();
1830 try {
1831 long accountId = getAccountId(db, account);
1832 if (accountId >= 0) {
1833 ContentValues values = new ContentValues();
1834 values.put(GRANTS_ACCOUNTS_ID, accountId);
1835 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1836 values.put(GRANTS_GRANTEE_UID, uid);
1837 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1838 db.setTransactionSuccessful();
1839 }
1840 } finally {
1841 db.endTransaction();
1842 }
1843 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1844 }
1845
1846 /**
1847 * Don't allow callers with the given uid permission to get credentials for
1848 * account/authTokenType.
1849 * <p>
1850 * Although this is public it can only be accessed via the AccountManagerService object
1851 * which is in the system. This means we don't need to protect it with permissions.
1852 * @hide
1853 */
1854 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001855 if (account == null || authTokenType == null) {
1856 return;
1857 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001858 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1859 db.beginTransaction();
1860 try {
1861 long accountId = getAccountId(db, account);
1862 if (accountId >= 0) {
1863 db.delete(TABLE_GRANTS,
1864 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1865 + GRANTS_GRANTEE_UID + "=?",
1866 new String[]{String.valueOf(accountId), authTokenType,
1867 String.valueOf(uid)});
1868 db.setTransactionSuccessful();
1869 }
1870 } finally {
1871 db.endTransaction();
1872 }
1873 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1874 }
Fred Quintana60307342009-03-24 22:48:12 -07001875}