blob: 6d0a26695d8e06a9d84dcc7fde758cb1661edc9e [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.accounts;
18
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
20import android.app.Notification;
21import android.app.NotificationManager;
22import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070023import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070024import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070025import android.content.ContentValues;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070029import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070030import android.content.pm.ApplicationInfo;
31import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070032import android.content.pm.PackageManager;
33import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070034import android.content.pm.RegisteredServicesCacheListener;
Fred Quintana60307342009-03-24 22:48:12 -070035import android.database.Cursor;
36import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070037import android.database.sqlite.SQLiteDatabase;
38import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070039import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070040import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080041import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070042import android.os.Handler;
43import android.os.HandlerThread;
44import android.os.IBinder;
45import android.os.Looper;
46import android.os.Message;
47import android.os.RemoteException;
Doug Zongker885cfc232009-10-21 16:52:44 -070048import android.os.ServiceManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070049import android.os.SystemClock;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070050import android.os.SystemProperties;
Fred Quintana60307342009-03-24 22:48:12 -070051import android.telephony.TelephonyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070052import android.text.TextUtils;
53import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070054import android.util.Pair;
Fred Quintana60307342009-03-24 22:48:12 -070055
Oscar Montemayora8529f62009-11-18 10:14:20 -080056import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070057import java.io.FileDescriptor;
58import java.io.PrintWriter;
59import java.util.ArrayList;
60import java.util.Collection;
Fred Quintanaa698f422009-04-08 19:14:54 -070061import java.util.LinkedHashMap;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070062import java.util.HashMap;
63import java.util.concurrent.atomic.AtomicInteger;
64import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070065
Fred Quintana26fc5eb2009-04-09 15:05:50 -070066import com.android.internal.R;
Doug Zongker885cfc232009-10-21 16:52:44 -070067import com.android.internal.telephony.ITelephony;
68import com.android.internal.telephony.TelephonyIntents;
Fred Quintana60307342009-03-24 22:48:12 -070069
70/**
71 * A system service that provides account, password, and authtoken management for all
72 * accounts on the device. Some of these calls are implemented with the help of the corresponding
73 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
74 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
75 * AccountManager accountManager =
76 * (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE)
Fred Quintana33269202009-04-20 16:05:10 -070077 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070078 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070079public class AccountManagerService
80 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080081 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Costin Manolache3348f142009-09-29 18:58:36 -070082 private static final String GOOGLE_ACCOUNT_TYPE = "com.google";
Jim Miller50c05f32009-09-21 19:07:44 -070083
84 private static final String NO_BROADCAST_FLAG = "nobroadcast";
85
Fred Quintana60307342009-03-24 22:48:12 -070086 private static final String TAG = "AccountManagerService";
87
88 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
89 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070090 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070091
92 private final Context mContext;
93
94 private HandlerThread mMessageThread;
95 private final MessageHandler mMessageHandler;
96
97 // Messages that can be sent on mHandler
98 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -070099
100 private final AccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700101 private final DatabaseHelper mOpenHelper;
102 private final SimWatcher mSimWatcher;
103
104 private static final String TABLE_ACCOUNTS = "accounts";
105 private static final String ACCOUNTS_ID = "_id";
106 private static final String ACCOUNTS_NAME = "name";
107 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700108 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700109 private static final String ACCOUNTS_PASSWORD = "password";
110
111 private static final String TABLE_AUTHTOKENS = "authtokens";
112 private static final String AUTHTOKENS_ID = "_id";
113 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
114 private static final String AUTHTOKENS_TYPE = "type";
115 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
116
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700117 private static final String TABLE_GRANTS = "grants";
118 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
119 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
120 private static final String GRANTS_GRANTEE_UID = "uid";
121
Fred Quintana60307342009-03-24 22:48:12 -0700122 private static final String TABLE_EXTRAS = "extras";
123 private static final String EXTRAS_ID = "_id";
124 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
125 private static final String EXTRAS_KEY = "key";
126 private static final String EXTRAS_VALUE = "value";
127
128 private static final String TABLE_META = "meta";
129 private static final String META_KEY = "key";
130 private static final String META_VALUE = "value";
131
132 private static final String[] ACCOUNT_NAME_TYPE_PROJECTION =
133 new String[]{ACCOUNTS_ID, ACCOUNTS_NAME, ACCOUNTS_TYPE};
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700134 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
135 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700136 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700137
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700138 private static final String COUNT_OF_MATCHING_GRANTS = ""
139 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
140 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
141 + " AND " + GRANTS_GRANTEE_UID + "=?"
142 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
143 + " AND " + ACCOUNTS_NAME + "=?"
144 + " AND " + ACCOUNTS_TYPE + "=?";
145
Fred Quintanaa698f422009-04-08 19:14:54 -0700146 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700147 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
148
149 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
150 mCredentialsPermissionNotificationIds =
151 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
152 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
153 new HashMap<Account, Integer>();
154 private static AtomicReference<AccountManagerService> sThis =
155 new AtomicReference<AccountManagerService>();
156
157 private static final boolean isDebuggableMonkeyBuild =
Ying Wang42c98ad2010-01-04 18:51:25 -0800158 SystemProperties.getBoolean("ro.monkey", false);
Fred Quintana31957f12009-10-21 13:43:10 -0700159 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700160
161 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700162 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700163 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
164 }
165
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700166 /**
167 * This should only be called by system code. One should only call this after the service
168 * has started.
169 * @return a reference to the AccountManagerService instance
170 * @hide
171 */
172 public static AccountManagerService getSingleton() {
173 return sThis.get();
174 }
Fred Quintana60307342009-03-24 22:48:12 -0700175
176 public class AuthTokenKey {
177 public final Account mAccount;
178 public final String mAuthTokenType;
179 private final int mHashCode;
180
181 public AuthTokenKey(Account account, String authTokenType) {
182 mAccount = account;
183 mAuthTokenType = authTokenType;
184 mHashCode = computeHashCode();
185 }
186
187 public boolean equals(Object o) {
188 if (o == this) {
189 return true;
190 }
191 if (!(o instanceof AuthTokenKey)) {
192 return false;
193 }
194 AuthTokenKey other = (AuthTokenKey)o;
195 if (!mAccount.equals(other.mAccount)) {
196 return false;
197 }
198 return (mAuthTokenType == null)
199 ? other.mAuthTokenType == null
200 : mAuthTokenType.equals(other.mAuthTokenType);
201 }
202
203 private int computeHashCode() {
204 int result = 17;
205 result = 31 * result + mAccount.hashCode();
206 result = 31 * result + ((mAuthTokenType == null) ? 0 : mAuthTokenType.hashCode());
207 return result;
208 }
209
210 public int hashCode() {
211 return mHashCode;
212 }
213 }
214
215 public AccountManagerService(Context context) {
216 mContext = context;
217
218 mOpenHelper = new DatabaseHelper(mContext);
219
220 mMessageThread = new HandlerThread("AccountManagerService");
221 mMessageThread.start();
222 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
223
224 mAuthenticatorCache = new AccountAuthenticatorCache(mContext);
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800225 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700226
Doug Zongker885cfc232009-10-21 16:52:44 -0700227 mSimWatcher = new SimWatcher(mContext);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700228 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800229
230 validateAccounts();
231 }
232
233 private void validateAccounts() {
234 boolean accountDeleted = false;
235 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
236 Cursor cursor = db.query(TABLE_ACCOUNTS,
237 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
238 null, null, null, null, null);
239 try {
240 while (cursor.moveToNext()) {
241 final long accountId = cursor.getLong(0);
242 final String accountType = cursor.getString(1);
243 final String accountName = cursor.getString(2);
244 if (mAuthenticatorCache.getServiceInfo(AuthenticatorDescription.newKey(accountType))
245 == null) {
246 Log.d(TAG, "deleting account " + accountName + " because type "
247 + accountType + " no longer has a registered authenticator");
248 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
249 accountDeleted = true;
250 }
251 }
252 } finally {
253 cursor.close();
254 if (accountDeleted) {
255 sendAccountsChangedBroadcast();
256 }
257 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700258 }
259
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800260 public void onServiceChanged(AuthenticatorDescription desc, boolean removed) {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700261 boolean accountDeleted = false;
262 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
263 Cursor cursor = db.query(TABLE_ACCOUNTS,
264 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800265 ACCOUNTS_TYPE + "=?", new String[]{desc.type}, null, null, null);
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700266 try {
267 while (cursor.moveToNext()) {
268 final long accountId = cursor.getLong(0);
269 final String accountType = cursor.getString(1);
270 final String accountName = cursor.getString(2);
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800271 Log.d(TAG, "deleting account " + accountName + " because type "
272 + accountType + " no longer has a registered authenticator");
273 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
274 accountDeleted = true;
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700275 }
276 } finally {
277 cursor.close();
278 if (accountDeleted) {
279 sendAccountsChangedBroadcast();
280 }
281 }
Fred Quintana60307342009-03-24 22:48:12 -0700282 }
283
Fred Quintanaa698f422009-04-08 19:14:54 -0700284 public String getPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700285 checkAuthenticateAccountsPermission(account);
286
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700287 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700288 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700289 return readPasswordFromDatabase(account);
290 } finally {
291 restoreCallingIdentity(identityToken);
292 }
293 }
294
295 private String readPasswordFromDatabase(Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700296 if (account == null) {
297 return null;
298 }
299
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700300 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
301 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
302 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
303 new String[]{account.name, account.type}, null, null, null);
304 try {
305 if (cursor.moveToNext()) {
306 return cursor.getString(0);
307 }
308 return null;
309 } finally {
310 cursor.close();
311 }
312 }
313
314 public String getUserData(Account account, String key) {
315 checkAuthenticateAccountsPermission(account);
316 long identityToken = clearCallingIdentity();
317 try {
318 return readUserDataFromDatabase(account, key);
319 } finally {
320 restoreCallingIdentity(identityToken);
321 }
322 }
323
324 private String readUserDataFromDatabase(Account account, String key) {
Fred Quintana31957f12009-10-21 13:43:10 -0700325 if (account == null) {
326 return null;
327 }
328
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700329 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700330 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_VALUE},
331 EXTRAS_ACCOUNTS_ID
332 + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
333 + EXTRAS_KEY + "=?",
334 new String[]{account.name, account.type, key}, null, null, null);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700335 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700336 if (cursor.moveToNext()) {
337 return cursor.getString(0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700338 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700339 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700340 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700341 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700342 }
343 }
344
Fred Quintana97889762009-06-15 12:29:24 -0700345 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700346 long identityToken = clearCallingIdentity();
347 try {
Fred Quintana97889762009-06-15 12:29:24 -0700348 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
349 authenticatorCollection = mAuthenticatorCache.getAllServices();
350 AuthenticatorDescription[] types =
351 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700352 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700353 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700354 : authenticatorCollection) {
355 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700356 i++;
357 }
358 return types;
359 } finally {
360 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700361 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700362 }
363
Fred Quintanaa698f422009-04-08 19:14:54 -0700364 public Account[] getAccountsByType(String accountType) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700365 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700366
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700367 final String selection = accountType == null ? null : (ACCOUNTS_TYPE + "=?");
368 final String[] selectionArgs = accountType == null ? null : new String[]{accountType};
369 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_NAME_TYPE_PROJECTION,
370 selection, selectionArgs, null, null, null);
371 try {
372 int i = 0;
373 Account[] accounts = new Account[cursor.getCount()];
374 while (cursor.moveToNext()) {
375 accounts[i] = new Account(cursor.getString(1), cursor.getString(2));
376 i++;
Fred Quintana60307342009-03-24 22:48:12 -0700377 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700378 return accounts;
Fred Quintana60307342009-03-24 22:48:12 -0700379 } finally {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700380 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700381 }
382 }
383
Fred Quintanaa698f422009-04-08 19:14:54 -0700384 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700385 checkAuthenticateAccountsPermission(account);
386
Fred Quintana60307342009-03-24 22:48:12 -0700387 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700388 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700389 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700390 return insertAccountIntoDatabase(account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700391 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700392 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700393 }
394 }
395
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700396 private boolean insertAccountIntoDatabase(Account account, String password, Bundle extras) {
397 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
398 db.beginTransaction();
399 try {
Fred Quintana31957f12009-10-21 13:43:10 -0700400 if (account == null) {
401 return false;
402 }
Jim Miller50c05f32009-09-21 19:07:44 -0700403 boolean noBroadcast = false;
404 if (account.type.equals(GOOGLE_ACCOUNT_TYPE)) {
405 // Look for the 'nobroadcast' flag and remove it since we don't want it to persist
406 // in the db.
407 noBroadcast = extras.getBoolean(NO_BROADCAST_FLAG, false);
408 extras.remove(NO_BROADCAST_FLAG);
409 }
410
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700411 long numMatches = DatabaseUtils.longForQuery(db,
412 "select count(*) from " + TABLE_ACCOUNTS
413 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
414 new String[]{account.name, account.type});
415 if (numMatches > 0) {
416 return false;
417 }
418 ContentValues values = new ContentValues();
419 values.put(ACCOUNTS_NAME, account.name);
420 values.put(ACCOUNTS_TYPE, account.type);
421 values.put(ACCOUNTS_PASSWORD, password);
422 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
423 if (accountId < 0) {
424 return false;
425 }
426 if (extras != null) {
427 for (String key : extras.keySet()) {
428 final String value = extras.getString(key);
429 if (insertExtra(db, accountId, key, value) < 0) {
430 return false;
431 }
432 }
433 }
434 db.setTransactionSuccessful();
Jim Miller50c05f32009-09-21 19:07:44 -0700435 if (!noBroadcast) {
436 sendAccountsChangedBroadcast();
437 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700438 return true;
439 } finally {
440 db.endTransaction();
441 }
442 }
443
Fred Quintana60307342009-03-24 22:48:12 -0700444 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
445 ContentValues values = new ContentValues();
446 values.put(EXTRAS_KEY, key);
447 values.put(EXTRAS_ACCOUNTS_ID, accountId);
448 values.put(EXTRAS_VALUE, value);
449 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
450 }
451
Fred Quintana3084a6f2010-01-14 18:02:03 -0800452 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800453 Account account, String[] features) {
454 checkReadAccountsPermission();
455 long identityToken = clearCallingIdentity();
456 try {
457 new TestFeaturesSession(response, account, features).bind();
458 } finally {
459 restoreCallingIdentity(identityToken);
460 }
461 }
462
463 private class TestFeaturesSession extends Session {
464 private final String[] mFeatures;
465 private final Account mAccount;
466
467 public TestFeaturesSession(IAccountManagerResponse response,
468 Account account, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -0800469 super(response, account.type, false /* expectActivityLaunch */,
470 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800471 mFeatures = features;
472 mAccount = account;
473 }
474
475 public void run() throws RemoteException {
476 try {
477 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
478 } catch (RemoteException e) {
479 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
480 }
481 }
482
483 public void onResult(Bundle result) {
484 IAccountManagerResponse response = getResponseAndClose();
485 if (response != null) {
486 try {
487 if (result == null) {
488 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
489 return;
490 }
491 final Bundle newResult = new Bundle();
492 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
493 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
494 response.onResult(newResult);
495 } catch (RemoteException e) {
496 // if the caller is dead then there is no one to care about remote exceptions
497 if (Log.isLoggable(TAG, Log.VERBOSE)) {
498 Log.v(TAG, "failure while notifying response", e);
499 }
500 }
501 }
502 }
503
504 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800505 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800506 + ", " + mAccount
507 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
508 }
509 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800510
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700511 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700512 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700513 long identityToken = clearCallingIdentity();
514 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700516 } finally {
517 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700518 }
Fred Quintana60307342009-03-24 22:48:12 -0700519 }
520
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700521 private class RemoveAccountSession extends Session {
522 final Account mAccount;
523 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
Fred Quintana8570f742010-02-18 10:32:54 -0800524 super(response, account.type, false /* expectActivityLaunch */,
525 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700526 mAccount = account;
527 }
528
529 protected String toDebugString(long now) {
530 return super.toDebugString(now) + ", removeAccount"
531 + ", account " + mAccount;
532 }
533
534 public void run() throws RemoteException {
535 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
536 }
537
538 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700539 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
540 && !result.containsKey(AccountManager.KEY_INTENT)) {
541 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700542 if (removalAllowed) {
543 removeAccount(mAccount);
544 }
545 IAccountManagerResponse response = getResponseAndClose();
546 if (response != null) {
547 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700548 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700549 try {
550 response.onResult(result2);
551 } catch (RemoteException e) {
552 // ignore
553 }
554 }
555 }
556 super.onResult(result);
557 }
558 }
559
560 private void removeAccount(Account account) {
561 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
562 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
563 new String[]{account.name, account.type});
564 sendAccountsChangedBroadcast();
565 }
566
Fred Quintanaa698f422009-04-08 19:14:54 -0700567 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintanab38eb142010-02-24 13:40:54 -0800568 checkManageAccountsOrUseCredentialsPermissions();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700569 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700570 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700571 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
572 db.beginTransaction();
573 try {
574 invalidateAuthToken(db, accountType, authToken);
575 db.setTransactionSuccessful();
576 } finally {
577 db.endTransaction();
578 }
Fred Quintana60307342009-03-24 22:48:12 -0700579 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700580 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700581 }
582 }
583
584 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700585 if (authToken == null || accountType == null) {
586 return;
587 }
Fred Quintana33269202009-04-20 16:05:10 -0700588 Cursor cursor = db.rawQuery(
589 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
590 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
591 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
592 + " FROM " + TABLE_ACCOUNTS
593 + " JOIN " + TABLE_AUTHTOKENS
594 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
595 + " = " + AUTHTOKENS_ACCOUNTS_ID
596 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
597 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
598 new String[]{authToken, accountType});
599 try {
600 while (cursor.moveToNext()) {
601 long authTokenId = cursor.getLong(0);
602 String accountName = cursor.getString(1);
603 String authTokenType = cursor.getString(2);
604 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana60307342009-03-24 22:48:12 -0700605 }
Fred Quintana33269202009-04-20 16:05:10 -0700606 } finally {
607 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700608 }
609 }
610
611 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700612 if (account == null || type == null) {
613 return false;
614 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700615 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700616 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
617 db.beginTransaction();
618 try {
Fred Quintana33269202009-04-20 16:05:10 -0700619 long accountId = getAccountId(db, account);
620 if (accountId < 0) {
621 return false;
622 }
623 db.delete(TABLE_AUTHTOKENS,
624 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
625 new String[]{type});
626 ContentValues values = new ContentValues();
627 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
628 values.put(AUTHTOKENS_TYPE, type);
629 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
630 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700631 db.setTransactionSuccessful();
632 return true;
633 }
634 return false;
635 } finally {
636 db.endTransaction();
637 }
638 }
639
Fred Quintana60307342009-03-24 22:48:12 -0700640 public String readAuthTokenFromDatabase(Account account, String authTokenType) {
Fred Quintana31957f12009-10-21 13:43:10 -0700641 if (account == null || authTokenType == null) {
642 return null;
643 }
Fred Quintana60307342009-03-24 22:48:12 -0700644 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintana86bd0842009-09-17 17:00:01 -0700645 Cursor cursor = db.query(TABLE_AUTHTOKENS, new String[]{AUTHTOKENS_AUTHTOKEN},
646 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?) AND "
647 + AUTHTOKENS_TYPE + "=?",
648 new String[]{account.name, account.type, authTokenType},
649 null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -0700650 try {
Fred Quintana86bd0842009-09-17 17:00:01 -0700651 if (cursor.moveToNext()) {
652 return cursor.getString(0);
Fred Quintana60307342009-03-24 22:48:12 -0700653 }
Fred Quintana86bd0842009-09-17 17:00:01 -0700654 return null;
Fred Quintana60307342009-03-24 22:48:12 -0700655 } finally {
Fred Quintana86bd0842009-09-17 17:00:01 -0700656 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700657 }
658 }
659
Fred Quintanaa698f422009-04-08 19:14:54 -0700660 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700661 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700662 long identityToken = clearCallingIdentity();
663 try {
Fred Quintana33269202009-04-20 16:05:10 -0700664 return readAuthTokenFromDatabase(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700665 } finally {
666 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700667 }
Fred Quintana60307342009-03-24 22:48:12 -0700668 }
669
Fred Quintanaa698f422009-04-08 19:14:54 -0700670 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700671 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700672 long identityToken = clearCallingIdentity();
673 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700674 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700675 } finally {
676 restoreCallingIdentity(identityToken);
677 }
Fred Quintana60307342009-03-24 22:48:12 -0700678 }
679
Fred Quintanaa698f422009-04-08 19:14:54 -0700680 public void setPassword(Account account, String password) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700681 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700682 long identityToken = clearCallingIdentity();
683 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700684 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700685 } finally {
686 restoreCallingIdentity(identityToken);
687 }
Fred Quintana60307342009-03-24 22:48:12 -0700688 }
689
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700690 private void setPasswordInDB(Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700691 if (account == null) {
692 return;
693 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800694 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
695 db.beginTransaction();
696 try {
697 final ContentValues values = new ContentValues();
698 values.put(ACCOUNTS_PASSWORD, password);
699 final long accountId = getAccountId(db, account);
700 if (accountId >= 0) {
701 final String[] argsAccountId = {String.valueOf(accountId)};
702 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
703 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
704 db.setTransactionSuccessful();
705 }
706 } finally {
707 db.endTransaction();
708 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700709 sendAccountsChangedBroadcast();
710 }
711
Fred Quintana33269202009-04-20 16:05:10 -0700712 private void sendAccountsChangedBroadcast() {
713 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
714 }
715
Fred Quintanaa698f422009-04-08 19:14:54 -0700716 public void clearPassword(Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700717 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700718 long identityToken = clearCallingIdentity();
719 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700720 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700721 } finally {
722 restoreCallingIdentity(identityToken);
723 }
Fred Quintana60307342009-03-24 22:48:12 -0700724 }
725
Fred Quintanaa698f422009-04-08 19:14:54 -0700726 public void setUserData(Account account, String key, String value) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700727 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700728 long identityToken = clearCallingIdentity();
Fred Quintana31957f12009-10-21 13:43:10 -0700729 if (account == null) {
730 return;
731 }
Jim Miller50c05f32009-09-21 19:07:44 -0700732 if (account.type.equals(GOOGLE_ACCOUNT_TYPE) && key.equals("broadcast")) {
733 sendAccountsChangedBroadcast();
734 return;
735 }
Fred Quintana60307342009-03-24 22:48:12 -0700736 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700737 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700738 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700739 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700740 }
741 }
742
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700743 private void writeUserdataIntoDatabase(Account account, String key, String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700744 if (account == null || key == null) {
745 return;
746 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700747 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
748 db.beginTransaction();
749 try {
750 long accountId = getAccountId(db, account);
751 if (accountId < 0) {
752 return;
753 }
754 long extrasId = getExtrasId(db, accountId, key);
755 if (extrasId < 0 ) {
756 extrasId = insertExtra(db, accountId, key, value);
757 if (extrasId < 0) {
758 return;
759 }
760 } else {
761 ContentValues values = new ContentValues();
762 values.put(EXTRAS_VALUE, value);
763 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
764 return;
765 }
766
767 }
768 db.setTransactionSuccessful();
769 } finally {
770 db.endTransaction();
771 }
772 }
773
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700774 private void onResult(IAccountManagerResponse response, Bundle result) {
775 try {
776 response.onResult(result);
777 } catch (RemoteException e) {
778 // if the caller is dead then there is no one to care about remote
779 // exceptions
780 if (Log.isLoggable(TAG, Log.VERBOSE)) {
781 Log.v(TAG, "failure while notifying response", e);
782 }
783 }
784 }
785
Fred Quintanaa698f422009-04-08 19:14:54 -0700786 public void getAuthToken(IAccountManagerResponse response, final Account account,
787 final String authTokenType, final boolean notifyOnAuthFailure,
788 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700789 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
790 final int callerUid = Binder.getCallingUid();
791 final boolean permissionGranted = permissionIsGranted(account, authTokenType, callerUid);
792
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700793 long identityToken = clearCallingIdentity();
794 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700795 // if the caller has permission, do the peek. otherwise go the more expensive
796 // route of starting a Session
797 if (permissionGranted) {
798 String authToken = readAuthTokenFromDatabase(account, authTokenType);
799 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700800 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700801 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
802 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
803 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700804 onResult(response, result);
805 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700806 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700807 }
808
Fred Quintana8570f742010-02-18 10:32:54 -0800809 new Session(response, account.type, expectActivityLaunch,
810 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700811 protected String toDebugString(long now) {
812 if (loginOptions != null) loginOptions.keySet();
813 return super.toDebugString(now) + ", getAuthToken"
814 + ", " + account
815 + ", authTokenType " + authTokenType
816 + ", loginOptions " + loginOptions
817 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
818 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700819
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700820 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700821 // If the caller doesn't have permission then create and return the
822 // "grant permission" intent instead of the "getAuthToken" intent.
823 if (!permissionGranted) {
824 mAuthenticator.getAuthTokenLabel(this, authTokenType);
825 } else {
826 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
827 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700828 }
829
830 public void onResult(Bundle result) {
831 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700832 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700833 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
834 new AccountAuthenticatorResponse(this),
835 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700836 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700837 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700838 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700839 onResult(bundle);
840 return;
841 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700842 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700843 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700844 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
845 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700846 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700847 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700848 "the type and name should not be empty");
849 return;
850 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700851 saveAuthTokenToDatabase(new Account(name, type),
852 authTokenType, authToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700853 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700854
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700855 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700856 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700857 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700858 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700859 intent);
860 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700861 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700862 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700863 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700864 }.bind();
865 } finally {
866 restoreCallingIdentity(identityToken);
867 }
Fred Quintana60307342009-03-24 22:48:12 -0700868 }
869
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700870 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
871 int uid = intent.getIntExtra(
872 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
873 String authTokenType = intent.getStringExtra(
874 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
875 String authTokenLabel = intent.getStringExtra(
876 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
877
878 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
879 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700880 final String titleAndSubtitle =
881 mContext.getString(R.string.permission_request_notification_with_subtitle,
882 account.name);
883 final int index = titleAndSubtitle.indexOf('\n');
884 final String title = titleAndSubtitle.substring(0, index);
885 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700886 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700887 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700888 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
889 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
890 .notify(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
891 }
892
893 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
894 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
895 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
896 mAuthenticatorCache.getServiceInfo(
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700897 AuthenticatorDescription.newKey(account.type));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700898 if (serviceInfo == null) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700899 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700900 }
901
902 final Context authContext;
903 try {
904 authContext = mContext.createPackageContext(
905 serviceInfo.type.packageName, 0);
906 } catch (PackageManager.NameNotFoundException e) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700907 throw new IllegalArgumentException("unknown account type: " + account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700908 }
909
910 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
911 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
912 intent.addCategory(
913 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
914 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
915 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL, authTokenLabel);
916 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
917 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
918 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT_TYPE_LABEL,
919 authContext.getString(serviceInfo.type.labelId));
920 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_PACKAGES,
921 mContext.getPackageManager().getPackagesForUid(uid));
922 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
923 return intent;
924 }
925
926 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
927 int uid) {
928 Integer id;
929 synchronized(mCredentialsPermissionNotificationIds) {
930 final Pair<Pair<Account, String>, Integer> key =
931 new Pair<Pair<Account, String>, Integer>(
932 new Pair<Account, String>(account, authTokenType), uid);
933 id = mCredentialsPermissionNotificationIds.get(key);
934 if (id == null) {
935 id = mNotificationIds.incrementAndGet();
936 mCredentialsPermissionNotificationIds.put(key, id);
937 }
938 }
939 return id;
940 }
941
942 private Integer getSigninRequiredNotificationId(Account account) {
943 Integer id;
944 synchronized(mSigninRequiredNotificationIds) {
945 id = mSigninRequiredNotificationIds.get(account);
946 if (id == null) {
947 id = mNotificationIds.incrementAndGet();
948 mSigninRequiredNotificationIds.put(account, id);
949 }
950 }
951 return id;
952 }
953
Fred Quintanaa698f422009-04-08 19:14:54 -0700954
Fred Quintana33269202009-04-20 16:05:10 -0700955 public void addAcount(final IAccountManagerResponse response, final String accountType,
956 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -0700957 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700958 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700959 long identityToken = clearCallingIdentity();
960 try {
Fred Quintana8570f742010-02-18 10:32:54 -0800961 new Session(response, accountType, expectActivityLaunch,
962 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700963 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -0700964 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -0700965 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700966 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700967
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700968 protected String toDebugString(long now) {
969 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -0700970 + ", accountType " + accountType
971 + ", requiredFeatures "
972 + (requiredFeatures != null
973 ? TextUtils.join(",", requiredFeatures)
974 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700975 }
976 }.bind();
977 } finally {
978 restoreCallingIdentity(identityToken);
979 }
Fred Quintana60307342009-03-24 22:48:12 -0700980 }
981
Fred Quintanaa698f422009-04-08 19:14:54 -0700982 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700983 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700984 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700985 long identityToken = clearCallingIdentity();
986 try {
Fred Quintana8570f742010-02-18 10:32:54 -0800987 new Session(response, account.type, expectActivityLaunch,
988 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700989 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700990 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700991 }
992 protected String toDebugString(long now) {
993 return super.toDebugString(now) + ", confirmCredentials"
994 + ", " + account;
995 }
996 }.bind();
997 } finally {
998 restoreCallingIdentity(identityToken);
999 }
Fred Quintana60307342009-03-24 22:48:12 -07001000 }
1001
Fred Quintanaa698f422009-04-08 19:14:54 -07001002 public void updateCredentials(IAccountManagerResponse response, final Account account,
1003 final String authTokenType, final boolean expectActivityLaunch,
1004 final Bundle loginOptions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001005 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001006 long identityToken = clearCallingIdentity();
1007 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001008 new Session(response, account.type, expectActivityLaunch,
1009 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001010 public void run() throws RemoteException {
1011 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1012 }
1013 protected String toDebugString(long now) {
1014 if (loginOptions != null) loginOptions.keySet();
1015 return super.toDebugString(now) + ", updateCredentials"
1016 + ", " + account
1017 + ", authTokenType " + authTokenType
1018 + ", loginOptions " + loginOptions;
1019 }
1020 }.bind();
1021 } finally {
1022 restoreCallingIdentity(identityToken);
1023 }
Fred Quintana60307342009-03-24 22:48:12 -07001024 }
1025
Fred Quintanaa698f422009-04-08 19:14:54 -07001026 public void editProperties(IAccountManagerResponse response, final String accountType,
1027 final boolean expectActivityLaunch) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001028 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001029 long identityToken = clearCallingIdentity();
1030 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001031 new Session(response, accountType, expectActivityLaunch,
1032 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001033 public void run() throws RemoteException {
1034 mAuthenticator.editProperties(this, mAccountType);
1035 }
1036 protected String toDebugString(long now) {
1037 return super.toDebugString(now) + ", editProperties"
1038 + ", accountType " + accountType;
1039 }
1040 }.bind();
1041 } finally {
1042 restoreCallingIdentity(identityToken);
1043 }
Fred Quintana60307342009-03-24 22:48:12 -07001044 }
1045
Fred Quintana33269202009-04-20 16:05:10 -07001046 private class GetAccountsByTypeAndFeatureSession extends Session {
1047 private final String[] mFeatures;
1048 private volatile Account[] mAccountsOfType = null;
1049 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1050 private volatile int mCurrentAccount = 0;
1051
1052 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
1053 String type, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -08001054 super(response, type, false /* expectActivityLaunch */,
1055 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001056 mFeatures = features;
1057 }
1058
1059 public void run() throws RemoteException {
1060 mAccountsOfType = getAccountsByType(mAccountType);
1061 // check whether each account matches the requested features
1062 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1063 mCurrentAccount = 0;
1064
1065 checkAccount();
1066 }
1067
1068 public void checkAccount() {
1069 if (mCurrentAccount >= mAccountsOfType.length) {
1070 sendResult();
1071 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001072 }
Fred Quintana33269202009-04-20 16:05:10 -07001073
Fred Quintana29e94b82010-03-10 12:11:51 -08001074 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1075 if (accountAuthenticator == null) {
1076 // It is possible that the authenticator has died, which is indicated by
1077 // mAuthenticator being set to null. If this happens then just abort.
1078 // There is no need to send back a result or error in this case since
1079 // that already happened when mAuthenticator was cleared.
1080 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1081 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1082 + " connected to the authenticator, " + toDebugString());
1083 }
1084 return;
1085 }
Fred Quintana33269202009-04-20 16:05:10 -07001086 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001087 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001088 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001089 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001090 }
1091 }
1092
1093 public void onResult(Bundle result) {
1094 mNumResults++;
1095 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001096 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001097 return;
1098 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001099 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001100 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1101 }
1102 mCurrentAccount++;
1103 checkAccount();
1104 }
1105
1106 public void sendResult() {
1107 IAccountManagerResponse response = getResponseAndClose();
1108 if (response != null) {
1109 try {
1110 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1111 for (int i = 0; i < accounts.length; i++) {
1112 accounts[i] = mAccountsWithFeatures.get(i);
1113 }
1114 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001115 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001116 response.onResult(result);
1117 } catch (RemoteException e) {
1118 // if the caller is dead then there is no one to care about remote exceptions
1119 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1120 Log.v(TAG, "failure while notifying response", e);
1121 }
1122 }
1123 }
1124 }
1125
1126
1127 protected String toDebugString(long now) {
1128 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1129 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1130 }
1131 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001132
1133 public Account[] getAccounts(String type) {
1134 checkReadAccountsPermission();
1135 long identityToken = clearCallingIdentity();
1136 try {
1137 return getAccountsByType(type);
1138 } finally {
1139 restoreCallingIdentity(identityToken);
1140 }
1141 }
1142
1143 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001144 String type, String[] features) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001145 checkReadAccountsPermission();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001146 if (features != null && type == null) {
Fred Quintana33269202009-04-20 16:05:10 -07001147 if (response != null) {
1148 try {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001149 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "type is null");
Fred Quintana33269202009-04-20 16:05:10 -07001150 } catch (RemoteException e) {
1151 // ignore this
1152 }
1153 }
1154 return;
1155 }
1156 long identityToken = clearCallingIdentity();
1157 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001158 if (features == null || features.length == 0) {
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001159 Account[] accounts = getAccountsByType(type);
1160 Bundle result = new Bundle();
1161 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1162 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001163 return;
1164 }
Fred Quintana33269202009-04-20 16:05:10 -07001165 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1166 } finally {
1167 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001168 }
1169 }
1170
Fred Quintana60307342009-03-24 22:48:12 -07001171 private long getAccountId(SQLiteDatabase db, Account account) {
1172 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001173 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001174 try {
1175 if (cursor.moveToNext()) {
1176 return cursor.getLong(0);
1177 }
1178 return -1;
1179 } finally {
1180 cursor.close();
1181 }
1182 }
1183
1184 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1185 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1186 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1187 new String[]{key}, null, null, null);
1188 try {
1189 if (cursor.moveToNext()) {
1190 return cursor.getLong(0);
1191 }
1192 return -1;
1193 } finally {
1194 cursor.close();
1195 }
1196 }
1197
Fred Quintanaa698f422009-04-08 19:14:54 -07001198 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001199 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001200 IAccountManagerResponse mResponse;
1201 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001202 final boolean mExpectActivityLaunch;
1203 final long mCreationTime;
1204
Fred Quintana33269202009-04-20 16:05:10 -07001205 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001206 private int mNumRequestContinued = 0;
1207 private int mNumErrors = 0;
1208
Fred Quintana60307342009-03-24 22:48:12 -07001209
1210 IAccountAuthenticator mAuthenticator = null;
1211
Fred Quintana8570f742010-02-18 10:32:54 -08001212 private final boolean mStripAuthTokenFromResult;
1213
Fred Quintanaa698f422009-04-08 19:14:54 -07001214 public Session(IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001215 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001216 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001217 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001218 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana8570f742010-02-18 10:32:54 -08001219 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001220 mResponse = response;
1221 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001222 mExpectActivityLaunch = expectActivityLaunch;
1223 mCreationTime = SystemClock.elapsedRealtime();
1224 synchronized (mSessions) {
1225 mSessions.put(toString(), this);
1226 }
1227 try {
1228 response.asBinder().linkToDeath(this, 0 /* flags */);
1229 } catch (RemoteException e) {
1230 mResponse = null;
1231 binderDied();
1232 }
Fred Quintana60307342009-03-24 22:48:12 -07001233 }
1234
Fred Quintanaa698f422009-04-08 19:14:54 -07001235 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001236 if (mResponse == null) {
1237 // this session has already been closed
1238 return null;
1239 }
Fred Quintana60307342009-03-24 22:48:12 -07001240 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001241 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001242 return response;
1243 }
1244
Fred Quintanaa698f422009-04-08 19:14:54 -07001245 private void close() {
1246 synchronized (mSessions) {
1247 if (mSessions.remove(toString()) == null) {
1248 // the session was already closed, so bail out now
1249 return;
1250 }
1251 }
1252 if (mResponse != null) {
1253 // stop listening for response deaths
1254 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1255
1256 // clear this so that we don't accidentally send any further results
1257 mResponse = null;
1258 }
1259 cancelTimeout();
1260 unbind();
1261 }
1262
1263 public void binderDied() {
1264 mResponse = null;
1265 close();
1266 }
1267
1268 protected String toDebugString() {
1269 return toDebugString(SystemClock.elapsedRealtime());
1270 }
1271
1272 protected String toDebugString(long now) {
1273 return "Session: expectLaunch " + mExpectActivityLaunch
1274 + ", connected " + (mAuthenticator != null)
1275 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1276 + "/" + mNumErrors + ")"
1277 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1278 }
1279
Fred Quintana60307342009-03-24 22:48:12 -07001280 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001281 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1282 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1283 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001284 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001285 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001286 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001287 }
1288 }
1289
1290 private void unbind() {
1291 if (mAuthenticator != null) {
1292 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001293 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001294 }
1295 }
1296
1297 public void scheduleTimeout() {
1298 mMessageHandler.sendMessageDelayed(
1299 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1300 }
1301
1302 public void cancelTimeout() {
1303 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1304 }
1305
Fred Quintanab839afc2009-10-14 15:57:28 -07001306 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001307 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001308 try {
1309 run();
1310 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001311 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001312 "remote exception");
1313 }
Fred Quintana60307342009-03-24 22:48:12 -07001314 }
1315
Fred Quintanab839afc2009-10-14 15:57:28 -07001316 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001317 mAuthenticator = null;
1318 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001319 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001320 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001321 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001322 }
1323 }
1324
Fred Quintanab839afc2009-10-14 15:57:28 -07001325 public abstract void run() throws RemoteException;
1326
Fred Quintana60307342009-03-24 22:48:12 -07001327 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001328 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001329 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001330 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001331 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001332 }
1333 }
1334
Fred Quintanaa698f422009-04-08 19:14:54 -07001335 public void onResult(Bundle result) {
1336 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001337 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1338 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1339 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001340 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1341 Account account = new Account(accountName, accountType);
1342 cancelNotification(getSigninRequiredNotificationId(account));
1343 }
Fred Quintana60307342009-03-24 22:48:12 -07001344 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001345 IAccountManagerResponse response;
1346 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001347 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001348 response = mResponse;
1349 } else {
1350 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001351 }
Fred Quintana60307342009-03-24 22:48:12 -07001352 if (response != null) {
1353 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001354 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001355 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001356 "null bundle returned");
1357 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001358 if (mStripAuthTokenFromResult) {
1359 result.remove(AccountManager.KEY_AUTHTOKEN);
1360 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001361 response.onResult(result);
1362 }
Fred Quintana60307342009-03-24 22:48:12 -07001363 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001364 // if the caller is dead then there is no one to care about remote exceptions
1365 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1366 Log.v(TAG, "failure while notifying response", e);
1367 }
Fred Quintana60307342009-03-24 22:48:12 -07001368 }
1369 }
1370 }
Fred Quintana60307342009-03-24 22:48:12 -07001371
Fred Quintanaa698f422009-04-08 19:14:54 -07001372 public void onRequestContinued() {
1373 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001374 }
1375
1376 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001377 mNumErrors++;
1378 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1379 Log.v(TAG, "Session.onError: " + errorCode + ", " + errorMessage);
Fred Quintana60307342009-03-24 22:48:12 -07001380 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001381 IAccountManagerResponse response = getResponseAndClose();
1382 if (response != null) {
1383 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1384 Log.v(TAG, "Session.onError: responding");
1385 }
1386 try {
1387 response.onError(errorCode, errorMessage);
1388 } catch (RemoteException e) {
1389 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1390 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1391 }
1392 }
1393 } else {
1394 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1395 Log.v(TAG, "Session.onError: already closed");
1396 }
Fred Quintana60307342009-03-24 22:48:12 -07001397 }
1398 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001399
1400 /**
1401 * find the component name for the authenticator and initiate a bind
1402 * if no authenticator or the bind fails then return false, otherwise return true
1403 */
1404 private boolean bindToAuthenticator(String authenticatorType) {
1405 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1406 mAuthenticatorCache.getServiceInfo(
1407 AuthenticatorDescription.newKey(authenticatorType));
1408 if (authenticatorInfo == null) {
1409 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1410 Log.v(TAG, "there is no authenticator for " + authenticatorType
1411 + ", bailing out");
1412 }
1413 return false;
1414 }
1415
1416 Intent intent = new Intent();
1417 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1418 intent.setComponent(authenticatorInfo.componentName);
1419 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1420 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1421 }
1422 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1423 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1424 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1425 }
1426 return false;
1427 }
1428
1429
1430 return true;
1431 }
Fred Quintana60307342009-03-24 22:48:12 -07001432 }
1433
1434 private class MessageHandler extends Handler {
1435 MessageHandler(Looper looper) {
1436 super(looper);
1437 }
Costin Manolache3348f142009-09-29 18:58:36 -07001438
Fred Quintana60307342009-03-24 22:48:12 -07001439 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001440 switch (msg.what) {
1441 case MESSAGE_TIMED_OUT:
1442 Session session = (Session)msg.obj;
1443 session.onTimedOut();
1444 break;
1445
1446 default:
1447 throw new IllegalStateException("unhandled message: " + msg.what);
1448 }
1449 }
1450 }
1451
Oscar Montemayora8529f62009-11-18 10:14:20 -08001452 private static String getDatabaseName() {
1453 if(Environment.isEncryptedFilesystemEnabled()) {
1454 // Hard-coded path in case of encrypted file system
1455 return Environment.getSystemSecureDirectory().getPath() + File.separator + DATABASE_NAME;
1456 } else {
1457 // Regular path in case of non-encrypted file system
1458 return DATABASE_NAME;
1459 }
1460 }
1461
Fred Quintana60307342009-03-24 22:48:12 -07001462 private class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001463
Fred Quintana60307342009-03-24 22:48:12 -07001464 public DatabaseHelper(Context context) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001465 super(context, AccountManagerService.getDatabaseName(), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001466 }
1467
1468 @Override
1469 public void onCreate(SQLiteDatabase db) {
1470 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1471 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1472 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1473 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1474 + ACCOUNTS_PASSWORD + " TEXT, "
1475 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1476
1477 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1478 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1479 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1480 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1481 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1482 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1483
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001484 createGrantsTable(db);
1485
Fred Quintana60307342009-03-24 22:48:12 -07001486 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1487 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1488 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1489 + EXTRAS_KEY + " TEXT NOT NULL, "
1490 + EXTRAS_VALUE + " TEXT, "
1491 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1492
1493 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1494 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1495 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001496
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001497 createAccountsDeletionTrigger(db);
1498 }
1499
1500 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001501 db.execSQL(""
1502 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1503 + " BEGIN"
1504 + " DELETE FROM " + TABLE_AUTHTOKENS
1505 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1506 + " DELETE FROM " + TABLE_EXTRAS
1507 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001508 + " DELETE FROM " + TABLE_GRANTS
1509 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001510 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001511 }
1512
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001513 private void createGrantsTable(SQLiteDatabase db) {
1514 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1515 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1516 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1517 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1518 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1519 + "," + GRANTS_GRANTEE_UID + "))");
1520 }
1521
Fred Quintana60307342009-03-24 22:48:12 -07001522 @Override
1523 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001524 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001525
Fred Quintanaa698f422009-04-08 19:14:54 -07001526 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001527 // no longer need to do anything since the work is done
1528 // when upgrading from version 2
1529 oldVersion++;
1530 }
1531
1532 if (oldVersion == 2) {
1533 createGrantsTable(db);
1534 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1535 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001536 oldVersion++;
1537 }
Costin Manolache3348f142009-09-29 18:58:36 -07001538
1539 if (oldVersion == 3) {
1540 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1541 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1542 oldVersion++;
1543 }
Fred Quintana60307342009-03-24 22:48:12 -07001544 }
1545
1546 @Override
1547 public void onOpen(SQLiteDatabase db) {
1548 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1549 }
1550 }
1551
1552 private void setMetaValue(String key, String value) {
1553 ContentValues values = new ContentValues();
1554 values.put(META_KEY, key);
1555 values.put(META_VALUE, value);
1556 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1557 }
1558
1559 private String getMetaValue(String key) {
1560 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1561 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1562 try {
1563 if (c.moveToNext()) {
1564 return c.getString(0);
1565 }
1566 return null;
1567 } finally {
1568 c.close();
1569 }
1570 }
1571
1572 private class SimWatcher extends BroadcastReceiver {
1573 public SimWatcher(Context context) {
1574 // Re-scan the SIM card when the SIM state changes, and also if
1575 // the disk recovers from a full state (we may have failed to handle
1576 // things properly while the disk was full).
1577 final IntentFilter filter = new IntentFilter();
1578 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1579 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1580 context.registerReceiver(this, filter);
1581 }
Costin Manolache3348f142009-09-29 18:58:36 -07001582
Fred Quintana60307342009-03-24 22:48:12 -07001583 /**
1584 * Compare the IMSI to the one stored in the login service's
1585 * database. If they differ, erase all passwords and
1586 * authtokens (and store the new IMSI).
1587 */
1588 @Override
1589 public void onReceive(Context context, Intent intent) {
Doug Zongker885cfc232009-10-21 16:52:44 -07001590 // Check IMSI on every update; nothing happens if the IMSI
1591 // is missing or unchanged.
1592 TelephonyManager telephonyManager =
1593 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1594 if (telephonyManager == null) {
1595 Log.w(TAG, "failed to get TelephonyManager");
1596 return;
1597 }
1598 String imsi = telephonyManager.getSubscriberId();
1599
1600 // If the subscriber ID is an empty string, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001601 if (TextUtils.isEmpty(imsi)) return;
1602
Doug Zongker885cfc232009-10-21 16:52:44 -07001603 // If the current IMSI matches what's stored, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001604 String storedImsi = getMetaValue("imsi");
Fred Quintana60307342009-03-24 22:48:12 -07001605 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1606 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1607 }
Doug Zongker885cfc232009-10-21 16:52:44 -07001608 if (imsi.equals(storedImsi)) return;
1609
1610 // If a CDMA phone is unprovisioned, getSubscriberId()
1611 // will return a different value, but we *don't* erase the
1612 // passwords. We only erase them if it has a different
1613 // subscriber ID once it's provisioned.
1614 if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
1615 IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
1616 if (service == null) {
1617 Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
1618 return;
1619 }
1620 ITelephony telephony = ITelephony.Stub.asInterface(service);
1621 if (telephony == null) {
1622 Log.w(TAG, "failed to get ITelephony interface");
1623 return;
1624 }
1625 boolean needsProvisioning;
1626 try {
1627 needsProvisioning = telephony.getCdmaNeedsProvisioning();
1628 } catch (RemoteException e) {
1629 Log.w(TAG, "exception while checking provisioning", e);
1630 // default to NOT wiping out the passwords
1631 needsProvisioning = true;
1632 }
1633 if (needsProvisioning) {
1634 // if the phone needs re-provisioning, don't do anything.
1635 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1636 Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
1637 storedImsi);
1638 }
1639 return;
1640 }
1641 }
Fred Quintana60307342009-03-24 22:48:12 -07001642
jsh5b462472009-09-01 16:13:55 -07001643 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001644 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1645 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001646 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1647 db.beginTransaction();
1648 try {
1649 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1650 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana33269202009-04-20 16:05:10 -07001651 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001652 db.setTransactionSuccessful();
1653 } finally {
1654 db.endTransaction();
1655 }
1656 }
1657 setMetaValue("imsi", imsi);
1658 }
1659 }
1660
1661 public IBinder onBind(Intent intent) {
1662 return asBinder();
1663 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001664
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001665 /**
1666 * Searches array of arguments for the specified string
1667 * @param args array of argument strings
1668 * @param value value to search for
1669 * @return true if the value is contained in the array
1670 */
1671 private static boolean scanArgs(String[] args, String value) {
1672 if (args != null) {
1673 for (String arg : args) {
1674 if (value.equals(arg)) {
1675 return true;
1676 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001677 }
1678 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001679 return false;
1680 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001681
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001682 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1683 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001684
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001685 if (isCheckinRequest) {
1686 // This is a checkin request. *Only* upload the account types and the count of each.
1687 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1688
1689 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1690 null, null, ACCOUNTS_TYPE, null, null);
1691 try {
1692 while (cursor.moveToNext()) {
1693 // print type,count
1694 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1695 }
1696 } finally {
1697 if (cursor != null) {
1698 cursor.close();
1699 }
1700 }
1701 } else {
Fred Quintana307da1a2010-01-21 14:24:20 -08001702 Account[] accounts = getAccounts(null /* type */);
1703 fout.println("Accounts: " + accounts.length);
1704 for (Account account : accounts) {
1705 fout.println(" " + account);
1706 }
1707
1708 fout.println();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001709 synchronized (mSessions) {
1710 final long now = SystemClock.elapsedRealtime();
Fred Quintana307da1a2010-01-21 14:24:20 -08001711 fout.println("Active Sessions: " + mSessions.size());
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001712 for (Session session : mSessions.values()) {
1713 fout.println(" " + session.toDebugString(now));
1714 }
1715 }
1716
1717 fout.println();
1718 mAuthenticatorCache.dump(fd, fout, args);
1719 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001720 }
1721
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001722 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001723 long identityToken = clearCallingIdentity();
1724 try {
1725 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1726 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1727 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001728
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001729 if (intent.getComponent() != null &&
1730 GrantCredentialsPermissionActivity.class.getName().equals(
1731 intent.getComponent().getClassName())) {
1732 createNoCredentialsPermissionNotification(account, intent);
1733 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001734 final Integer notificationId = getSigninRequiredNotificationId(account);
1735 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001736 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1737 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001738 final String notificationTitleFormat =
1739 mContext.getText(R.string.notification_title).toString();
1740 n.setLatestEventInfo(mContext,
1741 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001742 message, PendingIntent.getActivity(
1743 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
1744 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintana33f889a2009-09-14 17:31:26 -07001745 .notify(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001746 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001747 } finally {
1748 restoreCallingIdentity(identityToken);
1749 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001750 }
1751
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001752 private void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001753 long identityToken = clearCallingIdentity();
1754 try {
1755 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001756 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001757 } finally {
1758 restoreCallingIdentity(identityToken);
1759 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001760 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001761
Fred Quintanab38eb142010-02-24 13:40:54 -08001762 /** Succeeds if any of the specified permissions are granted. */
1763 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001764 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08001765
1766 for (String perm : permissions) {
1767 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
1768 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1769 Log.v(TAG, "caller uid " + uid + " has " + perm);
1770 }
1771 return;
1772 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001773 }
Fred Quintanab38eb142010-02-24 13:40:54 -08001774
1775 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
1776 Log.w(TAG, msg);
1777 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001778 }
1779
Fred Quintana7be59642009-08-24 18:29:25 -07001780 private boolean inSystemImage(int callerUid) {
1781 String[] packages = mContext.getPackageManager().getPackagesForUid(callerUid);
1782 for (String name : packages) {
1783 try {
1784 PackageInfo packageInfo =
1785 mContext.getPackageManager().getPackageInfo(name, 0 /* flags */);
1786 if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1787 return true;
1788 }
1789 } catch (PackageManager.NameNotFoundException e) {
1790 return false;
1791 }
1792 }
1793 return false;
1794 }
1795
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001796 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001797 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07001798 final boolean fromAuthenticator = account != null
1799 && hasAuthenticatorUid(account.type, callerUid);
1800 final boolean hasExplicitGrants = account != null
1801 && hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001802 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1803 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
1804 + callerUid + ", account " + account
1805 + ": is authenticator? " + fromAuthenticator
1806 + ", has explicit permission? " + hasExplicitGrants);
1807 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001808 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001809 }
1810
Fred Quintana1a231912009-10-15 11:31:30 -07001811 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001812 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1813 mAuthenticatorCache.getAllServices()) {
1814 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001815 return (serviceInfo.uid == callingUid) ||
1816 (mContext.getPackageManager().checkSignatures(serviceInfo.uid, callingUid)
1817 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001818 }
1819 }
1820 return false;
1821 }
1822
1823 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1824 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1825 return true;
1826 }
1827 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1828 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001829 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001830 final boolean permissionGranted =
1831 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1832 if (!permissionGranted && isDebuggableMonkeyBuild) {
1833 // TODO: Skip this check when running automated tests. Replace this
1834 // with a more general solution.
Fred Quintana751fdc02010-02-09 14:13:18 -08001835 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001836 + authTokenType + " by uid " + Binder.getCallingUid()
1837 + " but ignoring since this is a monkey build");
1838 return true;
1839 }
1840 return permissionGranted;
1841 }
1842
1843 private void checkCallingUidAgainstAuthenticator(Account account) {
1844 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07001845 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001846 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1847 Log.w(TAG, msg);
1848 throw new SecurityException(msg);
1849 }
1850 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1851 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1852 }
1853 }
1854
1855 private void checkAuthenticateAccountsPermission(Account account) {
1856 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1857 checkCallingUidAgainstAuthenticator(account);
1858 }
1859
1860 private void checkReadAccountsPermission() {
1861 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1862 }
1863
1864 private void checkManageAccountsPermission() {
1865 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
1866 }
1867
Fred Quintanab38eb142010-02-24 13:40:54 -08001868 private void checkManageAccountsOrUseCredentialsPermissions() {
1869 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
1870 Manifest.permission.USE_CREDENTIALS);
1871 }
1872
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001873 /**
1874 * Allow callers with the given uid permission to get credentials for account/authTokenType.
1875 * <p>
1876 * Although this is public it can only be accessed via the AccountManagerService object
1877 * which is in the system. This means we don't need to protect it with permissions.
1878 * @hide
1879 */
1880 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001881 if (account == null || authTokenType == null) {
1882 return;
1883 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001884 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1885 db.beginTransaction();
1886 try {
1887 long accountId = getAccountId(db, account);
1888 if (accountId >= 0) {
1889 ContentValues values = new ContentValues();
1890 values.put(GRANTS_ACCOUNTS_ID, accountId);
1891 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
1892 values.put(GRANTS_GRANTEE_UID, uid);
1893 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
1894 db.setTransactionSuccessful();
1895 }
1896 } finally {
1897 db.endTransaction();
1898 }
1899 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1900 }
1901
1902 /**
1903 * Don't allow callers with the given uid permission to get credentials for
1904 * account/authTokenType.
1905 * <p>
1906 * Although this is public it can only be accessed via the AccountManagerService object
1907 * which is in the system. This means we don't need to protect it with permissions.
1908 * @hide
1909 */
1910 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001911 if (account == null || authTokenType == null) {
1912 return;
1913 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001914 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1915 db.beginTransaction();
1916 try {
1917 long accountId = getAccountId(db, account);
1918 if (accountId >= 0) {
1919 db.delete(TABLE_GRANTS,
1920 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
1921 + GRANTS_GRANTEE_UID + "=?",
1922 new String[]{String.valueOf(accountId), authTokenType,
1923 String.valueOf(uid)});
1924 db.setTransactionSuccessful();
1925 }
1926 } finally {
1927 db.endTransaction();
1928 }
1929 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
1930 }
Fred Quintana60307342009-03-24 22:48:12 -07001931}