blob: de011539d1229f5d7767679a60ec13f74be235c2 [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;
41import android.os.Handler;
42import android.os.HandlerThread;
43import android.os.IBinder;
44import android.os.Looper;
45import android.os.Message;
46import android.os.RemoteException;
Doug Zongker885cfc232009-10-21 16:52:44 -070047import android.os.ServiceManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070048import android.os.SystemClock;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070049import android.os.SystemProperties;
Fred Quintana60307342009-03-24 22:48:12 -070050import android.telephony.TelephonyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070051import android.text.TextUtils;
52import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070053import android.util.Pair;
Fred Quintana60307342009-03-24 22:48:12 -070054
Fred Quintanaa698f422009-04-08 19:14:54 -070055import java.io.FileDescriptor;
56import java.io.PrintWriter;
57import java.util.ArrayList;
58import java.util.Collection;
Fred Quintanaa698f422009-04-08 19:14:54 -070059import java.util.LinkedHashMap;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070060import java.util.HashMap;
61import java.util.concurrent.atomic.AtomicInteger;
62import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070063
Fred Quintana26fc5eb2009-04-09 15:05:50 -070064import com.android.internal.R;
Doug Zongker885cfc232009-10-21 16:52:44 -070065import com.android.internal.telephony.ITelephony;
66import com.android.internal.telephony.TelephonyIntents;
Fred Quintana60307342009-03-24 22:48:12 -070067
68/**
69 * A system service that provides account, password, and authtoken management for all
70 * accounts on the device. Some of these calls are implemented with the help of the corresponding
71 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
72 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
73 * AccountManager accountManager =
74 * (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE)
Fred Quintana33269202009-04-20 16:05:10 -070075 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070076 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070077public class AccountManagerService
78 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080079 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Costin Manolache3348f142009-09-29 18:58:36 -070080 private static final String GOOGLE_ACCOUNT_TYPE = "com.google";
Jim Miller50c05f32009-09-21 19:07:44 -070081
82 private static final String NO_BROADCAST_FLAG = "nobroadcast";
83
Fred Quintana60307342009-03-24 22:48:12 -070084 private static final String TAG = "AccountManagerService";
85
86 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
87 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070088 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070089
90 private final Context mContext;
91
92 private HandlerThread mMessageThread;
93 private final MessageHandler mMessageHandler;
94
95 // Messages that can be sent on mHandler
96 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -070097
98 private final AccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -070099 private final DatabaseHelper mOpenHelper;
100 private final SimWatcher mSimWatcher;
101
102 private static final String TABLE_ACCOUNTS = "accounts";
103 private static final String ACCOUNTS_ID = "_id";
104 private static final String ACCOUNTS_NAME = "name";
105 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700106 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700107 private static final String ACCOUNTS_PASSWORD = "password";
108
109 private static final String TABLE_AUTHTOKENS = "authtokens";
110 private static final String AUTHTOKENS_ID = "_id";
111 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
112 private static final String AUTHTOKENS_TYPE = "type";
113 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
114
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700115 private static final String TABLE_GRANTS = "grants";
116 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
117 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
118 private static final String GRANTS_GRANTEE_UID = "uid";
119
Fred Quintana60307342009-03-24 22:48:12 -0700120 private static final String TABLE_EXTRAS = "extras";
121 private static final String EXTRAS_ID = "_id";
122 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
123 private static final String EXTRAS_KEY = "key";
124 private static final String EXTRAS_VALUE = "value";
125
126 private static final String TABLE_META = "meta";
127 private static final String META_KEY = "key";
128 private static final String META_VALUE = "value";
129
130 private static final String[] ACCOUNT_NAME_TYPE_PROJECTION =
131 new String[]{ACCOUNTS_ID, ACCOUNTS_NAME, ACCOUNTS_TYPE};
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700132 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
133 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700134 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700135
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700136 private static final String COUNT_OF_MATCHING_GRANTS = ""
137 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
138 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
139 + " AND " + GRANTS_GRANTEE_UID + "=?"
140 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
141 + " AND " + ACCOUNTS_NAME + "=?"
142 + " AND " + ACCOUNTS_TYPE + "=?";
143
Fred Quintanaa698f422009-04-08 19:14:54 -0700144 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700145 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
146
147 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
148 mCredentialsPermissionNotificationIds =
149 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
150 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
151 new HashMap<Account, Integer>();
152 private static AtomicReference<AccountManagerService> sThis =
153 new AtomicReference<AccountManagerService>();
154
155 private static final boolean isDebuggableMonkeyBuild =
156 SystemProperties.getBoolean("ro.monkey", false)
157 && SystemProperties.getBoolean("ro.debuggable", false);
Fred Quintana31957f12009-10-21 13:43:10 -0700158 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700159
160 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700161 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700162 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
163 }
164
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700165 /**
166 * This should only be called by system code. One should only call this after the service
167 * has started.
168 * @return a reference to the AccountManagerService instance
169 * @hide
170 */
171 public static AccountManagerService getSingleton() {
172 return sThis.get();
173 }
Fred Quintana60307342009-03-24 22:48:12 -0700174
175 public class AuthTokenKey {
176 public final Account mAccount;
177 public final String mAuthTokenType;
178 private final int mHashCode;
179
180 public AuthTokenKey(Account account, String authTokenType) {
181 mAccount = account;
182 mAuthTokenType = authTokenType;
183 mHashCode = computeHashCode();
184 }
185
186 public boolean equals(Object o) {
187 if (o == this) {
188 return true;
189 }
190 if (!(o instanceof AuthTokenKey)) {
191 return false;
192 }
193 AuthTokenKey other = (AuthTokenKey)o;
194 if (!mAccount.equals(other.mAccount)) {
195 return false;
196 }
197 return (mAuthTokenType == null)
198 ? other.mAuthTokenType == null
199 : mAuthTokenType.equals(other.mAuthTokenType);
200 }
201
202 private int computeHashCode() {
203 int result = 17;
204 result = 31 * result + mAccount.hashCode();
205 result = 31 * result + ((mAuthTokenType == null) ? 0 : mAuthTokenType.hashCode());
206 return result;
207 }
208
209 public int hashCode() {
210 return mHashCode;
211 }
212 }
213
214 public AccountManagerService(Context context) {
215 mContext = context;
216
217 mOpenHelper = new DatabaseHelper(mContext);
218
219 mMessageThread = new HandlerThread("AccountManagerService");
220 mMessageThread.start();
221 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
222
223 mAuthenticatorCache = new AccountAuthenticatorCache(mContext);
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800224 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700225
Doug Zongker885cfc232009-10-21 16:52:44 -0700226 mSimWatcher = new SimWatcher(mContext);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700227 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800228
229 validateAccounts();
230 }
231
232 private void validateAccounts() {
233 boolean accountDeleted = false;
234 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
235 Cursor cursor = db.query(TABLE_ACCOUNTS,
236 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
237 null, null, null, null, null);
238 try {
239 while (cursor.moveToNext()) {
240 final long accountId = cursor.getLong(0);
241 final String accountType = cursor.getString(1);
242 final String accountName = cursor.getString(2);
243 if (mAuthenticatorCache.getServiceInfo(AuthenticatorDescription.newKey(accountType))
244 == null) {
245 Log.d(TAG, "deleting account " + accountName + " because type "
246 + accountType + " no longer has a registered authenticator");
247 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
248 accountDeleted = true;
249 }
250 }
251 } finally {
252 cursor.close();
253 if (accountDeleted) {
254 sendAccountsChangedBroadcast();
255 }
256 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700257 }
258
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800259 public void onServiceChanged(AuthenticatorDescription desc, boolean removed) {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700260 boolean accountDeleted = false;
261 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
262 Cursor cursor = db.query(TABLE_ACCOUNTS,
263 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800264 ACCOUNTS_TYPE + "=?", new String[]{desc.type}, null, null, null);
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700265 try {
266 while (cursor.moveToNext()) {
267 final long accountId = cursor.getLong(0);
268 final String accountType = cursor.getString(1);
269 final String accountName = cursor.getString(2);
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800270 Log.d(TAG, "deleting account " + accountName + " because type "
271 + accountType + " no longer has a registered authenticator");
272 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
273 accountDeleted = true;
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700274 }
275 } finally {
276 cursor.close();
277 if (accountDeleted) {
278 sendAccountsChangedBroadcast();
279 }
280 }
Fred Quintana60307342009-03-24 22:48:12 -0700281 }
282
Fred Quintanaa698f422009-04-08 19:14:54 -0700283 public String getPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700284 checkAuthenticateAccountsPermission(account);
285
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700286 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700287 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700288 return readPasswordFromDatabase(account);
289 } finally {
290 restoreCallingIdentity(identityToken);
291 }
292 }
293
294 private String readPasswordFromDatabase(Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700295 if (account == null) {
296 return null;
297 }
298
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700299 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
300 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
301 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
302 new String[]{account.name, account.type}, null, null, null);
303 try {
304 if (cursor.moveToNext()) {
305 return cursor.getString(0);
306 }
307 return null;
308 } finally {
309 cursor.close();
310 }
311 }
312
313 public String getUserData(Account account, String key) {
314 checkAuthenticateAccountsPermission(account);
315 long identityToken = clearCallingIdentity();
316 try {
317 return readUserDataFromDatabase(account, key);
318 } finally {
319 restoreCallingIdentity(identityToken);
320 }
321 }
322
323 private String readUserDataFromDatabase(Account account, String key) {
Fred Quintana31957f12009-10-21 13:43:10 -0700324 if (account == null) {
325 return null;
326 }
327
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700328 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700329 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_VALUE},
330 EXTRAS_ACCOUNTS_ID
331 + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
332 + EXTRAS_KEY + "=?",
333 new String[]{account.name, account.type, key}, null, null, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700334 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700335 if (cursor.moveToNext()) {
336 return cursor.getString(0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700337 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700338 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700339 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700340 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700341 }
342 }
343
Fred Quintana97889762009-06-15 12:29:24 -0700344 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700345 long identityToken = clearCallingIdentity();
346 try {
Fred Quintana97889762009-06-15 12:29:24 -0700347 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
348 authenticatorCollection = mAuthenticatorCache.getAllServices();
349 AuthenticatorDescription[] types =
350 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700351 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700352 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700353 : authenticatorCollection) {
354 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700355 i++;
356 }
357 return types;
358 } finally {
359 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700360 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700361 }
362
Fred Quintanaa698f422009-04-08 19:14:54 -0700363 public Account[] getAccountsByType(String accountType) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700364 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700365
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700366 final String selection = accountType == null ? null : (ACCOUNTS_TYPE + "=?");
367 final String[] selectionArgs = accountType == null ? null : new String[]{accountType};
368 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_NAME_TYPE_PROJECTION,
369 selection, selectionArgs, null, null, null);
370 try {
371 int i = 0;
372 Account[] accounts = new Account[cursor.getCount()];
373 while (cursor.moveToNext()) {
374 accounts[i] = new Account(cursor.getString(1), cursor.getString(2));
375 i++;
Fred Quintana60307342009-03-24 22:48:12 -0700376 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700377 return accounts;
Fred Quintana60307342009-03-24 22:48:12 -0700378 } finally {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700379 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700380 }
381 }
382
Fred Quintanaa698f422009-04-08 19:14:54 -0700383 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700384 checkAuthenticateAccountsPermission(account);
385
Fred Quintana60307342009-03-24 22:48:12 -0700386 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700387 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700388 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700389 return insertAccountIntoDatabase(account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700390 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700391 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700392 }
393 }
394
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700395 private boolean insertAccountIntoDatabase(Account account, String password, Bundle extras) {
396 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
397 db.beginTransaction();
398 try {
Fred Quintana31957f12009-10-21 13:43:10 -0700399 if (account == null) {
400 return false;
401 }
Jim Miller50c05f32009-09-21 19:07:44 -0700402 boolean noBroadcast = false;
403 if (account.type.equals(GOOGLE_ACCOUNT_TYPE)) {
404 // Look for the 'nobroadcast' flag and remove it since we don't want it to persist
405 // in the db.
406 noBroadcast = extras.getBoolean(NO_BROADCAST_FLAG, false);
407 extras.remove(NO_BROADCAST_FLAG);
408 }
409
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700410 long numMatches = DatabaseUtils.longForQuery(db,
411 "select count(*) from " + TABLE_ACCOUNTS
412 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
413 new String[]{account.name, account.type});
414 if (numMatches > 0) {
415 return false;
416 }
417 ContentValues values = new ContentValues();
418 values.put(ACCOUNTS_NAME, account.name);
419 values.put(ACCOUNTS_TYPE, account.type);
420 values.put(ACCOUNTS_PASSWORD, password);
421 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
422 if (accountId < 0) {
423 return false;
424 }
425 if (extras != null) {
426 for (String key : extras.keySet()) {
427 final String value = extras.getString(key);
428 if (insertExtra(db, accountId, key, value) < 0) {
429 return false;
430 }
431 }
432 }
433 db.setTransactionSuccessful();
Jim Miller50c05f32009-09-21 19:07:44 -0700434 if (!noBroadcast) {
435 sendAccountsChangedBroadcast();
436 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700437 return true;
438 } finally {
439 db.endTransaction();
440 }
441 }
442
Fred Quintana60307342009-03-24 22:48:12 -0700443 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
444 ContentValues values = new ContentValues();
445 values.put(EXTRAS_KEY, key);
446 values.put(EXTRAS_ACCOUNTS_ID, accountId);
447 values.put(EXTRAS_VALUE, value);
448 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
449 }
450
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700451 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700452 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700453 long identityToken = clearCallingIdentity();
454 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700455 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700456 } finally {
457 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700458 }
Fred Quintana60307342009-03-24 22:48:12 -0700459 }
460
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700461 private class RemoveAccountSession extends Session {
462 final Account mAccount;
463 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
464 super(response, account.type, false /* expectActivityLaunch */);
465 mAccount = account;
466 }
467
468 protected String toDebugString(long now) {
469 return super.toDebugString(now) + ", removeAccount"
470 + ", account " + mAccount;
471 }
472
473 public void run() throws RemoteException {
474 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
475 }
476
477 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700478 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
479 && !result.containsKey(AccountManager.KEY_INTENT)) {
480 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700481 if (removalAllowed) {
482 removeAccount(mAccount);
483 }
484 IAccountManagerResponse response = getResponseAndClose();
485 if (response != null) {
486 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700487 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700488 try {
489 response.onResult(result2);
490 } catch (RemoteException e) {
491 // ignore
492 }
493 }
494 }
495 super.onResult(result);
496 }
497 }
498
499 private void removeAccount(Account account) {
500 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
501 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
502 new String[]{account.name, account.type});
503 sendAccountsChangedBroadcast();
504 }
505
Fred Quintanaa698f422009-04-08 19:14:54 -0700506 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700507 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700508 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700509 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700510 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
511 db.beginTransaction();
512 try {
513 invalidateAuthToken(db, accountType, authToken);
514 db.setTransactionSuccessful();
515 } finally {
516 db.endTransaction();
517 }
Fred Quintana60307342009-03-24 22:48:12 -0700518 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700519 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700520 }
521 }
522
523 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700524 if (authToken == null || accountType == null) {
525 return;
526 }
Fred Quintana33269202009-04-20 16:05:10 -0700527 Cursor cursor = db.rawQuery(
528 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
529 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
530 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
531 + " FROM " + TABLE_ACCOUNTS
532 + " JOIN " + TABLE_AUTHTOKENS
533 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
534 + " = " + AUTHTOKENS_ACCOUNTS_ID
535 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
536 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
537 new String[]{authToken, accountType});
538 try {
539 while (cursor.moveToNext()) {
540 long authTokenId = cursor.getLong(0);
541 String accountName = cursor.getString(1);
542 String authTokenType = cursor.getString(2);
543 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700544 }
Fred Quintana33269202009-04-20 16:05:10 -0700545 } finally {
546 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700547 }
548 }
549
550 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700551 if (account == null || type == null) {
552 return false;
553 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700554 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700555 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
556 db.beginTransaction();
557 try {
Fred Quintana33269202009-04-20 16:05:10 -0700558 long accountId = getAccountId(db, account);
559 if (accountId < 0) {
560 return false;
561 }
562 db.delete(TABLE_AUTHTOKENS,
563 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
564 new String[]{type});
565 ContentValues values = new ContentValues();
566 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
567 values.put(AUTHTOKENS_TYPE, type);
568 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
569 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700570 db.setTransactionSuccessful();
571 return true;
572 }
573 return false;
574 } finally {
575 db.endTransaction();
576 }
577 }
578
Fred Quintana60307342009-03-24 22:48:12 -0700579 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
Fred Quintana31957f12009-10-21 13:43:10 -0700580 if (account == null || authTokenType == null) {
581 return null;
582 }
Fred Quintana60307342009-03-24 22:48:12 -0700583 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700584 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
585 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
586 + AUTHTOKENS_TYPE + "=?",
587 new String[]{account.name, account.type, authTokenType},
588 null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700589 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700590 if (cursor.moveToNext()) {
591 return cursor.getString(0);
Fred Quintana60307342009-03-24 22:48:12 -0700592 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700593 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700594 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700595 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700596 }
597 }
598
Fred Quintanaa698f422009-04-08 19:14:54 -0700599 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700600 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700601 long identityToken = clearCallingIdentity();
602 try {
Fred Quintana33269202009-04-20 16:05:10 -0700603 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700604 } finally {
605 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700606 }
Fred Quintana60307342009-03-24 22:48:12 -0700607 }
608
Fred Quintanaa698f422009-04-08 19:14:54 -0700609 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700610 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700611 long identityToken = clearCallingIdentity();
612 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700613 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700614 } finally {
615 restoreCallingIdentity(identityToken);
616 }
Fred Quintana60307342009-03-24 22:48:12 -0700617 }
618
Fred Quintanaa698f422009-04-08 19:14:54 -0700619 public void setPassword(Account account, String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700620 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700621 long identityToken = clearCallingIdentity();
622 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700623 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700624 } finally {
625 restoreCallingIdentity(identityToken);
626 }
Fred Quintana60307342009-03-24 22:48:12 -0700627 }
628
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700629 private void setPasswordInDB(Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700630 if (account == null) {
631 return;
632 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700633 ContentValues values = new ContentValues();
634 values.put(ACCOUNTS_PASSWORD, password);
635 mOpenHelper.getWritableDatabase().update(TABLE_ACCOUNTS, values,
636 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
637 new String[]{account.name, account.type});
638 sendAccountsChangedBroadcast();
639 }
640
Fred Quintana33269202009-04-20 16:05:10 -0700641 private void sendAccountsChangedBroadcast() {
642 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
643 }
644
Fred Quintanaa698f422009-04-08 19:14:54 -0700645 public void clearPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700646 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700647 long identityToken = clearCallingIdentity();
648 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700649 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700650 } finally {
651 restoreCallingIdentity(identityToken);
652 }
Fred Quintana60307342009-03-24 22:48:12 -0700653 }
654
Fred Quintanaa698f422009-04-08 19:14:54 -0700655 public void setUserData(Account account, String key, String value) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700656 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700657 long identityToken = clearCallingIdentity();
Fred Quintana31957f12009-10-21 13:43:10 -0700658 if (account == null) {
659 return;
660 }
Jim Miller50c05f32009-09-21 19:07:44 -0700661 if (account.type.equals(GOOGLE_ACCOUNT_TYPE) && key.equals("broadcast")) {
662 sendAccountsChangedBroadcast();
663 return;
664 }
Fred Quintana60307342009-03-24 22:48:12 -0700665 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700666 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700667 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700668 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700669 }
670 }
671
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700672 private void writeUserdataIntoDatabase(Account account, String key, String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700673 if (account == null || key == null) {
674 return;
675 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700676 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
677 db.beginTransaction();
678 try {
679 long accountId = getAccountId(db, account);
680 if (accountId < 0) {
681 return;
682 }
683 long extrasId = getExtrasId(db, accountId, key);
684 if (extrasId < 0 ) {
685 extrasId = insertExtra(db, accountId, key, value);
686 if (extrasId < 0) {
687 return;
688 }
689 } else {
690 ContentValues values = new ContentValues();
691 values.put(EXTRAS_VALUE, value);
692 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
693 return;
694 }
695
696 }
697 db.setTransactionSuccessful();
698 } finally {
699 db.endTransaction();
700 }
701 }
702
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700703 private void onResult(IAccountManagerResponse response, Bundle result) {
704 try {
705 response.onResult(result);
706 } catch (RemoteException e) {
707 // if the caller is dead then there is no one to care about remote
708 // exceptions
709 if (Log.isLoggable(TAG, Log.VERBOSE)) {
710 Log.v(TAG, "failure while notifying response", e);
711 }
712 }
713 }
714
Fred Quintanaa698f422009-04-08 19:14:54 -0700715 public void getAuthToken(IAccountManagerResponse response, final Account account,
716 final String authTokenType, final boolean notifyOnAuthFailure,
717 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700718 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
719 final int callerUid = Binder.getCallingUid();
720 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
721
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700722 long identityToken = clearCallingIdentity();
723 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700724 // if the caller has permission, do the peek. otherwise go the more expensive
725 // route of starting a Session
726 if (permissionGranted) {
727 String authToken = readAuthTokenFromDatabase(account, authTokenType);
728 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700729 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700730 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
731 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
732 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700733 onResult(response, result);
734 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700735 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700736 }
737
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700738 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700739 protected String toDebugString(long now) {
740 if (loginOptions != null) loginOptions.keySet();
741 return super.toDebugString(now) + ", getAuthToken"
742 + ", " + account
743 + ", authTokenType " + authTokenType
744 + ", loginOptions " + loginOptions
745 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
746 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700747
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700748 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700749 // If the caller doesn't have permission then create and return the
750 // "grant permission" intent instead of the "getAuthToken" intent.
751 if (!permissionGranted) {
752 mAuthenticator.getAuthTokenLabel(this, authTokenType);
753 } else {
754 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
755 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700756 }
757
758 public void onResult(Bundle result) {
759 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700760 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700761 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
762 new AccountAuthenticatorResponse(this),
763 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700764 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700765 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700766 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700767 onResult(bundle);
768 return;
769 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700770 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700771 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700772 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
773 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700774 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700775 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700776 "the type and name should not be empty");
777 return;
778 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700779 saveAuthTokenToDatabase(new Account(name, type),
780 authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700781 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700782
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700783 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700784 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700785 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700786 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700787 intent);
788 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700789 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700790 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700791 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700792 }.bind();
793 } finally {
794 restoreCallingIdentity(identityToken);
795 }
Fred Quintana60307342009-03-24 22:48:12 -0700796 }
797
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700798 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
799 int uid = intent.getIntExtra(
800 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
801 String authTokenType = intent.getStringExtra(
802 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
803 String authTokenLabel = intent.getStringExtra(
804 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
805
806 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
807 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700808 final String titleAndSubtitle =
809 mContext.getString(R.string.permission_request_notification_with_subtitle,
810 account.name);
811 final int index = titleAndSubtitle.indexOf('\n');
812 final String title = titleAndSubtitle.substring(0, index);
813 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700814 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700815 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700816 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
817 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
818 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
819 }
820
821 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
822 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
823 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
824 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700825 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700826 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700827 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700828 }
829
830 final Context authContext;
831 try {
832 authContext = mContext.createPackageContext(
833 serviceInfo.type.packageName, 0);
834 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700835 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700836 }
837
838 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
839 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
840 intent.addCategory(
841 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
842 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
843 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
844 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
845 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
846 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
847 authContext.getString(serviceInfo.type.labelId));
848 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
849 mContext.getPackageManager().getPackagesForUid(uid));
850 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
851 return intent;
852 }
853
854 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
855 int uid) {
856 Integer id;
857 synchronized(mCredentialsPermissionNotificationIds) {
858 final Pair<Pair<Account, String>, Integer> key =
859 new Pair<Pair<Account, String>, Integer>(
860 new Pair<Account, String>(account, authTokenType), uid);
861 id = mCredentialsPermissionNotificationIds.get(key);
862 if (id == null) {
863 id = mNotificationIds.incrementAndGet();
864 mCredentialsPermissionNotificationIds.put(key, id);
865 }
866 }
867 return id;
868 }
869
870 private Integer getSigninRequiredNotificationId(Account account) {
871 Integer id;
872 synchronized(mSigninRequiredNotificationIds) {
873 id = mSigninRequiredNotificationIds.get(account);
874 if (id == null) {
875 id = mNotificationIds.incrementAndGet();
876 mSigninRequiredNotificationIds.put(account, id);
877 }
878 }
879 return id;
880 }
881
Fred Quintanaa698f422009-04-08 19:14:54 -0700882
Fred Quintana33269202009-04-20 16:05:10 -0700883 public void addAcount(final IAccountManagerResponse response, final String accountType,
884 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700885 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700886 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700887 long identityToken = clearCallingIdentity();
888 try {
889 new Session(response, accountType, expectActivityLaunch) {
890 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -0700891 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -0700892 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700893 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700894
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700895 protected String toDebugString(long now) {
896 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -0700897 + ", accountType " + accountType
898 + ", requiredFeatures "
899 + (requiredFeatures != null
900 ? TextUtils.join(",", requiredFeatures)
901 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700902 }
903 }.bind();
904 } finally {
905 restoreCallingIdentity(identityToken);
906 }
Fred Quintana60307342009-03-24 22:48:12 -0700907 }
908
Fred Quintanaa698f422009-04-08 19:14:54 -0700909 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700910 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700911 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700912 long identityToken = clearCallingIdentity();
913 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700914 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700915 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700916 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700917 }
918 protected String toDebugString(long now) {
919 return super.toDebugString(now) + ", confirmCredentials"
920 + ", " + account;
921 }
922 }.bind();
923 } finally {
924 restoreCallingIdentity(identityToken);
925 }
Fred Quintana60307342009-03-24 22:48:12 -0700926 }
927
Fred Quintanaa698f422009-04-08 19:14:54 -0700928 public void updateCredentials(IAccountManagerResponse response, final Account account,
929 final String authTokenType, final boolean expectActivityLaunch,
930 final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700931 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700932 long identityToken = clearCallingIdentity();
933 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700934 new Session(response, account.type, expectActivityLaunch) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700935 public void run() throws RemoteException {
936 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
937 }
938 protected String toDebugString(long now) {
939 if (loginOptions != null) loginOptions.keySet();
940 return super.toDebugString(now) + ", updateCredentials"
941 + ", " + account
942 + ", authTokenType " + authTokenType
943 + ", loginOptions " + loginOptions;
944 }
945 }.bind();
946 } finally {
947 restoreCallingIdentity(identityToken);
948 }
Fred Quintana60307342009-03-24 22:48:12 -0700949 }
950
Fred Quintanaa698f422009-04-08 19:14:54 -0700951 public void editProperties(IAccountManagerResponse response, final String accountType,
952 final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700953 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700954 long identityToken = clearCallingIdentity();
955 try {
956 new Session(response, accountType, expectActivityLaunch) {
957 public void run() throws RemoteException {
958 mAuthenticator.editProperties(this, mAccountType);
959 }
960 protected String toDebugString(long now) {
961 return super.toDebugString(now) + ", editProperties"
962 + ", accountType " + accountType;
963 }
964 }.bind();
965 } finally {
966 restoreCallingIdentity(identityToken);
967 }
Fred Quintana60307342009-03-24 22:48:12 -0700968 }
969
Fred Quintana33269202009-04-20 16:05:10 -0700970 private class GetAccountsByTypeAndFeatureSession extends Session {
971 private final String[] mFeatures;
972 private volatile Account[] mAccountsOfType = null;
973 private volatile ArrayList<Account> mAccountsWithFeatures = null;
974 private volatile int mCurrentAccount = 0;
975
976 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
977 String type, String[] features) {
978 super(response, type, false /* expectActivityLaunch */);
979 mFeatures = features;
980 }
981
982 public void run() throws RemoteException {
983 mAccountsOfType = getAccountsByType(mAccountType);
984 // check whether each account matches the requested features
985 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
986 mCurrentAccount = 0;
987
988 checkAccount();
989 }
990
991 public void checkAccount() {
992 if (mCurrentAccount >= mAccountsOfType.length) {
993 sendResult();
994 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700995 }
Fred Quintana33269202009-04-20 16:05:10 -0700996
997 try {
998 mAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
999 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001000 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001001 }
1002 }
1003
1004 public void onResult(Bundle result) {
1005 mNumResults++;
1006 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001007 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001008 return;
1009 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001010 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001011 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1012 }
1013 mCurrentAccount++;
1014 checkAccount();
1015 }
1016
1017 public void sendResult() {
1018 IAccountManagerResponse response = getResponseAndClose();
1019 if (response != null) {
1020 try {
1021 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1022 for (int i = 0; i < accounts.length; i++) {
1023 accounts[i] = mAccountsWithFeatures.get(i);
1024 }
1025 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001026 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001027 response.onResult(result);
1028 } catch (RemoteException e) {
1029 // if the caller is dead then there is no one to care about remote exceptions
1030 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1031 Log.v(TAG, "failure while notifying response", e);
1032 }
1033 }
1034 }
1035 }
1036
1037
1038 protected String toDebugString(long now) {
1039 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1040 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1041 }
1042 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001043
1044 public Account[] getAccounts(String type) {
1045 checkReadAccountsPermission();
1046 long identityToken = clearCallingIdentity();
1047 try {
1048 return getAccountsByType(type);
1049 } finally {
1050 restoreCallingIdentity(identityToken);
1051 }
1052 }
1053
1054 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001055 String type, String[] features) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001056 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001057 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -07001058 if (response != null) {
1059 try {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001060 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "type is null");
Fred Quintana33269202009-04-20 16:05:10 -07001061 } catch (RemoteException e) {
1062 // ignore this
1063 }
1064 }
1065 return;
1066 }
1067 long identityToken = clearCallingIdentity();
1068 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001069 if (features == null || features.length == 0) {
1070 getAccountsByType(type);
1071 return;
1072 }
Fred Quintana33269202009-04-20 16:05:10 -07001073 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1074 } finally {
1075 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001076 }
1077 }
1078
Fred Quintana60307342009-03-24 22:48:12 -07001079 private long getAccountId(SQLiteDatabase db, Account account) {
1080 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001081 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001082 try {
1083 if (cursor.moveToNext()) {
1084 return cursor.getLong(0);
1085 }
1086 return -1;
1087 } finally {
1088 cursor.close();
1089 }
1090 }
1091
1092 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1093 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1094 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1095 new String[]{key}, null, null, null);
1096 try {
1097 if (cursor.moveToNext()) {
1098 return cursor.getLong(0);
1099 }
1100 return -1;
1101 } finally {
1102 cursor.close();
1103 }
1104 }
1105
Fred Quintanaa698f422009-04-08 19:14:54 -07001106 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001107 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001108 IAccountManagerResponse mResponse;
1109 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001110 final boolean mExpectActivityLaunch;
1111 final long mCreationTime;
1112
Fred Quintana33269202009-04-20 16:05:10 -07001113 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001114 private int mNumRequestContinued = 0;
1115 private int mNumErrors = 0;
1116
Fred Quintana60307342009-03-24 22:48:12 -07001117
1118 IAccountAuthenticator mAuthenticator = null;
1119
Fred Quintanaa698f422009-04-08 19:14:54 -07001120 public Session(IAccountManagerResponse response, String accountType,
1121 boolean expectActivityLaunch) {
Fred Quintana60307342009-03-24 22:48:12 -07001122 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001123 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001124 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana60307342009-03-24 22:48:12 -07001125 mResponse = response;
1126 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001127 mExpectActivityLaunch = expectActivityLaunch;
1128 mCreationTime = SystemClock.elapsedRealtime();
1129 synchronized (mSessions) {
1130 mSessions.put(toString(), this);
1131 }
1132 try {
1133 response.asBinder().linkToDeath(this, 0 /* flags */);
1134 } catch (RemoteException e) {
1135 mResponse = null;
1136 binderDied();
1137 }
Fred Quintana60307342009-03-24 22:48:12 -07001138 }
1139
Fred Quintanaa698f422009-04-08 19:14:54 -07001140 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001141 if (mResponse == null) {
1142 // this session has already been closed
1143 return null;
1144 }
Fred Quintana60307342009-03-24 22:48:12 -07001145 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001146 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001147 return response;
1148 }
1149
Fred Quintanaa698f422009-04-08 19:14:54 -07001150 private void close() {
1151 synchronized (mSessions) {
1152 if (mSessions.remove(toString()) == null) {
1153 // the session was already closed, so bail out now
1154 return;
1155 }
1156 }
1157 if (mResponse != null) {
1158 // stop listening for response deaths
1159 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1160
1161 // clear this so that we don't accidentally send any further results
1162 mResponse = null;
1163 }
1164 cancelTimeout();
1165 unbind();
1166 }
1167
1168 public void binderDied() {
1169 mResponse = null;
1170 close();
1171 }
1172
1173 protected String toDebugString() {
1174 return toDebugString(SystemClock.elapsedRealtime());
1175 }
1176
1177 protected String toDebugString(long now) {
1178 return "Session: expectLaunch " + mExpectActivityLaunch
1179 + ", connected " + (mAuthenticator != null)
1180 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1181 + "/" + mNumErrors + ")"
1182 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1183 }
1184
Fred Quintana60307342009-03-24 22:48:12 -07001185 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001186 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1187 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1188 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001189 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001190 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001191 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001192 }
1193 }
1194
1195 private void unbind() {
1196 if (mAuthenticator != null) {
1197 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001198 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001199 }
1200 }
1201
1202 public void scheduleTimeout() {
1203 mMessageHandler.sendMessageDelayed(
1204 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1205 }
1206
1207 public void cancelTimeout() {
1208 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1209 }
1210
Fred Quintanab839afc2009-10-14 15:57:28 -07001211 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001212 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001213 try {
1214 run();
1215 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001216 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001217 "remote exception");
1218 }
Fred Quintana60307342009-03-24 22:48:12 -07001219 }
1220
Fred Quintanab839afc2009-10-14 15:57:28 -07001221 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001222 mAuthenticator = null;
1223 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001224 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001225 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001226 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001227 }
1228 }
1229
Fred Quintanab839afc2009-10-14 15:57:28 -07001230 public abstract void run() throws RemoteException;
1231
Fred Quintana60307342009-03-24 22:48:12 -07001232 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001233 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001234 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001235 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001236 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001237 }
1238 }
1239
Fred Quintanaa698f422009-04-08 19:14:54 -07001240 public void onResult(Bundle result) {
1241 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001242 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1243 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1244 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001245 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1246 Account account = new Account(accountName, accountType);
1247 cancelNotification(getSigninRequiredNotificationId(account));
1248 }
Fred Quintana60307342009-03-24 22:48:12 -07001249 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001250 IAccountManagerResponse response;
1251 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001252 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001253 response = mResponse;
1254 } else {
1255 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001256 }
Fred Quintana60307342009-03-24 22:48:12 -07001257 if (response != null) {
1258 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001259 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001260 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001261 "null bundle returned");
1262 } else {
1263 response.onResult(result);
1264 }
Fred Quintana60307342009-03-24 22:48:12 -07001265 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001266 // if the caller is dead then there is no one to care about remote exceptions
1267 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1268 Log.v(TAG, "failure while notifying response", e);
1269 }
Fred Quintana60307342009-03-24 22:48:12 -07001270 }
1271 }
1272 }
Fred Quintana60307342009-03-24 22:48:12 -07001273
Fred Quintanaa698f422009-04-08 19:14:54 -07001274 public void onRequestContinued() {
1275 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001276 }
1277
1278 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001279 mNumErrors++;
1280 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1281 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001282 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001283 IAccountManagerResponse response = getResponseAndClose();
1284 if (response != null) {
1285 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1286 Log.v(TAG, "Session.onError: responding");
1287 }
1288 try {
1289 response.onError(errorCode, errorMessage);
1290 } catch (RemoteException e) {
1291 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1292 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1293 }
1294 }
1295 } else {
1296 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1297 Log.v(TAG, "Session.onError: already closed");
1298 }
Fred Quintana60307342009-03-24 22:48:12 -07001299 }
1300 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001301
1302 /**
1303 * find the component name for the authenticator and initiate a bind
1304 * if no authenticator or the bind fails then return false, otherwise return true
1305 */
1306 private boolean bindToAuthenticator(String authenticatorType) {
1307 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1308 mAuthenticatorCache.getServiceInfo(
1309 AuthenticatorDescription.newKey(authenticatorType));
1310 if (authenticatorInfo == null) {
1311 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1312 Log.v(TAG, "there is no authenticator for " + authenticatorType
1313 + ", bailing out");
1314 }
1315 return false;
1316 }
1317
1318 Intent intent = new Intent();
1319 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1320 intent.setComponent(authenticatorInfo.componentName);
1321 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1322 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1323 }
1324 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1325 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1326 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1327 }
1328 return false;
1329 }
1330
1331
1332 return true;
1333 }
Fred Quintana60307342009-03-24 22:48:12 -07001334 }
1335
1336 private class MessageHandler extends Handler {
1337 MessageHandler(Looper looper) {
1338 super(looper);
1339 }
Costin Manolache3348f142009-09-29 18:58:36 -07001340
Fred Quintana60307342009-03-24 22:48:12 -07001341 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001342 switch (msg.what) {
1343 case MESSAGE_TIMED_OUT:
1344 Session session = (Session)msg.obj;
1345 session.onTimedOut();
1346 break;
1347
1348 default:
1349 throw new IllegalStateException("unhandled message: " + msg.what);
1350 }
1351 }
1352 }
1353
1354 private class DatabaseHelper extends SQLiteOpenHelper {
1355 public DatabaseHelper(Context context) {
1356 super(context, DATABASE_NAME, null, DATABASE_VERSION);
1357 }
1358
1359 @Override
1360 public void onCreate(SQLiteDatabase db) {
1361 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1362 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1363 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1364 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1365 + ACCOUNTS_PASSWORD + " TEXT, "
1366 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1367
1368 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1369 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1370 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1371 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1372 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1373 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1374
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001375 createGrantsTable(db);
1376
Fred Quintana60307342009-03-24 22:48:12 -07001377 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1378 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1379 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1380 + EXTRAS_KEY + " TEXT NOT NULL, "
1381 + EXTRAS_VALUE + " TEXT, "
1382 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1383
1384 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1385 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1386 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001387
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001388 createAccountsDeletionTrigger(db);
1389 }
1390
1391 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001392 db.execSQL(""
1393 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1394 + " BEGIN"
1395 + " DELETE FROM " + TABLE_AUTHTOKENS
1396 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1397 + " DELETE FROM " + TABLE_EXTRAS
1398 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001399 + " DELETE FROM " + TABLE_GRANTS
1400 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001401 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001402 }
1403
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001404 private void createGrantsTable(SQLiteDatabase db) {
1405 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1406 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1407 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1408 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1409 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1410 + "," + GRANTS_GRANTEE_UID + "))");
1411 }
1412
Fred Quintana60307342009-03-24 22:48:12 -07001413 @Override
1414 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001415 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001416
Fred Quintanaa698f422009-04-08 19:14:54 -07001417 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001418 // no longer need to do anything since the work is done
1419 // when upgrading from version 2
1420 oldVersion++;
1421 }
1422
1423 if (oldVersion == 2) {
1424 createGrantsTable(db);
1425 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1426 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001427 oldVersion++;
1428 }
Costin Manolache3348f142009-09-29 18:58:36 -07001429
1430 if (oldVersion == 3) {
1431 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1432 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1433 oldVersion++;
1434 }
Fred Quintana60307342009-03-24 22:48:12 -07001435 }
1436
1437 @Override
1438 public void onOpen(SQLiteDatabase db) {
1439 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1440 }
1441 }
1442
1443 private void setMetaValue(String key, String value) {
1444 ContentValues values = new ContentValues();
1445 values.put(META_KEY, key);
1446 values.put(META_VALUE, value);
1447 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1448 }
1449
1450 private String getMetaValue(String key) {
1451 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1452 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1453 try {
1454 if (c.moveToNext()) {
1455 return c.getString(0);
1456 }
1457 return null;
1458 } finally {
1459 c.close();
1460 }
1461 }
1462
1463 private class SimWatcher extends BroadcastReceiver {
1464 public SimWatcher(Context context) {
1465 // Re-scan the SIM card when the SIM state changes, and also if
1466 // the disk recovers from a full state (we may have failed to handle
1467 // things properly while the disk was full).
1468 final IntentFilter filter = new IntentFilter();
1469 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1470 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1471 context.registerReceiver(this, filter);
1472 }
Costin Manolache3348f142009-09-29 18:58:36 -07001473
Fred Quintana60307342009-03-24 22:48:12 -07001474 /**
1475 * Compare the IMSI to the one stored in the login service's
1476 * database. If they differ, erase all passwords and
1477 * authtokens (and store the new IMSI).
1478 */
1479 @Override
1480 public void onReceive(Context context, Intent intent) {
Doug Zongker885cfc232009-10-21 16:52:44 -07001481 // Check IMSI on every update; nothing happens if the IMSI
1482 // is missing or unchanged.
1483 TelephonyManager telephonyManager =
1484 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1485 if (telephonyManager == null) {
1486 Log.w(TAG, "failed to get TelephonyManager");
1487 return;
1488 }
1489 String imsi = telephonyManager.getSubscriberId();
1490
1491 // If the subscriber ID is an empty string, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001492 if (TextUtils.isEmpty(imsi)) return;
1493
Doug Zongker885cfc232009-10-21 16:52:44 -07001494 // If the current IMSI matches what's stored, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001495 String storedImsi = getMetaValue("imsi");
Fred Quintana60307342009-03-24 22:48:12 -07001496 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1497 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1498 }
Doug Zongker885cfc232009-10-21 16:52:44 -07001499 if (imsi.equals(storedImsi)) return;
1500
1501 // If a CDMA phone is unprovisioned, getSubscriberId()
1502 // will return a different value, but we *don't* erase the
1503 // passwords. We only erase them if it has a different
1504 // subscriber ID once it's provisioned.
1505 if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
1506 IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
1507 if (service == null) {
1508 Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
1509 return;
1510 }
1511 ITelephony telephony = ITelephony.Stub.asInterface(service);
1512 if (telephony == null) {
1513 Log.w(TAG, "failed to get ITelephony interface");
1514 return;
1515 }
1516 boolean needsProvisioning;
1517 try {
1518 needsProvisioning = telephony.getCdmaNeedsProvisioning();
1519 } catch (RemoteException e) {
1520 Log.w(TAG, "exception while checking provisioning", e);
1521 // default to NOT wiping out the passwords
1522 needsProvisioning = true;
1523 }
1524 if (needsProvisioning) {
1525 // if the phone needs re-provisioning, don't do anything.
1526 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1527 Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
1528 storedImsi);
1529 }
1530 return;
1531 }
1532 }
Fred Quintana60307342009-03-24 22:48:12 -07001533
jsh5b462472009-09-01 16:13:55 -07001534 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001535 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1536 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001537 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1538 db.beginTransaction();
1539 try {
1540 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1541 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001542 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001543 db.setTransactionSuccessful();
1544 } finally {
1545 db.endTransaction();
1546 }
1547 }
1548 setMetaValue("imsi", imsi);
1549 }
1550 }
1551
1552 public IBinder onBind(Intent intent) {
1553 return asBinder();
1554 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001555
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001556 /**
1557 * Searches array of arguments for the specified string
1558 * @param args array of argument strings
1559 * @param value value to search for
1560 * @return true if the value is contained in the array
1561 */
1562 private static boolean scanArgs(String[] args, String value) {
1563 if (args != null) {
1564 for (String arg : args) {
1565 if (value.equals(arg)) {
1566 return true;
1567 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001568 }
1569 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001570 return false;
1571 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001572
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001573 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1574 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001575
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001576 if (isCheckinRequest) {
1577 // This is a checkin request. *Only* upload the account types and the count of each.
1578 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1579
1580 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1581 null, null, ACCOUNTS_TYPE, null, null);
1582 try {
1583 while (cursor.moveToNext()) {
1584 // print type,count
1585 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1586 }
1587 } finally {
1588 if (cursor != null) {
1589 cursor.close();
1590 }
1591 }
1592 } else {
1593 synchronized (mSessions) {
1594 final long now = SystemClock.elapsedRealtime();
1595 fout.println("AccountManagerService: " + mSessions.size() + " sessions");
1596 for (Session session : mSessions.values()) {
1597 fout.println(" " + session.toDebugString(now));
1598 }
1599 }
1600
1601 fout.println();
1602 mAuthenticatorCache.dump(fd, fout, args);
1603 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001604 }
1605
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001606 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001607 long identityToken = clearCallingIdentity();
1608 try {
1609 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1610 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1611 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001612
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001613 if (intent.getComponent() != null &&
1614 GrantCredentialsPermissionActivity.class.getName().equals(
1615 intent.getComponent().getClassName())) {
1616 createNoCredentialsPermissionNotification(account, intent);
1617 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001618 final Integer notificationId = getSigninRequiredNotificationId(account);
1619 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001620 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1621 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001622 final String notificationTitleFormat =
1623 mContext.getText(R.string.notification_title).toString();
1624 n.setLatestEventInfo(mContext,
1625 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001626 message, PendingIntent.getActivity(
1627 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1628 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001629 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001630 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001631 } finally {
1632 restoreCallingIdentity(identityToken);
1633 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001634 }
1635
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001636 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001637 long identityToken = clearCallingIdentity();
1638 try {
1639 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001640 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001641 } finally {
1642 restoreCallingIdentity(identityToken);
1643 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001644 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001645
1646 private void checkBinderPermission(String permission) {
1647 final int uid = Binder.getCallingUid();
1648 if (mContext.checkCallingOrSelfPermission(permission) !=
1649 PackageManager.PERMISSION_GRANTED) {
1650 String msg = "caller uid " + uid + " lacks " + permission;
1651 Log.w(TAG, msg);
1652 throw new SecurityException(msg);
1653 }
1654 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1655 Log.v(TAG, "caller uid " + uid + " has " + permission);
1656 }
1657 }
1658
Fred Quintana7be59642009-08-24 18:29:25 -07001659 private boolean inSystemImage(int callerUid) {
1660 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1661 for (String name : packages) {
1662 try {
1663 PackageInfo packageInfo =
1664 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1665 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1666 return true;
1667 }
1668 } catch (PackageManager.NameNotFoundException e) {
1669 return false;
1670 }
1671 }
1672 return false;
1673 }
1674
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001675 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001676 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07001677 final boolean fromAuthenticator = account != null
1678 && hasAuthenticatorUid(account.type, callerUid);
1679 final boolean hasExplicitGrants = account != null
1680 && hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001681 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1682 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1683 + callerUid + ", account " + account
1684 + ": is authenticator? " + fromAuthenticator
1685 + ", has explicit permission? " + hasExplicitGrants);
1686 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001687 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001688 }
1689
Fred Quintana1a231912009-10-15 11:31:30 -07001690 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001691 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1692 mAuthenticatorCache.getAllServices()) {
1693 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001694 return (serviceInfo.uid == callingUid) ||
1695 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1696 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001697 }
1698 }
1699 return false;
1700 }
1701
1702 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1703 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1704 return true;
1705 }
1706 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1707 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001708 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001709 final boolean permissionGranted =
1710 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1711 if (!permissionGranted && isDebuggableMonkeyBuild) {
1712 // TODO: Skip this check when running automated tests. Replace this
1713 // with a more general solution.
1714 Log.w(TAG, "no credentials permission for usage of " + account + ", "
1715 + authTokenType + " by uid " + Binder.getCallingUid()
1716 + " but ignoring since this is a monkey build");
1717 return true;
1718 }
1719 return permissionGranted;
1720 }
1721
1722 private void checkCallingUidAgainstAuthenticator(Account account) {
1723 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07001724 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001725 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1726 Log.w(TAG, msg);
1727 throw new SecurityException(msg);
1728 }
1729 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1730 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1731 }
1732 }
1733
1734 private void checkAuthenticateAccountsPermission(Account account) {
1735 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1736 checkCallingUidAgainstAuthenticator(account);
1737 }
1738
1739 private void checkReadAccountsPermission() {
1740 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1741 }
1742
1743 private void checkManageAccountsPermission() {
1744 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1745 }
1746
1747 /**
1748 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1749 * <p>
1750 * Although this is public it can only be accessed via the AccountManagerService object
1751 * which is in the system. This means we don't need to protect it with permissions.
1752 * @hide
1753 */
1754 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001755 if (account == null || authTokenType == null) {
1756 return;
1757 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001758 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1759 db.beginTransaction();
1760 try {
1761 long accountId = getAccountId(db, account);
1762 if (accountId >= 0) {
1763 ContentValues values = new ContentValues();
1764 values.put(GRANTS_ACCOUNTS_ID, accountId);
1765 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1766 values.put(GRANTS_GRANTEE_UID, uid);
1767 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1768 db.setTransactionSuccessful();
1769 }
1770 } finally {
1771 db.endTransaction();
1772 }
1773 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1774 }
1775
1776 /**
1777 * Don't allow callers with the given uid permission to get credentials for
1778 * account/authTokenType.
1779 * <p>
1780 * Although this is public it can only be accessed via the AccountManagerService object
1781 * which is in the system. This means we don't need to protect it with permissions.
1782 * @hide
1783 */
1784 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001785 if (account == null || authTokenType == null) {
1786 return;
1787 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001788 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1789 db.beginTransaction();
1790 try {
1791 long accountId = getAccountId(db, account);
1792 if (accountId >= 0) {
1793 db.delete(TABLE_GRANTS,
1794 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1795 + GRANTS_GRANTEE_UID + "=?",
1796 new String[]{String.valueOf(accountId), authTokenType,
1797 String.valueOf(uid)});
1798 db.setTransactionSuccessful();
1799 }
1800 } finally {
1801 db.endTransaction();
1802 }
1803 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1804 }
Fred Quintana60307342009-03-24 22:48:12 -07001805}