blob: 6e045877aa9d3f9b95268592966b0a0924f6ac0a [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
Fred Quintana56285a62010-12-02 14:20:51 -080019import com.android.internal.R;
20import com.android.internal.telephony.ITelephony;
21import com.android.internal.telephony.TelephonyIntents;
22
Doug Zongker885cfc232009-10-21 16:52:44 -070023import android.Manifest;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080024import android.app.ActivityManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070025import android.app.Notification;
26import android.app.NotificationManager;
27import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070028import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070029import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070030import android.content.ContentValues;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070034import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070035import android.content.pm.ApplicationInfo;
36import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070037import android.content.pm.PackageManager;
38import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070039import android.content.pm.RegisteredServicesCacheListener;
Fred Quintana60307342009-03-24 22:48:12 -070040import android.database.Cursor;
41import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070042import android.database.sqlite.SQLiteDatabase;
43import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070044import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070045import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080046import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070047import android.os.Handler;
48import android.os.HandlerThread;
49import android.os.IBinder;
50import android.os.Looper;
51import android.os.Message;
52import android.os.RemoteException;
Doug Zongker885cfc232009-10-21 16:52:44 -070053import android.os.ServiceManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070054import android.os.SystemClock;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070055import android.os.SystemProperties;
Fred Quintana60307342009-03-24 22:48:12 -070056import android.telephony.TelephonyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070057import android.text.TextUtils;
58import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070059import android.util.Pair;
Fred Quintana60307342009-03-24 22:48:12 -070060
Oscar Montemayora8529f62009-11-18 10:14:20 -080061import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import java.io.FileDescriptor;
63import java.io.PrintWriter;
64import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080065import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070067import java.util.HashMap;
Fred Quintana56285a62010-12-02 14:20:51 -080068import java.util.LinkedHashMap;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070069import java.util.concurrent.atomic.AtomicInteger;
70import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070071
Fred Quintana60307342009-03-24 22:48:12 -070072/**
73 * A system service that provides account, password, and authtoken management for all
74 * accounts on the device. Some of these calls are implemented with the help of the corresponding
75 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
76 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
77 * AccountManager accountManager =
78 * (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE)
Fred Quintana33269202009-04-20 16:05:10 -070079 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070080 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070081public class AccountManagerService
82 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080083 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Costin Manolache3348f142009-09-29 18:58:36 -070084 private static final String GOOGLE_ACCOUNT_TYPE = "com.google";
Jim Miller50c05f32009-09-21 19:07:44 -070085
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
Fred Quintana56285a62010-12-02 14:20:51 -080094 private final PackageManager mPackageManager;
95
Fred Quintana60307342009-03-24 22:48:12 -070096 private HandlerThread mMessageThread;
97 private final MessageHandler mMessageHandler;
98
99 // Messages that can be sent on mHandler
100 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700101
Fred Quintana56285a62010-12-02 14:20:51 -0800102 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700103 private final DatabaseHelper mOpenHelper;
104 private final SimWatcher mSimWatcher;
105
106 private static final String TABLE_ACCOUNTS = "accounts";
107 private static final String ACCOUNTS_ID = "_id";
108 private static final String ACCOUNTS_NAME = "name";
109 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700110 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700111 private static final String ACCOUNTS_PASSWORD = "password";
112
113 private static final String TABLE_AUTHTOKENS = "authtokens";
114 private static final String AUTHTOKENS_ID = "_id";
115 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
116 private static final String AUTHTOKENS_TYPE = "type";
117 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
118
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700119 private static final String TABLE_GRANTS = "grants";
120 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
121 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
122 private static final String GRANTS_GRANTEE_UID = "uid";
123
Fred Quintana60307342009-03-24 22:48:12 -0700124 private static final String TABLE_EXTRAS = "extras";
125 private static final String EXTRAS_ID = "_id";
126 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
127 private static final String EXTRAS_KEY = "key";
128 private static final String EXTRAS_VALUE = "value";
129
130 private static final String TABLE_META = "meta";
131 private static final String META_KEY = "key";
132 private static final String META_VALUE = "value";
133
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 Quintana56285a62010-12-02 14:20:51 -0800146 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
147 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
148 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
149 AUTHTOKENS_AUTHTOKEN};
150
151 private static final String SELECTION_USERDATA_BY_ACCOUNT =
152 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
153 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
154
Fred Quintanaa698f422009-04-08 19:14:54 -0700155 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700156 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
157
158 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
159 mCredentialsPermissionNotificationIds =
160 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
161 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
162 new HashMap<Account, Integer>();
163 private static AtomicReference<AccountManagerService> sThis =
164 new AtomicReference<AccountManagerService>();
165
Fred Quintana31957f12009-10-21 13:43:10 -0700166 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700167
168 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700169 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700170 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
171 }
172
Fred Quintana56285a62010-12-02 14:20:51 -0800173 private final Object mCacheLock = new Object();
174 /** protected by the {@link #mCacheLock} */
175 private final HashMap<String, Account[]> mAccountCache = new HashMap<String, Account[]>();
176 /** protected by the {@link #mCacheLock} */
177 private HashMap<Account, HashMap<String, String>> mUserDataCache =
178 new HashMap<Account, HashMap<String, String>>();
179 /** protected by the {@link #mCacheLock} */
180 private HashMap<Account, HashMap<String, String>> mAuthTokenCache =
181 new HashMap<Account, HashMap<String, String>>();
182
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700183 /**
184 * This should only be called by system code. One should only call this after the service
185 * has started.
186 * @return a reference to the AccountManagerService instance
187 * @hide
188 */
189 public static AccountManagerService getSingleton() {
190 return sThis.get();
191 }
Fred Quintana60307342009-03-24 22:48:12 -0700192
Fred Quintana56285a62010-12-02 14:20:51 -0800193 public AccountManagerService(Context context) {
194 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700195 }
196
Fred Quintana56285a62010-12-02 14:20:51 -0800197 public AccountManagerService(Context context, PackageManager packageManager,
198 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700199 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800200 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700201
202 mOpenHelper = new DatabaseHelper(mContext);
203
204 mMessageThread = new HandlerThread("AccountManagerService");
205 mMessageThread.start();
206 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
207
Fred Quintana56285a62010-12-02 14:20:51 -0800208 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800209 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700210
Doug Zongker885cfc232009-10-21 16:52:44 -0700211 mSimWatcher = new SimWatcher(mContext);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700212 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800213
Fred Quintana56285a62010-12-02 14:20:51 -0800214 validateAccountsAndPopulateCache();
Fred Quintanaafa92b82009-12-01 16:27:03 -0800215 }
216
Fred Quintana56285a62010-12-02 14:20:51 -0800217 private void validateAccountsAndPopulateCache() {
Fred Quintanaafa92b82009-12-01 16:27:03 -0800218 boolean accountDeleted = false;
219 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
220 Cursor cursor = db.query(TABLE_ACCOUNTS,
221 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
222 null, null, null, null, null);
223 try {
Fred Quintana56285a62010-12-02 14:20:51 -0800224 synchronized (mCacheLock) {
225 mAccountCache.clear();
226 final HashMap<String, ArrayList<String>> accountNamesByType =
227 new HashMap<String, ArrayList<String>>();
228 while (cursor.moveToNext()) {
229 final long accountId = cursor.getLong(0);
230 final String accountType = cursor.getString(1);
231 final String accountName = cursor.getString(2);
232 if (mAuthenticatorCache.getServiceInfo(
233 AuthenticatorDescription.newKey(accountType)) == null) {
234 Log.d(TAG, "deleting account " + accountName + " because type "
235 + accountType + " no longer has a registered authenticator");
236 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
237 accountDeleted = true;
238 final Account account = new Account(accountName, accountType);
239 mUserDataCache.remove(account);
240 mAuthTokenCache.remove(account);
241 } else {
242 ArrayList<String> accountNames = accountNamesByType.get(accountType);
243 if (accountNames == null) {
244 accountNames = new ArrayList<String>();
245 accountNamesByType.put(accountType, accountNames);
246 }
247 accountNames.add(accountName);
248 }
249 }
250 for (HashMap.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
251 final String accountType = cur.getKey();
252 final ArrayList<String> accountNames = cur.getValue();
253 final Account[] accountsForType = new Account[accountNames.size()];
254 int i = 0;
255 for (String accountName : accountNames) {
256 accountsForType[i] = new Account(accountName, accountType);
257 ++i;
258 }
259 mAccountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800260 }
261 }
262 } finally {
263 cursor.close();
264 if (accountDeleted) {
265 sendAccountsChangedBroadcast();
266 }
267 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700268 }
269
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800270 public void onServiceChanged(AuthenticatorDescription desc, boolean removed) {
Fred Quintana56285a62010-12-02 14:20:51 -0800271 validateAccountsAndPopulateCache();
Fred Quintana60307342009-03-24 22:48:12 -0700272 }
273
Fred Quintanaa698f422009-04-08 19:14:54 -0700274 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800275 if (Log.isLoggable(TAG, Log.VERBOSE)) {
276 Log.v(TAG, "getPassword: " + account
277 + ", caller's uid " + Binder.getCallingUid()
278 + ", pid " + Binder.getCallingPid());
279 }
Fred Quintana382601f2010-03-25 12:25:10 -0700280 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700281 checkAuthenticateAccountsPermission(account);
282
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700283 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700284 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700285 return readPasswordFromDatabase(account);
286 } finally {
287 restoreCallingIdentity(identityToken);
288 }
289 }
290
291 private String readPasswordFromDatabase(Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700292 if (account == null) {
293 return null;
294 }
295
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700296 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
297 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
298 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
299 new String[]{account.name, account.type}, null, null, null);
300 try {
301 if (cursor.moveToNext()) {
302 return cursor.getString(0);
303 }
304 return null;
305 } finally {
306 cursor.close();
307 }
308 }
309
310 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800311 if (Log.isLoggable(TAG, Log.VERBOSE)) {
312 Log.v(TAG, "getUserData: " + account
313 + ", key " + key
314 + ", caller's uid " + Binder.getCallingUid()
315 + ", pid " + Binder.getCallingPid());
316 }
Fred Quintana382601f2010-03-25 12:25:10 -0700317 if (account == null) throw new IllegalArgumentException("account is null");
318 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700319 checkAuthenticateAccountsPermission(account);
320 long identityToken = clearCallingIdentity();
321 try {
Fred Quintana56285a62010-12-02 14:20:51 -0800322 return readUserDataFromCache(account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700323 } finally {
324 restoreCallingIdentity(identityToken);
325 }
326 }
327
Fred Quintana97889762009-06-15 12:29:24 -0700328 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800329 if (Log.isLoggable(TAG, Log.VERBOSE)) {
330 Log.v(TAG, "getAuthenticatorTypes: "
331 + "caller's uid " + Binder.getCallingUid()
332 + ", pid " + Binder.getCallingPid());
333 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700334 long identityToken = clearCallingIdentity();
335 try {
Fred Quintana97889762009-06-15 12:29:24 -0700336 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
337 authenticatorCollection = mAuthenticatorCache.getAllServices();
338 AuthenticatorDescription[] types =
339 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700340 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700341 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700342 : authenticatorCollection) {
343 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700344 i++;
345 }
346 return types;
347 } finally {
348 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700349 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700350 }
351
Fred Quintanaa698f422009-04-08 19:14:54 -0700352 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800353 if (Log.isLoggable(TAG, Log.VERBOSE)) {
354 Log.v(TAG, "addAccount: " + account
355 + ", caller's uid " + Binder.getCallingUid()
356 + ", pid " + Binder.getCallingPid());
357 }
Fred Quintana382601f2010-03-25 12:25:10 -0700358 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700359 checkAuthenticateAccountsPermission(account);
360
Fred Quintana60307342009-03-24 22:48:12 -0700361 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700362 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700363 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700364 return insertAccountIntoDatabase(account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700365 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700366 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700367 }
368 }
369
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700370 private boolean insertAccountIntoDatabase(Account account, String password, Bundle extras) {
371 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Fred Quintana743dfad2010-07-15 10:59:25 -0700372 if (account == null) {
373 return false;
374 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700375 db.beginTransaction();
376 try {
377 long numMatches = DatabaseUtils.longForQuery(db,
378 "select count(*) from " + TABLE_ACCOUNTS
379 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
380 new String[]{account.name, account.type});
381 if (numMatches > 0) {
Fred Quintana56285a62010-12-02 14:20:51 -0800382 Log.w(TAG, "insertAccountIntoDatabase: " + account
383 + ", skipping since the account already exists");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700384 return false;
385 }
386 ContentValues values = new ContentValues();
387 values.put(ACCOUNTS_NAME, account.name);
388 values.put(ACCOUNTS_TYPE, account.type);
389 values.put(ACCOUNTS_PASSWORD, password);
390 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
391 if (accountId < 0) {
Fred Quintana56285a62010-12-02 14:20:51 -0800392 Log.w(TAG, "insertAccountIntoDatabase: " + account
393 + ", skipping the DB insert failed");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700394 return false;
395 }
396 if (extras != null) {
397 for (String key : extras.keySet()) {
398 final String value = extras.getString(key);
399 if (insertExtra(db, accountId, key, value) < 0) {
Fred Quintana56285a62010-12-02 14:20:51 -0800400 Log.w(TAG, "insertAccountIntoDatabase: " + account
401 + ", skipping since insertExtra failed for key " + key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700402 return false;
403 }
404 }
405 }
406 db.setTransactionSuccessful();
Fred Quintana56285a62010-12-02 14:20:51 -0800407 insertAccountIntoCache(account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700408 } finally {
409 db.endTransaction();
410 }
Fred Quintanaafd2f542010-12-17 14:12:03 -0800411 sendAccountsChangedBroadcast();
Fred Quintana743dfad2010-07-15 10:59:25 -0700412 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700413 }
414
Fred Quintana60307342009-03-24 22:48:12 -0700415 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
416 ContentValues values = new ContentValues();
417 values.put(EXTRAS_KEY, key);
418 values.put(EXTRAS_ACCOUNTS_ID, accountId);
419 values.put(EXTRAS_VALUE, value);
420 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
421 }
422
Fred Quintana3084a6f2010-01-14 18:02:03 -0800423 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800424 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800425 if (Log.isLoggable(TAG, Log.VERBOSE)) {
426 Log.v(TAG, "hasFeatures: " + account
427 + ", response " + response
428 + ", features " + stringArrayToString(features)
429 + ", caller's uid " + Binder.getCallingUid()
430 + ", pid " + Binder.getCallingPid());
431 }
Fred Quintana382601f2010-03-25 12:25:10 -0700432 if (response == null) throw new IllegalArgumentException("response is null");
433 if (account == null) throw new IllegalArgumentException("account is null");
434 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800435 checkReadAccountsPermission();
436 long identityToken = clearCallingIdentity();
437 try {
438 new TestFeaturesSession(response, account, features).bind();
439 } finally {
440 restoreCallingIdentity(identityToken);
441 }
442 }
443
444 private class TestFeaturesSession extends Session {
445 private final String[] mFeatures;
446 private final Account mAccount;
447
448 public TestFeaturesSession(IAccountManagerResponse response,
449 Account account, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -0800450 super(response, account.type, false /* expectActivityLaunch */,
451 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800452 mFeatures = features;
453 mAccount = account;
454 }
455
456 public void run() throws RemoteException {
457 try {
458 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
459 } catch (RemoteException e) {
460 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
461 }
462 }
463
464 public void onResult(Bundle result) {
465 IAccountManagerResponse response = getResponseAndClose();
466 if (response != null) {
467 try {
468 if (result == null) {
469 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
470 return;
471 }
Fred Quintana56285a62010-12-02 14:20:51 -0800472 if (Log.isLoggable(TAG, Log.VERBOSE)) {
473 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
474 + response);
475 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800476 final Bundle newResult = new Bundle();
477 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
478 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
479 response.onResult(newResult);
480 } catch (RemoteException e) {
481 // if the caller is dead then there is no one to care about remote exceptions
482 if (Log.isLoggable(TAG, Log.VERBOSE)) {
483 Log.v(TAG, "failure while notifying response", e);
484 }
485 }
486 }
487 }
488
489 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800490 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800491 + ", " + mAccount
492 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
493 }
494 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800495
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700496 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800497 if (Log.isLoggable(TAG, Log.VERBOSE)) {
498 Log.v(TAG, "removeAccount: " + account
499 + ", response " + response
500 + ", caller's uid " + Binder.getCallingUid()
501 + ", pid " + Binder.getCallingPid());
502 }
Fred Quintana382601f2010-03-25 12:25:10 -0700503 if (response == null) throw new IllegalArgumentException("response is null");
504 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700505 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700506 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800507
508 cancelNotification(getSigninRequiredNotificationId(account));
509 synchronized(mCredentialsPermissionNotificationIds) {
510 for (Pair<Pair<Account, String>, Integer> pair:
511 mCredentialsPermissionNotificationIds.keySet()) {
512 if (account.equals(pair.first.first)) {
513 int id = mCredentialsPermissionNotificationIds.get(pair);
514 cancelNotification(id);
515 }
516 }
517 }
518
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700519 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700520 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700521 } finally {
522 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700523 }
Fred Quintana60307342009-03-24 22:48:12 -0700524 }
525
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700526 private class RemoveAccountSession extends Session {
527 final Account mAccount;
528 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
Fred Quintana8570f742010-02-18 10:32:54 -0800529 super(response, account.type, false /* expectActivityLaunch */,
530 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700531 mAccount = account;
532 }
533
534 protected String toDebugString(long now) {
535 return super.toDebugString(now) + ", removeAccount"
536 + ", account " + mAccount;
537 }
538
539 public void run() throws RemoteException {
540 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
541 }
542
543 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700544 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
545 && !result.containsKey(AccountManager.KEY_INTENT)) {
546 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700547 if (removalAllowed) {
548 removeAccount(mAccount);
549 }
550 IAccountManagerResponse response = getResponseAndClose();
551 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800552 if (Log.isLoggable(TAG, Log.VERBOSE)) {
553 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
554 + response);
555 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700556 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700557 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700558 try {
559 response.onResult(result2);
560 } catch (RemoteException e) {
561 // ignore
562 }
563 }
564 }
565 super.onResult(result);
566 }
567 }
568
Fred Quintana56285a62010-12-02 14:20:51 -0800569 protected void removeAccount(Account account) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700570 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
571 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
572 new String[]{account.name, account.type});
Fred Quintana56285a62010-12-02 14:20:51 -0800573 removeAccountFromCache(account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700574 sendAccountsChangedBroadcast();
575 }
576
Fred Quintanaa698f422009-04-08 19:14:54 -0700577 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800578 if (Log.isLoggable(TAG, Log.VERBOSE)) {
579 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
580 + ", caller's uid " + Binder.getCallingUid()
581 + ", pid " + Binder.getCallingPid());
582 }
Fred Quintana382601f2010-03-25 12:25:10 -0700583 if (accountType == null) throw new IllegalArgumentException("accountType is null");
584 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800585 checkManageAccountsOrUseCredentialsPermissions();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700586 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700587 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700588 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
589 db.beginTransaction();
590 try {
591 invalidateAuthToken(db, accountType, authToken);
592 db.setTransactionSuccessful();
593 } finally {
594 db.endTransaction();
595 }
Fred Quintana60307342009-03-24 22:48:12 -0700596 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700597 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700598 }
599 }
600
601 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700602 if (authToken == null || accountType == null) {
603 return;
604 }
Fred Quintana33269202009-04-20 16:05:10 -0700605 Cursor cursor = db.rawQuery(
606 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
607 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
608 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
609 + " FROM " + TABLE_ACCOUNTS
610 + " JOIN " + TABLE_AUTHTOKENS
611 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
612 + " = " + AUTHTOKENS_ACCOUNTS_ID
613 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
614 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
615 new String[]{authToken, accountType});
616 try {
617 while (cursor.moveToNext()) {
618 long authTokenId = cursor.getLong(0);
619 String accountName = cursor.getString(1);
620 String authTokenType = cursor.getString(2);
621 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana56285a62010-12-02 14:20:51 -0800622 writeAuthTokenIntoCache(new Account(accountName, accountType), authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700623 }
Fred Quintana33269202009-04-20 16:05:10 -0700624 } finally {
625 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700626 }
627 }
628
629 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700630 if (account == null || type == null) {
631 return false;
632 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700633 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700634 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
635 db.beginTransaction();
636 try {
Fred Quintana33269202009-04-20 16:05:10 -0700637 long accountId = getAccountId(db, account);
638 if (accountId < 0) {
639 return false;
640 }
641 db.delete(TABLE_AUTHTOKENS,
642 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
643 new String[]{type});
644 ContentValues values = new ContentValues();
645 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
646 values.put(AUTHTOKENS_TYPE, type);
647 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
648 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700649 db.setTransactionSuccessful();
Fred Quintana56285a62010-12-02 14:20:51 -0800650 writeAuthTokenIntoCache(account, type, authToken);
Fred Quintana60307342009-03-24 22:48:12 -0700651 return true;
652 }
653 return false;
654 } finally {
655 db.endTransaction();
656 }
657 }
658
Fred Quintanaa698f422009-04-08 19:14:54 -0700659 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800660 if (Log.isLoggable(TAG, Log.VERBOSE)) {
661 Log.v(TAG, "peekAuthToken: " + account
662 + ", authTokenType " + authTokenType
663 + ", caller's uid " + Binder.getCallingUid()
664 + ", pid " + Binder.getCallingPid());
665 }
Fred Quintana382601f2010-03-25 12:25:10 -0700666 if (account == null) throw new IllegalArgumentException("account is null");
667 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700668 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700669 long identityToken = clearCallingIdentity();
670 try {
Fred Quintana56285a62010-12-02 14:20:51 -0800671 return readAuthTokenFromCache(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700672 } finally {
673 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700674 }
Fred Quintana60307342009-03-24 22:48:12 -0700675 }
676
Fred Quintanaa698f422009-04-08 19:14:54 -0700677 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800678 if (Log.isLoggable(TAG, Log.VERBOSE)) {
679 Log.v(TAG, "setAuthToken: " + account
680 + ", authTokenType " + authTokenType
681 + ", caller's uid " + Binder.getCallingUid()
682 + ", pid " + Binder.getCallingPid());
683 }
Fred Quintana382601f2010-03-25 12:25:10 -0700684 if (account == null) throw new IllegalArgumentException("account is null");
685 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700686 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700687 long identityToken = clearCallingIdentity();
688 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700689 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700690 } finally {
691 restoreCallingIdentity(identityToken);
692 }
Fred Quintana60307342009-03-24 22:48:12 -0700693 }
694
Fred Quintanaa698f422009-04-08 19:14:54 -0700695 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -0800696 if (Log.isLoggable(TAG, Log.VERBOSE)) {
697 Log.v(TAG, "setAuthToken: " + account
698 + ", caller's uid " + Binder.getCallingUid()
699 + ", pid " + Binder.getCallingPid());
700 }
Fred Quintana382601f2010-03-25 12:25:10 -0700701 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700702 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700703 long identityToken = clearCallingIdentity();
704 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700705 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700706 } finally {
707 restoreCallingIdentity(identityToken);
708 }
Fred Quintana60307342009-03-24 22:48:12 -0700709 }
710
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700711 private void setPasswordInDB(Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700712 if (account == null) {
713 return;
714 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800715 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
716 db.beginTransaction();
717 try {
718 final ContentValues values = new ContentValues();
719 values.put(ACCOUNTS_PASSWORD, password);
720 final long accountId = getAccountId(db, account);
721 if (accountId >= 0) {
722 final String[] argsAccountId = {String.valueOf(accountId)};
723 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
724 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
725 db.setTransactionSuccessful();
726 }
727 } finally {
728 db.endTransaction();
729 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700730 sendAccountsChangedBroadcast();
731 }
732
Fred Quintana33269202009-04-20 16:05:10 -0700733 private void sendAccountsChangedBroadcast() {
Fred Quintana56285a62010-12-02 14:20:51 -0800734 Log.i(TAG, "the accounts changed, sending broadcast of "
735 + ACCOUNTS_CHANGED_INTENT.getAction());
Fred Quintana33269202009-04-20 16:05:10 -0700736 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
737 }
738
Fred Quintanaa698f422009-04-08 19:14:54 -0700739 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800740 if (Log.isLoggable(TAG, Log.VERBOSE)) {
741 Log.v(TAG, "clearPassword: " + account
742 + ", caller's uid " + Binder.getCallingUid()
743 + ", pid " + Binder.getCallingPid());
744 }
Fred Quintana382601f2010-03-25 12:25:10 -0700745 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700746 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700747 long identityToken = clearCallingIdentity();
748 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700749 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700750 } finally {
751 restoreCallingIdentity(identityToken);
752 }
Fred Quintana60307342009-03-24 22:48:12 -0700753 }
754
Fred Quintanaa698f422009-04-08 19:14:54 -0700755 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -0800756 if (Log.isLoggable(TAG, Log.VERBOSE)) {
757 Log.v(TAG, "setUserData: " + account
758 + ", key " + key
759 + ", caller's uid " + Binder.getCallingUid()
760 + ", pid " + Binder.getCallingPid());
761 }
Fred Quintana382601f2010-03-25 12:25:10 -0700762 if (key == null) throw new IllegalArgumentException("key is null");
763 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700764 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700765 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700766 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700767 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700768 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700769 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700770 }
771 }
772
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700773 private void writeUserdataIntoDatabase(Account account, String key, String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700774 if (account == null || key == null) {
775 return;
776 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700777 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
778 db.beginTransaction();
779 try {
780 long accountId = getAccountId(db, account);
781 if (accountId < 0) {
782 return;
783 }
784 long extrasId = getExtrasId(db, accountId, key);
785 if (extrasId < 0 ) {
786 extrasId = insertExtra(db, accountId, key, value);
787 if (extrasId < 0) {
788 return;
789 }
790 } else {
791 ContentValues values = new ContentValues();
792 values.put(EXTRAS_VALUE, value);
793 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
794 return;
795 }
796
797 }
798 db.setTransactionSuccessful();
Fred Quintana56285a62010-12-02 14:20:51 -0800799 writeUserDataIntoCache(account, key, value);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700800 } finally {
801 db.endTransaction();
802 }
803 }
804
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700805 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -0800806 if (result == null) {
807 Log.e(TAG, "the result is unexpectedly null", new Exception());
808 }
809 if (Log.isLoggable(TAG, Log.VERBOSE)) {
810 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
811 + response);
812 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700813 try {
814 response.onResult(result);
815 } catch (RemoteException e) {
816 // if the caller is dead then there is no one to care about remote
817 // exceptions
818 if (Log.isLoggable(TAG, Log.VERBOSE)) {
819 Log.v(TAG, "failure while notifying response", e);
820 }
821 }
822 }
823
Costin Manolache5f383ad92010-12-02 16:44:46 -0800824 void getAuthTokenLabel(final IAccountManagerResponse response,
825 final Account account, final String authTokenType) {
826 if (account == null) throw new IllegalArgumentException("account is null");
827 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
828
829 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
830
831 long identityToken = clearCallingIdentity();
832 try {
833 new Session(response, account.type, false,
834 false /* stripAuthTokenFromResult */) {
835 protected String toDebugString(long now) {
836 return super.toDebugString(now) + ", getAuthTokenLabel"
837 + ", " + account
838 + ", authTokenType " + authTokenType;
839 }
840
841 public void run() throws RemoteException {
842 mAuthenticator.getAuthTokenLabel(this, authTokenType);
843 }
844
845 public void onResult(Bundle result) {
846 if (result != null) {
847 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
848 Bundle bundle = new Bundle();
849 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
850 super.onResult(bundle);
851 return;
852 } else {
853 super.onResult(result);
854 }
855 }
856 }.bind();
857 } finally {
858 restoreCallingIdentity(identityToken);
859 }
860 }
861
Fred Quintanaa698f422009-04-08 19:14:54 -0700862 public void getAuthToken(IAccountManagerResponse response, final Account account,
863 final String authTokenType, final boolean notifyOnAuthFailure,
864 final boolean expectActivityLaunch, final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -0800865 if (Log.isLoggable(TAG, Log.VERBOSE)) {
866 Log.v(TAG, "getAuthToken: " + account
867 + ", response " + response
868 + ", authTokenType " + authTokenType
869 + ", notifyOnAuthFailure " + notifyOnAuthFailure
870 + ", expectActivityLaunch " + expectActivityLaunch
871 + ", caller's uid " + Binder.getCallingUid()
872 + ", pid " + Binder.getCallingPid());
873 }
Fred Quintana382601f2010-03-25 12:25:10 -0700874 if (response == null) throw new IllegalArgumentException("response is null");
875 if (account == null) throw new IllegalArgumentException("account is null");
876 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700877 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
878 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -0800879 final int callerPid = Binder.getCallingPid();
880
881 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
882 mAuthenticatorCache.getServiceInfo(
883 AuthenticatorDescription.newKey(account.type));
884 final boolean customTokens =
885 authenticatorInfo != null && authenticatorInfo.type.customTokens;
886
887 // skip the check if customTokens
888 final boolean permissionGranted = customTokens ||
889 permissionIsGranted(account, authTokenType, callerUid);
890
891 if (customTokens) {
892 // let authenticator know the identity of the caller
893 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
894 loginOptions.putInt(AccountManager.KEY_CALLER_PID, callerPid);
895 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700896
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700897 long identityToken = clearCallingIdentity();
898 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700899 // if the caller has permission, do the peek. otherwise go the more expensive
900 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -0800901 if (!customTokens && permissionGranted) {
Fred Quintana56285a62010-12-02 14:20:51 -0800902 String authToken = readAuthTokenFromCache(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700903 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700904 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700905 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
906 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
907 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700908 onResult(response, result);
909 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700910 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700911 }
912
Fred Quintana8570f742010-02-18 10:32:54 -0800913 new Session(response, account.type, expectActivityLaunch,
914 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700915 protected String toDebugString(long now) {
916 if (loginOptions != null) loginOptions.keySet();
917 return super.toDebugString(now) + ", getAuthToken"
918 + ", " + account
919 + ", authTokenType " + authTokenType
920 + ", loginOptions " + loginOptions
921 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
922 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700923
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700924 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700925 // If the caller doesn't have permission then create and return the
926 // "grant permission" intent instead of the "getAuthToken" intent.
927 if (!permissionGranted) {
928 mAuthenticator.getAuthTokenLabel(this, authTokenType);
929 } else {
930 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
931 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700932 }
933
934 public void onResult(Bundle result) {
935 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700936 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700937 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
938 new AccountAuthenticatorResponse(this),
939 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700940 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700941 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700942 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700943 onResult(bundle);
944 return;
945 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700946 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700947 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700948 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
949 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700950 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700951 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700952 "the type and name should not be empty");
953 return;
954 }
Costin Manolachea40c6302010-12-13 14:50:45 -0800955 if (!customTokens) {
956 saveAuthTokenToDatabase(new Account(name, type),
957 authTokenType, authToken);
958 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700959 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700960
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700961 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700962 if (intent != null && notifyOnAuthFailure) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700963 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700964 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700965 intent);
966 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700967 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700968 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -0700969 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700970 }.bind();
971 } finally {
972 restoreCallingIdentity(identityToken);
973 }
Fred Quintana60307342009-03-24 22:48:12 -0700974 }
975
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700976 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
977 int uid = intent.getIntExtra(
978 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
979 String authTokenType = intent.getStringExtra(
980 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
981 String authTokenLabel = intent.getStringExtra(
982 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
983
984 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
985 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -0700986 final String titleAndSubtitle =
987 mContext.getString(R.string.permission_request_notification_with_subtitle,
988 account.name);
989 final int index = titleAndSubtitle.indexOf('\n');
990 final String title = titleAndSubtitle.substring(0, index);
991 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700992 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -0700993 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700994 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -0800995 installNotification(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700996 }
997
Costin Manolache5f383ad92010-12-02 16:44:46 -0800998 String getAccountLabel(String accountType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700999 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
Costin Manolache5f383ad92010-12-02 16:44:46 -08001000 mAuthenticatorCache.getServiceInfo(
1001 AuthenticatorDescription.newKey(accountType));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001002 if (serviceInfo == null) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001003 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001004 }
1005
1006 final Context authContext;
1007 try {
1008 authContext = mContext.createPackageContext(
Costin Manolache5f383ad92010-12-02 16:44:46 -08001009 serviceInfo.type.packageName, 0);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001010 } catch (PackageManager.NameNotFoundException e) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001011 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001012 }
Costin Manolache5f383ad92010-12-02 16:44:46 -08001013 return authContext.getString(serviceInfo.type.labelId);
1014 }
1015
1016 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1017 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001018
1019 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001020 intent.addCategory(
1021 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001022
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001023 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001024 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1025 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001026 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001027
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001028 return intent;
1029 }
1030
1031 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1032 int uid) {
1033 Integer id;
1034 synchronized(mCredentialsPermissionNotificationIds) {
1035 final Pair<Pair<Account, String>, Integer> key =
1036 new Pair<Pair<Account, String>, Integer>(
1037 new Pair<Account, String>(account, authTokenType), uid);
1038 id = mCredentialsPermissionNotificationIds.get(key);
1039 if (id == null) {
1040 id = mNotificationIds.incrementAndGet();
1041 mCredentialsPermissionNotificationIds.put(key, id);
1042 }
1043 }
1044 return id;
1045 }
1046
1047 private Integer getSigninRequiredNotificationId(Account account) {
1048 Integer id;
1049 synchronized(mSigninRequiredNotificationIds) {
1050 id = mSigninRequiredNotificationIds.get(account);
1051 if (id == null) {
1052 id = mNotificationIds.incrementAndGet();
1053 mSigninRequiredNotificationIds.put(account, id);
1054 }
1055 }
1056 return id;
1057 }
1058
Fred Quintana33269202009-04-20 16:05:10 -07001059 public void addAcount(final IAccountManagerResponse response, final String accountType,
1060 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -07001061 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintana56285a62010-12-02 14:20:51 -08001062 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1063 Log.v(TAG, "addAccount: accountType " + accountType
1064 + ", response " + response
1065 + ", authTokenType " + authTokenType
1066 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1067 + ", expectActivityLaunch " + expectActivityLaunch
1068 + ", caller's uid " + Binder.getCallingUid()
1069 + ", pid " + Binder.getCallingPid());
1070 }
Fred Quintana382601f2010-03-25 12:25:10 -07001071 if (response == null) throw new IllegalArgumentException("response is null");
1072 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001073 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001074 long identityToken = clearCallingIdentity();
1075 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001076 new Session(response, accountType, expectActivityLaunch,
1077 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001078 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001079 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001080 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001081 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001082
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001083 protected String toDebugString(long now) {
1084 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001085 + ", accountType " + accountType
1086 + ", requiredFeatures "
1087 + (requiredFeatures != null
1088 ? TextUtils.join(",", requiredFeatures)
1089 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001090 }
1091 }.bind();
1092 } finally {
1093 restoreCallingIdentity(identityToken);
1094 }
Fred Quintana60307342009-03-24 22:48:12 -07001095 }
1096
Fred Quintanaa698f422009-04-08 19:14:54 -07001097 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001098 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001099 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1100 Log.v(TAG, "confirmCredentials: " + account
1101 + ", response " + response
1102 + ", expectActivityLaunch " + expectActivityLaunch
1103 + ", caller's uid " + Binder.getCallingUid()
1104 + ", pid " + Binder.getCallingPid());
1105 }
Fred Quintana382601f2010-03-25 12:25:10 -07001106 if (response == null) throw new IllegalArgumentException("response is null");
1107 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001108 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001109 long identityToken = clearCallingIdentity();
1110 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001111 new Session(response, account.type, expectActivityLaunch,
1112 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001113 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001114 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001115 }
1116 protected String toDebugString(long now) {
1117 return super.toDebugString(now) + ", confirmCredentials"
1118 + ", " + account;
1119 }
1120 }.bind();
1121 } finally {
1122 restoreCallingIdentity(identityToken);
1123 }
Fred Quintana60307342009-03-24 22:48:12 -07001124 }
1125
Fred Quintanaa698f422009-04-08 19:14:54 -07001126 public void updateCredentials(IAccountManagerResponse response, final Account account,
1127 final String authTokenType, final boolean expectActivityLaunch,
1128 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001129 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1130 Log.v(TAG, "updateCredentials: " + account
1131 + ", response " + response
1132 + ", authTokenType " + authTokenType
1133 + ", expectActivityLaunch " + expectActivityLaunch
1134 + ", caller's uid " + Binder.getCallingUid()
1135 + ", pid " + Binder.getCallingPid());
1136 }
Fred Quintana382601f2010-03-25 12:25:10 -07001137 if (response == null) throw new IllegalArgumentException("response is null");
1138 if (account == null) throw new IllegalArgumentException("account is null");
1139 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001140 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001141 long identityToken = clearCallingIdentity();
1142 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001143 new Session(response, account.type, expectActivityLaunch,
1144 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001145 public void run() throws RemoteException {
1146 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1147 }
1148 protected String toDebugString(long now) {
1149 if (loginOptions != null) loginOptions.keySet();
1150 return super.toDebugString(now) + ", updateCredentials"
1151 + ", " + account
1152 + ", authTokenType " + authTokenType
1153 + ", loginOptions " + loginOptions;
1154 }
1155 }.bind();
1156 } finally {
1157 restoreCallingIdentity(identityToken);
1158 }
Fred Quintana60307342009-03-24 22:48:12 -07001159 }
1160
Fred Quintanaa698f422009-04-08 19:14:54 -07001161 public void editProperties(IAccountManagerResponse response, final String accountType,
1162 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001163 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1164 Log.v(TAG, "editProperties: accountType " + accountType
1165 + ", response " + response
1166 + ", expectActivityLaunch " + expectActivityLaunch
1167 + ", caller's uid " + Binder.getCallingUid()
1168 + ", pid " + Binder.getCallingPid());
1169 }
Fred Quintana382601f2010-03-25 12:25:10 -07001170 if (response == null) throw new IllegalArgumentException("response is null");
1171 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001172 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001173 long identityToken = clearCallingIdentity();
1174 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001175 new Session(response, accountType, expectActivityLaunch,
1176 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001177 public void run() throws RemoteException {
1178 mAuthenticator.editProperties(this, mAccountType);
1179 }
1180 protected String toDebugString(long now) {
1181 return super.toDebugString(now) + ", editProperties"
1182 + ", accountType " + accountType;
1183 }
1184 }.bind();
1185 } finally {
1186 restoreCallingIdentity(identityToken);
1187 }
Fred Quintana60307342009-03-24 22:48:12 -07001188 }
1189
Fred Quintana33269202009-04-20 16:05:10 -07001190 private class GetAccountsByTypeAndFeatureSession extends Session {
1191 private final String[] mFeatures;
1192 private volatile Account[] mAccountsOfType = null;
1193 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1194 private volatile int mCurrentAccount = 0;
1195
1196 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
1197 String type, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -08001198 super(response, type, false /* expectActivityLaunch */,
1199 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001200 mFeatures = features;
1201 }
1202
1203 public void run() throws RemoteException {
Fred Quintana56285a62010-12-02 14:20:51 -08001204 mAccountsOfType = getAccountsByTypeFromCache(mAccountType);
Fred Quintana33269202009-04-20 16:05:10 -07001205 // check whether each account matches the requested features
1206 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1207 mCurrentAccount = 0;
1208
1209 checkAccount();
1210 }
1211
1212 public void checkAccount() {
1213 if (mCurrentAccount >= mAccountsOfType.length) {
1214 sendResult();
1215 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001216 }
Fred Quintana33269202009-04-20 16:05:10 -07001217
Fred Quintana29e94b82010-03-10 12:11:51 -08001218 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1219 if (accountAuthenticator == null) {
1220 // It is possible that the authenticator has died, which is indicated by
1221 // mAuthenticator being set to null. If this happens then just abort.
1222 // There is no need to send back a result or error in this case since
1223 // that already happened when mAuthenticator was cleared.
1224 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1225 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1226 + " connected to the authenticator, " + toDebugString());
1227 }
1228 return;
1229 }
Fred Quintana33269202009-04-20 16:05:10 -07001230 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001231 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001232 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001233 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001234 }
1235 }
1236
1237 public void onResult(Bundle result) {
1238 mNumResults++;
1239 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001240 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001241 return;
1242 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001243 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001244 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1245 }
1246 mCurrentAccount++;
1247 checkAccount();
1248 }
1249
1250 public void sendResult() {
1251 IAccountManagerResponse response = getResponseAndClose();
1252 if (response != null) {
1253 try {
1254 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1255 for (int i = 0; i < accounts.length; i++) {
1256 accounts[i] = mAccountsWithFeatures.get(i);
1257 }
Fred Quintana56285a62010-12-02 14:20:51 -08001258 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1259 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1260 + response);
1261 }
Fred Quintana33269202009-04-20 16:05:10 -07001262 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001263 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001264 response.onResult(result);
1265 } catch (RemoteException e) {
1266 // 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 }
1270 }
1271 }
1272 }
1273
1274
1275 protected String toDebugString(long now) {
1276 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1277 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1278 }
1279 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001280
1281 public Account[] getAccounts(String type) {
Fred Quintana56285a62010-12-02 14:20:51 -08001282 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1283 Log.v(TAG, "getAccounts: accountType " + type
1284 + ", caller's uid " + Binder.getCallingUid()
1285 + ", pid " + Binder.getCallingPid());
1286 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001287 checkReadAccountsPermission();
1288 long identityToken = clearCallingIdentity();
1289 try {
Fred Quintana56285a62010-12-02 14:20:51 -08001290 return getAccountsByTypeFromCache(type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001291 } finally {
1292 restoreCallingIdentity(identityToken);
1293 }
1294 }
1295
1296 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001297 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001298 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1299 Log.v(TAG, "getAccounts: accountType " + type
1300 + ", response " + response
1301 + ", features " + stringArrayToString(features)
1302 + ", caller's uid " + Binder.getCallingUid()
1303 + ", pid " + Binder.getCallingPid());
1304 }
Fred Quintana382601f2010-03-25 12:25:10 -07001305 if (response == null) throw new IllegalArgumentException("response is null");
1306 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001307 checkReadAccountsPermission();
Fred Quintana33269202009-04-20 16:05:10 -07001308 long identityToken = clearCallingIdentity();
1309 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001310 if (features == null || features.length == 0) {
Fred Quintana56285a62010-12-02 14:20:51 -08001311 Account[] accounts = getAccountsByTypeFromCache(type);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001312 Bundle result = new Bundle();
1313 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1314 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001315 return;
1316 }
Fred Quintana33269202009-04-20 16:05:10 -07001317 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1318 } finally {
1319 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001320 }
1321 }
1322
Fred Quintana60307342009-03-24 22:48:12 -07001323 private long getAccountId(SQLiteDatabase db, Account account) {
1324 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001325 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001326 try {
1327 if (cursor.moveToNext()) {
1328 return cursor.getLong(0);
1329 }
1330 return -1;
1331 } finally {
1332 cursor.close();
1333 }
1334 }
1335
1336 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1337 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1338 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1339 new String[]{key}, null, null, null);
1340 try {
1341 if (cursor.moveToNext()) {
1342 return cursor.getLong(0);
1343 }
1344 return -1;
1345 } finally {
1346 cursor.close();
1347 }
1348 }
1349
Fred Quintanaa698f422009-04-08 19:14:54 -07001350 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001351 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001352 IAccountManagerResponse mResponse;
1353 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001354 final boolean mExpectActivityLaunch;
1355 final long mCreationTime;
1356
Fred Quintana33269202009-04-20 16:05:10 -07001357 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001358 private int mNumRequestContinued = 0;
1359 private int mNumErrors = 0;
1360
Fred Quintana60307342009-03-24 22:48:12 -07001361
1362 IAccountAuthenticator mAuthenticator = null;
1363
Fred Quintana8570f742010-02-18 10:32:54 -08001364 private final boolean mStripAuthTokenFromResult;
1365
Fred Quintanaa698f422009-04-08 19:14:54 -07001366 public Session(IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001367 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001368 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001369 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001370 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana8570f742010-02-18 10:32:54 -08001371 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001372 mResponse = response;
1373 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001374 mExpectActivityLaunch = expectActivityLaunch;
1375 mCreationTime = SystemClock.elapsedRealtime();
1376 synchronized (mSessions) {
1377 mSessions.put(toString(), this);
1378 }
1379 try {
1380 response.asBinder().linkToDeath(this, 0 /* flags */);
1381 } catch (RemoteException e) {
1382 mResponse = null;
1383 binderDied();
1384 }
Fred Quintana60307342009-03-24 22:48:12 -07001385 }
1386
Fred Quintanaa698f422009-04-08 19:14:54 -07001387 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001388 if (mResponse == null) {
1389 // this session has already been closed
1390 return null;
1391 }
Fred Quintana60307342009-03-24 22:48:12 -07001392 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001393 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001394 return response;
1395 }
1396
Fred Quintanaa698f422009-04-08 19:14:54 -07001397 private void close() {
1398 synchronized (mSessions) {
1399 if (mSessions.remove(toString()) == null) {
1400 // the session was already closed, so bail out now
1401 return;
1402 }
1403 }
1404 if (mResponse != null) {
1405 // stop listening for response deaths
1406 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1407
1408 // clear this so that we don't accidentally send any further results
1409 mResponse = null;
1410 }
1411 cancelTimeout();
1412 unbind();
1413 }
1414
1415 public void binderDied() {
1416 mResponse = null;
1417 close();
1418 }
1419
1420 protected String toDebugString() {
1421 return toDebugString(SystemClock.elapsedRealtime());
1422 }
1423
1424 protected String toDebugString(long now) {
1425 return "Session: expectLaunch " + mExpectActivityLaunch
1426 + ", connected " + (mAuthenticator != null)
1427 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1428 + "/" + mNumErrors + ")"
1429 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1430 }
1431
Fred Quintana60307342009-03-24 22:48:12 -07001432 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001433 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1434 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1435 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001436 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001437 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001438 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001439 }
1440 }
1441
1442 private void unbind() {
1443 if (mAuthenticator != null) {
1444 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001445 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001446 }
1447 }
1448
1449 public void scheduleTimeout() {
1450 mMessageHandler.sendMessageDelayed(
1451 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1452 }
1453
1454 public void cancelTimeout() {
1455 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1456 }
1457
Fred Quintanab839afc2009-10-14 15:57:28 -07001458 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001459 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001460 try {
1461 run();
1462 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001463 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001464 "remote exception");
1465 }
Fred Quintana60307342009-03-24 22:48:12 -07001466 }
1467
Fred Quintanab839afc2009-10-14 15:57:28 -07001468 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001469 mAuthenticator = null;
1470 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001471 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001472 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001473 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001474 }
1475 }
1476
Fred Quintanab839afc2009-10-14 15:57:28 -07001477 public abstract void run() throws RemoteException;
1478
Fred Quintana60307342009-03-24 22:48:12 -07001479 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001480 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001481 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001482 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001483 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001484 }
1485 }
1486
Fred Quintanaa698f422009-04-08 19:14:54 -07001487 public void onResult(Bundle result) {
1488 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001489 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1490 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1491 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001492 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1493 Account account = new Account(accountName, accountType);
1494 cancelNotification(getSigninRequiredNotificationId(account));
1495 }
Fred Quintana60307342009-03-24 22:48:12 -07001496 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001497 IAccountManagerResponse response;
1498 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001499 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001500 response = mResponse;
1501 } else {
1502 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001503 }
Fred Quintana60307342009-03-24 22:48:12 -07001504 if (response != null) {
1505 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001506 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001507 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1508 Log.v(TAG, getClass().getSimpleName()
1509 + " calling onError() on response " + response);
1510 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001511 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001512 "null bundle returned");
1513 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001514 if (mStripAuthTokenFromResult) {
1515 result.remove(AccountManager.KEY_AUTHTOKEN);
1516 }
Fred Quintana56285a62010-12-02 14:20:51 -08001517 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1518 Log.v(TAG, getClass().getSimpleName()
1519 + " calling onResult() on response " + response);
1520 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001521 response.onResult(result);
1522 }
Fred Quintana60307342009-03-24 22:48:12 -07001523 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001524 // if the caller is dead then there is no one to care about remote exceptions
1525 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1526 Log.v(TAG, "failure while notifying response", e);
1527 }
Fred Quintana60307342009-03-24 22:48:12 -07001528 }
1529 }
1530 }
Fred Quintana60307342009-03-24 22:48:12 -07001531
Fred Quintanaa698f422009-04-08 19:14:54 -07001532 public void onRequestContinued() {
1533 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001534 }
1535
1536 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001537 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001538 IAccountManagerResponse response = getResponseAndClose();
1539 if (response != null) {
1540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001541 Log.v(TAG, getClass().getSimpleName()
1542 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001543 }
1544 try {
1545 response.onError(errorCode, errorMessage);
1546 } catch (RemoteException e) {
1547 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1548 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1549 }
1550 }
1551 } else {
1552 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1553 Log.v(TAG, "Session.onError: already closed");
1554 }
Fred Quintana60307342009-03-24 22:48:12 -07001555 }
1556 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001557
1558 /**
1559 * find the component name for the authenticator and initiate a bind
1560 * if no authenticator or the bind fails then return false, otherwise return true
1561 */
1562 private boolean bindToAuthenticator(String authenticatorType) {
1563 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1564 mAuthenticatorCache.getServiceInfo(
1565 AuthenticatorDescription.newKey(authenticatorType));
1566 if (authenticatorInfo == null) {
1567 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1568 Log.v(TAG, "there is no authenticator for " + authenticatorType
1569 + ", bailing out");
1570 }
1571 return false;
1572 }
1573
1574 Intent intent = new Intent();
1575 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1576 intent.setComponent(authenticatorInfo.componentName);
1577 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1578 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1579 }
1580 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1581 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1582 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1583 }
1584 return false;
1585 }
1586
1587
1588 return true;
1589 }
Fred Quintana60307342009-03-24 22:48:12 -07001590 }
1591
1592 private class MessageHandler extends Handler {
1593 MessageHandler(Looper looper) {
1594 super(looper);
1595 }
Costin Manolache3348f142009-09-29 18:58:36 -07001596
Fred Quintana60307342009-03-24 22:48:12 -07001597 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001598 switch (msg.what) {
1599 case MESSAGE_TIMED_OUT:
1600 Session session = (Session)msg.obj;
1601 session.onTimedOut();
1602 break;
1603
1604 default:
1605 throw new IllegalStateException("unhandled message: " + msg.what);
1606 }
1607 }
1608 }
1609
Oscar Montemayora8529f62009-11-18 10:14:20 -08001610 private static String getDatabaseName() {
1611 if(Environment.isEncryptedFilesystemEnabled()) {
1612 // Hard-coded path in case of encrypted file system
1613 return Environment.getSystemSecureDirectory().getPath() + File.separator + DATABASE_NAME;
1614 } else {
1615 // Regular path in case of non-encrypted file system
1616 return DATABASE_NAME;
1617 }
1618 }
1619
Fred Quintana60307342009-03-24 22:48:12 -07001620 private class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001621
Fred Quintana60307342009-03-24 22:48:12 -07001622 public DatabaseHelper(Context context) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001623 super(context, AccountManagerService.getDatabaseName(), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001624 }
1625
1626 @Override
1627 public void onCreate(SQLiteDatabase db) {
1628 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1629 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1630 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1631 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1632 + ACCOUNTS_PASSWORD + " TEXT, "
1633 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1634
1635 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1636 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1637 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1638 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1639 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1640 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1641
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001642 createGrantsTable(db);
1643
Fred Quintana60307342009-03-24 22:48:12 -07001644 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1645 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1646 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1647 + EXTRAS_KEY + " TEXT NOT NULL, "
1648 + EXTRAS_VALUE + " TEXT, "
1649 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1650
1651 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1652 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1653 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001654
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001655 createAccountsDeletionTrigger(db);
1656 }
1657
1658 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001659 db.execSQL(""
1660 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1661 + " BEGIN"
1662 + " DELETE FROM " + TABLE_AUTHTOKENS
1663 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1664 + " DELETE FROM " + TABLE_EXTRAS
1665 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001666 + " DELETE FROM " + TABLE_GRANTS
1667 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001668 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001669 }
1670
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001671 private void createGrantsTable(SQLiteDatabase db) {
1672 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1673 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1674 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1675 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1676 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1677 + "," + GRANTS_GRANTEE_UID + "))");
1678 }
1679
Fred Quintana60307342009-03-24 22:48:12 -07001680 @Override
1681 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001682 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001683
Fred Quintanaa698f422009-04-08 19:14:54 -07001684 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001685 // no longer need to do anything since the work is done
1686 // when upgrading from version 2
1687 oldVersion++;
1688 }
1689
1690 if (oldVersion == 2) {
1691 createGrantsTable(db);
1692 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1693 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001694 oldVersion++;
1695 }
Costin Manolache3348f142009-09-29 18:58:36 -07001696
1697 if (oldVersion == 3) {
1698 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1699 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1700 oldVersion++;
1701 }
Fred Quintana60307342009-03-24 22:48:12 -07001702 }
1703
1704 @Override
1705 public void onOpen(SQLiteDatabase db) {
1706 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1707 }
1708 }
1709
1710 private void setMetaValue(String key, String value) {
1711 ContentValues values = new ContentValues();
1712 values.put(META_KEY, key);
1713 values.put(META_VALUE, value);
1714 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1715 }
1716
1717 private String getMetaValue(String key) {
1718 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1719 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1720 try {
1721 if (c.moveToNext()) {
1722 return c.getString(0);
1723 }
1724 return null;
1725 } finally {
1726 c.close();
1727 }
1728 }
1729
1730 private class SimWatcher extends BroadcastReceiver {
1731 public SimWatcher(Context context) {
1732 // Re-scan the SIM card when the SIM state changes, and also if
1733 // the disk recovers from a full state (we may have failed to handle
1734 // things properly while the disk was full).
1735 final IntentFilter filter = new IntentFilter();
1736 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1737 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1738 context.registerReceiver(this, filter);
1739 }
Costin Manolache3348f142009-09-29 18:58:36 -07001740
Fred Quintana60307342009-03-24 22:48:12 -07001741 /**
1742 * Compare the IMSI to the one stored in the login service's
1743 * database. If they differ, erase all passwords and
1744 * authtokens (and store the new IMSI).
1745 */
1746 @Override
1747 public void onReceive(Context context, Intent intent) {
Doug Zongker885cfc232009-10-21 16:52:44 -07001748 // Check IMSI on every update; nothing happens if the IMSI
1749 // is missing or unchanged.
1750 TelephonyManager telephonyManager =
1751 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1752 if (telephonyManager == null) {
1753 Log.w(TAG, "failed to get TelephonyManager");
1754 return;
1755 }
1756 String imsi = telephonyManager.getSubscriberId();
1757
1758 // If the subscriber ID is an empty string, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001759 if (TextUtils.isEmpty(imsi)) return;
1760
Doug Zongker885cfc232009-10-21 16:52:44 -07001761 // If the current IMSI matches what's stored, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001762 String storedImsi = getMetaValue("imsi");
Fred Quintana60307342009-03-24 22:48:12 -07001763 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1764 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1765 }
Doug Zongker885cfc232009-10-21 16:52:44 -07001766 if (imsi.equals(storedImsi)) return;
1767
1768 // If a CDMA phone is unprovisioned, getSubscriberId()
1769 // will return a different value, but we *don't* erase the
1770 // passwords. We only erase them if it has a different
1771 // subscriber ID once it's provisioned.
1772 if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
1773 IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
1774 if (service == null) {
1775 Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
1776 return;
1777 }
1778 ITelephony telephony = ITelephony.Stub.asInterface(service);
1779 if (telephony == null) {
1780 Log.w(TAG, "failed to get ITelephony interface");
1781 return;
1782 }
1783 boolean needsProvisioning;
1784 try {
Wink Saville4d8ae852010-05-24 17:50:32 -07001785 needsProvisioning = telephony.needsOtaServiceProvisioning();
Doug Zongker885cfc232009-10-21 16:52:44 -07001786 } catch (RemoteException e) {
1787 Log.w(TAG, "exception while checking provisioning", e);
1788 // default to NOT wiping out the passwords
1789 needsProvisioning = true;
1790 }
1791 if (needsProvisioning) {
1792 // if the phone needs re-provisioning, don't do anything.
1793 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1794 Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
1795 storedImsi);
1796 }
1797 return;
1798 }
1799 }
Fred Quintana60307342009-03-24 22:48:12 -07001800
jsh5b462472009-09-01 16:13:55 -07001801 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001802 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1803 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001804 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1805 db.beginTransaction();
1806 try {
1807 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1808 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Fred Quintana60307342009-03-24 22:48:12 -07001809 db.setTransactionSuccessful();
1810 } finally {
1811 db.endTransaction();
1812 }
Fred Quintana743dfad2010-07-15 10:59:25 -07001813 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001814 }
1815 setMetaValue("imsi", imsi);
1816 }
1817 }
1818
1819 public IBinder onBind(Intent intent) {
1820 return asBinder();
1821 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001822
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001823 /**
1824 * Searches array of arguments for the specified string
1825 * @param args array of argument strings
1826 * @param value value to search for
1827 * @return true if the value is contained in the array
1828 */
1829 private static boolean scanArgs(String[] args, String value) {
1830 if (args != null) {
1831 for (String arg : args) {
1832 if (value.equals(arg)) {
1833 return true;
1834 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001835 }
1836 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001837 return false;
1838 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001839
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001840 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1841 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001842
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001843 if (isCheckinRequest) {
1844 // This is a checkin request. *Only* upload the account types and the count of each.
1845 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1846
1847 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1848 null, null, ACCOUNTS_TYPE, null, null);
1849 try {
1850 while (cursor.moveToNext()) {
1851 // print type,count
1852 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1853 }
1854 } finally {
1855 if (cursor != null) {
1856 cursor.close();
1857 }
1858 }
1859 } else {
Fred Quintana56285a62010-12-02 14:20:51 -08001860 Account[] accounts = getAccountsByTypeFromCache(null /* type */);
Fred Quintana307da1a2010-01-21 14:24:20 -08001861 fout.println("Accounts: " + accounts.length);
1862 for (Account account : accounts) {
1863 fout.println(" " + account);
1864 }
1865
1866 fout.println();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001867 synchronized (mSessions) {
1868 final long now = SystemClock.elapsedRealtime();
Fred Quintana307da1a2010-01-21 14:24:20 -08001869 fout.println("Active Sessions: " + mSessions.size());
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001870 for (Session session : mSessions.values()) {
1871 fout.println(" " + session.toDebugString(now));
1872 }
1873 }
1874
1875 fout.println();
1876 mAuthenticatorCache.dump(fd, fout, args);
1877 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001878 }
1879
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001880 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001881 long identityToken = clearCallingIdentity();
1882 try {
1883 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1884 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1885 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001886
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001887 if (intent.getComponent() != null &&
1888 GrantCredentialsPermissionActivity.class.getName().equals(
1889 intent.getComponent().getClassName())) {
1890 createNoCredentialsPermissionNotification(account, intent);
1891 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001892 final Integer notificationId = getSigninRequiredNotificationId(account);
1893 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001894 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1895 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001896 final String notificationTitleFormat =
1897 mContext.getText(R.string.notification_title).toString();
1898 n.setLatestEventInfo(mContext,
1899 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001900 message, PendingIntent.getActivity(
1901 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -08001902 installNotification(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001903 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001904 } finally {
1905 restoreCallingIdentity(identityToken);
1906 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001907 }
1908
Fred Quintana56285a62010-12-02 14:20:51 -08001909 protected void installNotification(final int notificationId, final Notification n) {
1910 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
1911 .notify(notificationId, n);
1912 }
1913
1914 protected void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001915 long identityToken = clearCallingIdentity();
1916 try {
1917 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001918 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001919 } finally {
1920 restoreCallingIdentity(identityToken);
1921 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001922 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001923
Fred Quintanab38eb142010-02-24 13:40:54 -08001924 /** Succeeds if any of the specified permissions are granted. */
1925 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001926 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08001927
1928 for (String perm : permissions) {
1929 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
1930 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001931 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08001932 }
1933 return;
1934 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001935 }
Fred Quintanab38eb142010-02-24 13:40:54 -08001936
1937 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08001938 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08001939 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001940 }
1941
Fred Quintana7be59642009-08-24 18:29:25 -07001942 private boolean inSystemImage(int callerUid) {
Fred Quintana56285a62010-12-02 14:20:51 -08001943 String[] packages = mPackageManager.getPackagesForUid(callerUid);
Fred Quintana7be59642009-08-24 18:29:25 -07001944 for (String name : packages) {
1945 try {
Fred Quintana56285a62010-12-02 14:20:51 -08001946 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
1947 if (packageInfo != null
1948 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07001949 return true;
1950 }
1951 } catch (PackageManager.NameNotFoundException e) {
1952 return false;
1953 }
1954 }
1955 return false;
1956 }
1957
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001958 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001959 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07001960 final boolean fromAuthenticator = account != null
1961 && hasAuthenticatorUid(account.type, callerUid);
1962 final boolean hasExplicitGrants = account != null
1963 && hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001964 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1965 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08001966 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001967 + ": is authenticator? " + fromAuthenticator
1968 + ", has explicit permission? " + hasExplicitGrants);
1969 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001970 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001971 }
1972
Fred Quintana1a231912009-10-15 11:31:30 -07001973 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001974 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1975 mAuthenticatorCache.getAllServices()) {
1976 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001977 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08001978 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001979 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001980 }
1981 }
1982 return false;
1983 }
1984
1985 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1986 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1987 return true;
1988 }
1989 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1990 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001991 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001992 final boolean permissionGranted =
1993 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -08001994 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001995 // TODO: Skip this check when running automated tests. Replace this
1996 // with a more general solution.
Fred Quintana751fdc02010-02-09 14:13:18 -08001997 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001998 + authTokenType + " by uid " + Binder.getCallingUid()
Brett Chabot3b4fcbc2011-01-09 13:41:02 -08001999 + " but ignoring since device is in test harness.");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002000 return true;
2001 }
2002 return permissionGranted;
2003 }
2004
2005 private void checkCallingUidAgainstAuthenticator(Account account) {
2006 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002007 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002008 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2009 Log.w(TAG, msg);
2010 throw new SecurityException(msg);
2011 }
2012 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2013 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2014 }
2015 }
2016
2017 private void checkAuthenticateAccountsPermission(Account account) {
2018 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2019 checkCallingUidAgainstAuthenticator(account);
2020 }
2021
2022 private void checkReadAccountsPermission() {
2023 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2024 }
2025
2026 private void checkManageAccountsPermission() {
2027 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2028 }
2029
Fred Quintanab38eb142010-02-24 13:40:54 -08002030 private void checkManageAccountsOrUseCredentialsPermissions() {
2031 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2032 Manifest.permission.USE_CREDENTIALS);
2033 }
2034
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002035 /**
2036 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2037 * <p>
2038 * Although this is public it can only be accessed via the AccountManagerService object
2039 * which is in the system. This means we don't need to protect it with permissions.
2040 * @hide
2041 */
2042 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002043 if (account == null || authTokenType == null) {
2044 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002045 return;
2046 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002047 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
2048 db.beginTransaction();
2049 try {
2050 long accountId = getAccountId(db, account);
2051 if (accountId >= 0) {
2052 ContentValues values = new ContentValues();
2053 values.put(GRANTS_ACCOUNTS_ID, accountId);
2054 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2055 values.put(GRANTS_GRANTEE_UID, uid);
2056 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2057 db.setTransactionSuccessful();
2058 }
2059 } finally {
2060 db.endTransaction();
2061 }
2062 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
2063 }
2064
2065 /**
2066 * Don't allow callers with the given uid permission to get credentials for
2067 * account/authTokenType.
2068 * <p>
2069 * Although this is public it can only be accessed via the AccountManagerService object
2070 * which is in the system. This means we don't need to protect it with permissions.
2071 * @hide
2072 */
2073 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002074 if (account == null || authTokenType == null) {
2075 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002076 return;
2077 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002078 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
2079 db.beginTransaction();
2080 try {
2081 long accountId = getAccountId(db, account);
2082 if (accountId >= 0) {
2083 db.delete(TABLE_GRANTS,
2084 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2085 + GRANTS_GRANTEE_UID + "=?",
2086 new String[]{String.valueOf(accountId), authTokenType,
2087 String.valueOf(uid)});
2088 db.setTransactionSuccessful();
2089 }
2090 } finally {
2091 db.endTransaction();
2092 }
2093 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
2094 }
Fred Quintana56285a62010-12-02 14:20:51 -08002095
2096 static final private String stringArrayToString(String[] value) {
2097 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2098 }
2099
2100 private void removeAccountFromCache(Account account) {
2101 synchronized (mCacheLock) {
2102 final Account[] oldAccountsForType = mAccountCache.get(account.type);
2103 if (oldAccountsForType != null) {
2104 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2105 for (Account curAccount : oldAccountsForType) {
2106 if (!curAccount.equals(account)) {
2107 newAccountsList.add(curAccount);
2108 }
2109 }
2110 if (newAccountsList.isEmpty()) {
2111 mAccountCache.remove(account.type);
2112 } else {
2113 Account[] newAccountsForType = new Account[newAccountsList.size()];
2114 newAccountsForType = newAccountsList.toArray(newAccountsForType);
2115 mAccountCache.put(account.type, newAccountsForType);
2116 }
2117 }
2118 mUserDataCache.remove(account);
2119 mAuthTokenCache.remove(account);
2120 }
2121 }
2122
2123 /**
2124 * This assumes that the caller has already checked that the account is not already present.
2125 */
2126 private void insertAccountIntoCache(Account account) {
2127 synchronized (mCacheLock) {
2128 Account[] accountsForType = mAccountCache.get(account.type);
2129 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2130 Account[] newAccountsForType = new Account[oldLength + 1];
2131 if (accountsForType != null) {
2132 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
2133 }
2134 newAccountsForType[oldLength] = account;
2135 mAccountCache.put(account.type, newAccountsForType);
2136 }
2137 }
2138
2139 protected Account[] getAccountsByTypeFromCache(String accountType) {
2140 synchronized (mCacheLock) {
2141 if (accountType != null) {
2142 final Account[] accounts = mAccountCache.get(accountType);
2143 if (accounts == null) {
2144 return EMPTY_ACCOUNT_ARRAY;
2145 } else {
2146 return Arrays.copyOf(accounts, accounts.length);
2147 }
2148 } else {
2149 int totalLength = 0;
2150 for (Account[] accounts : mAccountCache.values()) {
2151 totalLength += accounts.length;
2152 }
2153 if (totalLength == 0) {
2154 return EMPTY_ACCOUNT_ARRAY;
2155 }
2156 Account[] accounts = new Account[totalLength];
2157 totalLength = 0;
2158 for (Account[] accountsOfType : mAccountCache.values()) {
2159 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2160 accountsOfType.length);
2161 totalLength += accountsOfType.length;
2162 }
2163 return accounts;
2164 }
2165 }
2166 }
2167
2168 protected void writeUserDataIntoCache(Account account, String key, String value) {
2169 synchronized (mCacheLock) {
2170 HashMap<String, String> userDataForAccount = mUserDataCache.get(account);
2171 if (userDataForAccount == null) {
2172 userDataForAccount = readUserDataForAccountFromDatabase(account);
2173 mUserDataCache.put(account, userDataForAccount);
2174 }
2175 if (value == null) {
2176 userDataForAccount.remove(key);
2177 } else {
2178 userDataForAccount.put(key, value);
2179 }
2180 }
2181 }
2182
2183 protected void writeAuthTokenIntoCache(Account account, String key, String value) {
2184 synchronized (mCacheLock) {
2185 HashMap<String, String> authTokensForAccount = mAuthTokenCache.get(account);
2186 if (authTokensForAccount == null) {
2187 authTokensForAccount = readAuthTokensForAccountFromDatabase(account);
2188 mAuthTokenCache.put(account, authTokensForAccount);
2189 }
2190 if (value == null) {
2191 authTokensForAccount.remove(key);
2192 } else {
2193 authTokensForAccount.put(key, value);
2194 }
2195 }
2196 }
2197
2198 protected String readAuthTokenFromCache(Account account, String authTokenType) {
2199 synchronized (mCacheLock) {
2200 HashMap<String, String> authTokensForAccount = mAuthTokenCache.get(account);
2201 if (authTokensForAccount == null) {
2202 // need to populate the cache for this account
2203 authTokensForAccount = readAuthTokensForAccountFromDatabase(account);
2204 mAuthTokenCache.put(account, authTokensForAccount);
2205 }
2206 return authTokensForAccount.get(authTokenType);
2207 }
2208 }
2209
2210 protected String readUserDataFromCache(Account account, String key) {
2211 synchronized (mCacheLock) {
2212 HashMap<String, String> userDataForAccount = mUserDataCache.get(account);
2213 if (userDataForAccount == null) {
2214 // need to populate the cache for this account
2215 userDataForAccount = readUserDataForAccountFromDatabase(account);
2216 mUserDataCache.put(account, userDataForAccount);
2217 }
2218 return userDataForAccount.get(key);
2219 }
2220 }
2221
2222 protected HashMap<String, String> readUserDataForAccountFromDatabase(Account account) {
2223 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
2224 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
2225 Cursor cursor = db.query(TABLE_EXTRAS,
2226 COLUMNS_EXTRAS_KEY_AND_VALUE,
2227 SELECTION_USERDATA_BY_ACCOUNT,
2228 new String[]{account.name, account.type},
2229 null, null, null);
2230 try {
2231 while (cursor.moveToNext()) {
2232 final String tmpkey = cursor.getString(0);
2233 final String value = cursor.getString(1);
2234 userDataForAccount.put(tmpkey, value);
2235 }
2236 } finally {
2237 cursor.close();
2238 }
2239 return userDataForAccount;
2240 }
2241
2242 protected HashMap<String, String> readAuthTokensForAccountFromDatabase(Account account) {
2243 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
2244 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
2245 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2246 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2247 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2248 new String[]{account.name, account.type},
2249 null, null, null);
2250 try {
2251 while (cursor.moveToNext()) {
2252 final String type = cursor.getString(0);
2253 final String authToken = cursor.getString(1);
2254 authTokensForAccount.put(type, authToken);
2255 }
2256 } finally {
2257 cursor.close();
2258 }
2259 return authTokensForAccount;
2260 }
Fred Quintana60307342009-03-24 22:48:12 -07002261}