blob: 93983a6d55a93e40bf26002b8a6b0539e4639704 [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 Quintana60307342009-03-24 22:48:12 -070055import android.telephony.TelephonyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070056import android.text.TextUtils;
57import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070058import android.util.Pair;
Fred Quintana60307342009-03-24 22:48:12 -070059
Oscar Montemayora8529f62009-11-18 10:14:20 -080060import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070061import java.io.FileDescriptor;
62import java.io.PrintWriter;
63import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080064import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070066import java.util.HashMap;
Fred Quintana56285a62010-12-02 14:20:51 -080067import java.util.LinkedHashMap;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070068import java.util.concurrent.atomic.AtomicInteger;
69import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070070
Fred Quintana60307342009-03-24 22:48:12 -070071/**
72 * A system service that provides account, password, and authtoken management for all
73 * accounts on the device. Some of these calls are implemented with the help of the corresponding
74 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
75 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
76 * AccountManager accountManager =
77 * (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE)
Fred Quintana33269202009-04-20 16:05:10 -070078 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070079 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070080public class AccountManagerService
81 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080082 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -070083 private static final String TAG = "AccountManagerService";
84
85 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
86 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070087 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070088
89 private final Context mContext;
90
Fred Quintana56285a62010-12-02 14:20:51 -080091 private final PackageManager mPackageManager;
92
Fred Quintana60307342009-03-24 22:48:12 -070093 private HandlerThread mMessageThread;
94 private final MessageHandler mMessageHandler;
95
96 // Messages that can be sent on mHandler
97 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -070098
Fred Quintana56285a62010-12-02 14:20:51 -080099 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700100 private final DatabaseHelper mOpenHelper;
Fred Quintana60307342009-03-24 22:48:12 -0700101
102 private static final String TABLE_ACCOUNTS = "accounts";
103 private static final String ACCOUNTS_ID = "_id";
104 private static final String ACCOUNTS_NAME = "name";
105 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700106 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700107 private static final String ACCOUNTS_PASSWORD = "password";
108
109 private static final String TABLE_AUTHTOKENS = "authtokens";
110 private static final String AUTHTOKENS_ID = "_id";
111 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
112 private static final String AUTHTOKENS_TYPE = "type";
113 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
114
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700115 private static final String TABLE_GRANTS = "grants";
116 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
117 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
118 private static final String GRANTS_GRANTEE_UID = "uid";
119
Fred Quintana60307342009-03-24 22:48:12 -0700120 private static final String TABLE_EXTRAS = "extras";
121 private static final String EXTRAS_ID = "_id";
122 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
123 private static final String EXTRAS_KEY = "key";
124 private static final String EXTRAS_VALUE = "value";
125
126 private static final String TABLE_META = "meta";
127 private static final String META_KEY = "key";
128 private static final String META_VALUE = "value";
129
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700130 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
131 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700132 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700133
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700134 private static final String COUNT_OF_MATCHING_GRANTS = ""
135 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
136 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
137 + " AND " + GRANTS_GRANTEE_UID + "=?"
138 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
139 + " AND " + ACCOUNTS_NAME + "=?"
140 + " AND " + ACCOUNTS_TYPE + "=?";
141
Fred Quintana56285a62010-12-02 14:20:51 -0800142 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
143 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
144 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
145 AUTHTOKENS_AUTHTOKEN};
146
147 private static final String SELECTION_USERDATA_BY_ACCOUNT =
148 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
149 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
150
Fred Quintanaa698f422009-04-08 19:14:54 -0700151 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700152 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
153
154 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
155 mCredentialsPermissionNotificationIds =
156 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
157 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
158 new HashMap<Account, Integer>();
159 private static AtomicReference<AccountManagerService> sThis =
160 new AtomicReference<AccountManagerService>();
161
Fred Quintana31957f12009-10-21 13:43:10 -0700162 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700163
164 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700165 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700166 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
167 }
168
Fred Quintana56285a62010-12-02 14:20:51 -0800169 private final Object mCacheLock = new Object();
170 /** protected by the {@link #mCacheLock} */
171 private final HashMap<String, Account[]> mAccountCache = new HashMap<String, Account[]>();
172 /** protected by the {@link #mCacheLock} */
173 private HashMap<Account, HashMap<String, String>> mUserDataCache =
174 new HashMap<Account, HashMap<String, String>>();
175 /** protected by the {@link #mCacheLock} */
176 private HashMap<Account, HashMap<String, String>> mAuthTokenCache =
177 new HashMap<Account, HashMap<String, String>>();
178
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700179 /**
180 * This should only be called by system code. One should only call this after the service
181 * has started.
182 * @return a reference to the AccountManagerService instance
183 * @hide
184 */
185 public static AccountManagerService getSingleton() {
186 return sThis.get();
187 }
Fred Quintana60307342009-03-24 22:48:12 -0700188
Fred Quintana56285a62010-12-02 14:20:51 -0800189 public AccountManagerService(Context context) {
190 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700191 }
192
Fred Quintana56285a62010-12-02 14:20:51 -0800193 public AccountManagerService(Context context, PackageManager packageManager,
194 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700195 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800196 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700197
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800198 synchronized (mCacheLock) {
199 mOpenHelper = new DatabaseHelper(mContext);
200 }
Fred Quintana60307342009-03-24 22:48:12 -0700201
202 mMessageThread = new HandlerThread("AccountManagerService");
203 mMessageThread.start();
204 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
205
Fred Quintana56285a62010-12-02 14:20:51 -0800206 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800207 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700208
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700209 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800210
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800211 IntentFilter intentFilter = new IntentFilter();
212 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
213 intentFilter.addDataScheme("package");
214 mContext.registerReceiver(new BroadcastReceiver() {
215 @Override
216 public void onReceive(Context context1, Intent intent) {
217 purgeOldGrants();
218 }
219 }, intentFilter);
220 purgeOldGrants();
221
Fred Quintana56285a62010-12-02 14:20:51 -0800222 validateAccountsAndPopulateCache();
Fred Quintanaafa92b82009-12-01 16:27:03 -0800223 }
224
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800225 private void purgeOldGrants() {
226 synchronized (mCacheLock) {
227 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
228 final Cursor cursor = db.query(TABLE_GRANTS,
229 new String[]{GRANTS_GRANTEE_UID},
230 null, null, GRANTS_GRANTEE_UID, null, null);
231 try {
232 while (cursor.moveToNext()) {
233 final int uid = cursor.getInt(0);
234 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
235 if (packageExists) {
236 continue;
237 }
238 Log.d(TAG, "deleting grants for UID " + uid
239 + " because its package is no longer installed");
240 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
241 new String[]{Integer.toString(uid)});
242 }
243 } finally {
244 cursor.close();
245 }
246 }
247 }
248
Fred Quintana56285a62010-12-02 14:20:51 -0800249 private void validateAccountsAndPopulateCache() {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800250 synchronized (mCacheLock) {
251 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
252 boolean accountDeleted = false;
253 Cursor cursor = db.query(TABLE_ACCOUNTS,
254 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
255 null, null, null, null, null);
256 try {
Fred Quintana56285a62010-12-02 14:20:51 -0800257 mAccountCache.clear();
258 final HashMap<String, ArrayList<String>> accountNamesByType =
259 new HashMap<String, ArrayList<String>>();
260 while (cursor.moveToNext()) {
261 final long accountId = cursor.getLong(0);
262 final String accountType = cursor.getString(1);
263 final String accountName = cursor.getString(2);
264 if (mAuthenticatorCache.getServiceInfo(
265 AuthenticatorDescription.newKey(accountType)) == null) {
266 Log.d(TAG, "deleting account " + accountName + " because type "
267 + accountType + " no longer has a registered authenticator");
268 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
269 accountDeleted = true;
270 final Account account = new Account(accountName, accountType);
271 mUserDataCache.remove(account);
272 mAuthTokenCache.remove(account);
273 } else {
274 ArrayList<String> accountNames = accountNamesByType.get(accountType);
275 if (accountNames == null) {
276 accountNames = new ArrayList<String>();
277 accountNamesByType.put(accountType, accountNames);
278 }
279 accountNames.add(accountName);
280 }
281 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800282 for (HashMap.Entry<String, ArrayList<String>> cur
283 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800284 final String accountType = cur.getKey();
285 final ArrayList<String> accountNames = cur.getValue();
286 final Account[] accountsForType = new Account[accountNames.size()];
287 int i = 0;
288 for (String accountName : accountNames) {
289 accountsForType[i] = new Account(accountName, accountType);
290 ++i;
291 }
292 mAccountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800293 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800294 } finally {
295 cursor.close();
296 if (accountDeleted) {
297 sendAccountsChangedBroadcast();
298 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800299 }
300 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700301 }
302
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800303 public void onServiceChanged(AuthenticatorDescription desc, boolean removed) {
Fred Quintana56285a62010-12-02 14:20:51 -0800304 validateAccountsAndPopulateCache();
Fred Quintana60307342009-03-24 22:48:12 -0700305 }
306
Fred Quintanaa698f422009-04-08 19:14:54 -0700307 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800308 if (Log.isLoggable(TAG, Log.VERBOSE)) {
309 Log.v(TAG, "getPassword: " + account
310 + ", caller's uid " + Binder.getCallingUid()
311 + ", pid " + Binder.getCallingPid());
312 }
Fred Quintana382601f2010-03-25 12:25:10 -0700313 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700314 checkAuthenticateAccountsPermission(account);
315
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700316 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700317 try {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800318 return readPasswordInternal(account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700319 } finally {
320 restoreCallingIdentity(identityToken);
321 }
322 }
323
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800324 private String readPasswordInternal(Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700325 if (account == null) {
326 return null;
327 }
328
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800329 synchronized (mCacheLock) {
330 final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
331 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
332 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
333 new String[]{account.name, account.type}, null, null, null);
334 try {
335 if (cursor.moveToNext()) {
336 return cursor.getString(0);
337 }
338 return null;
339 } finally {
340 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700341 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700342 }
343 }
344
345 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800346 if (Log.isLoggable(TAG, Log.VERBOSE)) {
347 Log.v(TAG, "getUserData: " + account
348 + ", key " + key
349 + ", caller's uid " + Binder.getCallingUid()
350 + ", pid " + Binder.getCallingPid());
351 }
Fred Quintana382601f2010-03-25 12:25:10 -0700352 if (account == null) throw new IllegalArgumentException("account is null");
353 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700354 checkAuthenticateAccountsPermission(account);
355 long identityToken = clearCallingIdentity();
356 try {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800357 return readUserDataInternal(account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700358 } finally {
359 restoreCallingIdentity(identityToken);
360 }
361 }
362
Fred Quintana97889762009-06-15 12:29:24 -0700363 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800364 if (Log.isLoggable(TAG, Log.VERBOSE)) {
365 Log.v(TAG, "getAuthenticatorTypes: "
366 + "caller's uid " + Binder.getCallingUid()
367 + ", pid " + Binder.getCallingPid());
368 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700369 long identityToken = clearCallingIdentity();
370 try {
Fred Quintana97889762009-06-15 12:29:24 -0700371 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
372 authenticatorCollection = mAuthenticatorCache.getAllServices();
373 AuthenticatorDescription[] types =
374 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700375 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700376 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700377 : authenticatorCollection) {
378 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700379 i++;
380 }
381 return types;
382 } finally {
383 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700384 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700385 }
386
Fred Quintanaa698f422009-04-08 19:14:54 -0700387 public boolean addAccount(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800388 if (Log.isLoggable(TAG, Log.VERBOSE)) {
389 Log.v(TAG, "addAccount: " + account
390 + ", caller's uid " + Binder.getCallingUid()
391 + ", pid " + Binder.getCallingPid());
392 }
Fred Quintana382601f2010-03-25 12:25:10 -0700393 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700394 checkAuthenticateAccountsPermission(account);
395
Fred Quintana60307342009-03-24 22:48:12 -0700396 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700397 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700398 try {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800399 return addAccountInternal(account, password, extras);
Fred Quintana60307342009-03-24 22:48:12 -0700400 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700401 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700402 }
403 }
404
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800405 private boolean addAccountInternal(Account account, String password, Bundle extras) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700406 if (account == null) {
407 return false;
408 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800409 synchronized (mCacheLock) {
410 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
411 db.beginTransaction();
412 try {
413 long numMatches = DatabaseUtils.longForQuery(db,
414 "select count(*) from " + TABLE_ACCOUNTS
415 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
416 new String[]{account.name, account.type});
417 if (numMatches > 0) {
418 Log.w(TAG, "insertAccountIntoDatabase: " + account
419 + ", skipping since the account already exists");
420 return false;
421 }
422 ContentValues values = new ContentValues();
423 values.put(ACCOUNTS_NAME, account.name);
424 values.put(ACCOUNTS_TYPE, account.type);
425 values.put(ACCOUNTS_PASSWORD, password);
426 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
427 if (accountId < 0) {
428 Log.w(TAG, "insertAccountIntoDatabase: " + account
429 + ", skipping the DB insert failed");
430 return false;
431 }
432 if (extras != null) {
433 for (String key : extras.keySet()) {
434 final String value = extras.getString(key);
435 if (insertExtraLocked(db, accountId, key, value) < 0) {
436 Log.w(TAG, "insertAccountIntoDatabase: " + account
437 + ", skipping since insertExtra failed for key " + key);
438 return false;
439 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700440 }
441 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800442 db.setTransactionSuccessful();
443 insertAccountIntoCacheLocked(account);
444 } finally {
445 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700446 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800447 sendAccountsChangedBroadcast();
448 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700449 }
450 }
451
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800452 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700453 ContentValues values = new ContentValues();
454 values.put(EXTRAS_KEY, key);
455 values.put(EXTRAS_ACCOUNTS_ID, accountId);
456 values.put(EXTRAS_VALUE, value);
457 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
458 }
459
Fred Quintana3084a6f2010-01-14 18:02:03 -0800460 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800461 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800462 if (Log.isLoggable(TAG, Log.VERBOSE)) {
463 Log.v(TAG, "hasFeatures: " + account
464 + ", response " + response
465 + ", features " + stringArrayToString(features)
466 + ", caller's uid " + Binder.getCallingUid()
467 + ", pid " + Binder.getCallingPid());
468 }
Fred Quintana382601f2010-03-25 12:25:10 -0700469 if (response == null) throw new IllegalArgumentException("response is null");
470 if (account == null) throw new IllegalArgumentException("account is null");
471 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800472 checkReadAccountsPermission();
473 long identityToken = clearCallingIdentity();
474 try {
475 new TestFeaturesSession(response, account, features).bind();
476 } finally {
477 restoreCallingIdentity(identityToken);
478 }
479 }
480
481 private class TestFeaturesSession extends Session {
482 private final String[] mFeatures;
483 private final Account mAccount;
484
485 public TestFeaturesSession(IAccountManagerResponse response,
486 Account account, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -0800487 super(response, account.type, false /* expectActivityLaunch */,
488 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800489 mFeatures = features;
490 mAccount = account;
491 }
492
493 public void run() throws RemoteException {
494 try {
495 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
496 } catch (RemoteException e) {
497 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
498 }
499 }
500
501 public void onResult(Bundle result) {
502 IAccountManagerResponse response = getResponseAndClose();
503 if (response != null) {
504 try {
505 if (result == null) {
506 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
507 return;
508 }
Fred Quintana56285a62010-12-02 14:20:51 -0800509 if (Log.isLoggable(TAG, Log.VERBOSE)) {
510 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
511 + response);
512 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800513 final Bundle newResult = new Bundle();
514 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
515 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
516 response.onResult(newResult);
517 } catch (RemoteException e) {
518 // if the caller is dead then there is no one to care about remote exceptions
519 if (Log.isLoggable(TAG, Log.VERBOSE)) {
520 Log.v(TAG, "failure while notifying response", e);
521 }
522 }
523 }
524 }
525
526 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800527 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800528 + ", " + mAccount
529 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
530 }
531 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800532
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700533 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800534 if (Log.isLoggable(TAG, Log.VERBOSE)) {
535 Log.v(TAG, "removeAccount: " + account
536 + ", response " + response
537 + ", caller's uid " + Binder.getCallingUid()
538 + ", pid " + Binder.getCallingPid());
539 }
Fred Quintana382601f2010-03-25 12:25:10 -0700540 if (response == null) throw new IllegalArgumentException("response is null");
541 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700542 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700543 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800544
545 cancelNotification(getSigninRequiredNotificationId(account));
546 synchronized(mCredentialsPermissionNotificationIds) {
547 for (Pair<Pair<Account, String>, Integer> pair:
548 mCredentialsPermissionNotificationIds.keySet()) {
549 if (account.equals(pair.first.first)) {
550 int id = mCredentialsPermissionNotificationIds.get(pair);
551 cancelNotification(id);
552 }
553 }
554 }
555
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700556 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700557 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700558 } finally {
559 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700560 }
Fred Quintana60307342009-03-24 22:48:12 -0700561 }
562
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700563 private class RemoveAccountSession extends Session {
564 final Account mAccount;
565 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
Fred Quintana8570f742010-02-18 10:32:54 -0800566 super(response, account.type, false /* expectActivityLaunch */,
567 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700568 mAccount = account;
569 }
570
571 protected String toDebugString(long now) {
572 return super.toDebugString(now) + ", removeAccount"
573 + ", account " + mAccount;
574 }
575
576 public void run() throws RemoteException {
577 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
578 }
579
580 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700581 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
582 && !result.containsKey(AccountManager.KEY_INTENT)) {
583 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700584 if (removalAllowed) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800585 removeAccountInternal(mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700586 }
587 IAccountManagerResponse response = getResponseAndClose();
588 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800589 if (Log.isLoggable(TAG, Log.VERBOSE)) {
590 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
591 + response);
592 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700593 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700594 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700595 try {
596 response.onResult(result2);
597 } catch (RemoteException e) {
598 // ignore
599 }
600 }
601 }
602 super.onResult(result);
603 }
604 }
605
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800606 protected void removeAccountInternal(Account account) {
607 synchronized (mCacheLock) {
608 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
609 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
610 new String[]{account.name, account.type});
611 removeAccountFromCacheLocked(account);
612 sendAccountsChangedBroadcast();
613 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700614 }
615
Fred Quintanaa698f422009-04-08 19:14:54 -0700616 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800617 if (Log.isLoggable(TAG, Log.VERBOSE)) {
618 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
619 + ", caller's uid " + Binder.getCallingUid()
620 + ", pid " + Binder.getCallingPid());
621 }
Fred Quintana382601f2010-03-25 12:25:10 -0700622 if (accountType == null) throw new IllegalArgumentException("accountType is null");
623 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800624 checkManageAccountsOrUseCredentialsPermissions();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700625 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700626 try {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800627 synchronized (mCacheLock) {
628 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
629 db.beginTransaction();
630 try {
631 invalidateAuthTokenLocked(db, accountType, authToken);
632 db.setTransactionSuccessful();
633 } finally {
634 db.endTransaction();
635 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700636 }
Fred Quintana60307342009-03-24 22:48:12 -0700637 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700638 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700639 }
640 }
641
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800642 private void invalidateAuthTokenLocked(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700643 if (authToken == null || accountType == null) {
644 return;
645 }
Fred Quintana33269202009-04-20 16:05:10 -0700646 Cursor cursor = db.rawQuery(
647 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
648 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
649 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
650 + " FROM " + TABLE_ACCOUNTS
651 + " JOIN " + TABLE_AUTHTOKENS
652 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
653 + " = " + AUTHTOKENS_ACCOUNTS_ID
654 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
655 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
656 new String[]{authToken, accountType});
657 try {
658 while (cursor.moveToNext()) {
659 long authTokenId = cursor.getLong(0);
660 String accountName = cursor.getString(1);
661 String authTokenType = cursor.getString(2);
662 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800663 writeAuthTokenIntoCacheLocked(db, new Account(accountName, accountType),
664 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700665 }
Fred Quintana33269202009-04-20 16:05:10 -0700666 } finally {
667 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700668 }
669 }
670
671 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700672 if (account == null || type == null) {
673 return false;
674 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700675 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800676 synchronized (mCacheLock) {
677 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
678 db.beginTransaction();
679 try {
680 long accountId = getAccountIdLocked(db, account);
681 if (accountId < 0) {
682 return false;
683 }
684 db.delete(TABLE_AUTHTOKENS,
685 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
686 new String[]{type});
687 ContentValues values = new ContentValues();
688 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
689 values.put(AUTHTOKENS_TYPE, type);
690 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
691 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
692 db.setTransactionSuccessful();
693 writeAuthTokenIntoCacheLocked(db, account, type, authToken);
694 return true;
695 }
Fred Quintana33269202009-04-20 16:05:10 -0700696 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800697 } finally {
698 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -0700699 }
Fred Quintana60307342009-03-24 22:48:12 -0700700 }
701 }
702
Fred Quintanaa698f422009-04-08 19:14:54 -0700703 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800704 if (Log.isLoggable(TAG, Log.VERBOSE)) {
705 Log.v(TAG, "peekAuthToken: " + account
706 + ", authTokenType " + authTokenType
707 + ", caller's uid " + Binder.getCallingUid()
708 + ", pid " + Binder.getCallingPid());
709 }
Fred Quintana382601f2010-03-25 12:25:10 -0700710 if (account == null) throw new IllegalArgumentException("account is null");
711 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700712 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700713 long identityToken = clearCallingIdentity();
714 try {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800715 return readAuthTokenInternal(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700716 } finally {
717 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700718 }
Fred Quintana60307342009-03-24 22:48:12 -0700719 }
720
Fred Quintanaa698f422009-04-08 19:14:54 -0700721 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800722 if (Log.isLoggable(TAG, Log.VERBOSE)) {
723 Log.v(TAG, "setAuthToken: " + account
724 + ", authTokenType " + authTokenType
725 + ", caller's uid " + Binder.getCallingUid()
726 + ", pid " + Binder.getCallingPid());
727 }
Fred Quintana382601f2010-03-25 12:25:10 -0700728 if (account == null) throw new IllegalArgumentException("account is null");
729 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700730 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700731 long identityToken = clearCallingIdentity();
732 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700733 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700734 } finally {
735 restoreCallingIdentity(identityToken);
736 }
Fred Quintana60307342009-03-24 22:48:12 -0700737 }
738
Fred Quintanaa698f422009-04-08 19:14:54 -0700739 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -0800740 if (Log.isLoggable(TAG, Log.VERBOSE)) {
741 Log.v(TAG, "setAuthToken: " + 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 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700747 long identityToken = clearCallingIdentity();
748 try {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800749 setPasswordInternal(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700750 } finally {
751 restoreCallingIdentity(identityToken);
752 }
Fred Quintana60307342009-03-24 22:48:12 -0700753 }
754
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800755 private void setPasswordInternal(Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700756 if (account == null) {
757 return;
758 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800759 synchronized (mCacheLock) {
760 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
761 db.beginTransaction();
762 try {
763 final ContentValues values = new ContentValues();
764 values.put(ACCOUNTS_PASSWORD, password);
765 final long accountId = getAccountIdLocked(db, account);
766 if (accountId >= 0) {
767 final String[] argsAccountId = {String.valueOf(accountId)};
768 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
769 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Costin Manolachef5ffe892011-01-19 09:35:32 -0800770 mAuthTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800771 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -0800772 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800773 } finally {
774 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800775 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800776 sendAccountsChangedBroadcast();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800777 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700778 }
779
Fred Quintana33269202009-04-20 16:05:10 -0700780 private void sendAccountsChangedBroadcast() {
Fred Quintana56285a62010-12-02 14:20:51 -0800781 Log.i(TAG, "the accounts changed, sending broadcast of "
782 + ACCOUNTS_CHANGED_INTENT.getAction());
Fred Quintana33269202009-04-20 16:05:10 -0700783 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
784 }
785
Fred Quintanaa698f422009-04-08 19:14:54 -0700786 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800787 if (Log.isLoggable(TAG, Log.VERBOSE)) {
788 Log.v(TAG, "clearPassword: " + account
789 + ", caller's uid " + Binder.getCallingUid()
790 + ", pid " + Binder.getCallingPid());
791 }
Fred Quintana382601f2010-03-25 12:25:10 -0700792 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700793 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700794 long identityToken = clearCallingIdentity();
795 try {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800796 setPasswordInternal(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700797 } finally {
798 restoreCallingIdentity(identityToken);
799 }
Fred Quintana60307342009-03-24 22:48:12 -0700800 }
801
Fred Quintanaa698f422009-04-08 19:14:54 -0700802 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -0800803 if (Log.isLoggable(TAG, Log.VERBOSE)) {
804 Log.v(TAG, "setUserData: " + account
805 + ", key " + key
806 + ", caller's uid " + Binder.getCallingUid()
807 + ", pid " + Binder.getCallingPid());
808 }
Fred Quintana382601f2010-03-25 12:25:10 -0700809 if (key == null) throw new IllegalArgumentException("key is null");
810 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700811 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700812 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700813 try {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800814 setUserdataInternal(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700815 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700816 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700817 }
818 }
819
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800820 private void setUserdataInternal(Account account, String key, String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700821 if (account == null || key == null) {
822 return;
823 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800824 synchronized (mCacheLock) {
825 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
826 db.beginTransaction();
827 try {
828 long accountId = getAccountIdLocked(db, account);
829 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700830 return;
831 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800832 long extrasId = getExtrasIdLocked(db, accountId, key);
833 if (extrasId < 0 ) {
834 extrasId = insertExtraLocked(db, accountId, key, value);
835 if (extrasId < 0) {
836 return;
837 }
838 } else {
839 ContentValues values = new ContentValues();
840 values.put(EXTRAS_VALUE, value);
841 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
842 return;
843 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700844
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800845 }
846 writeUserDataIntoCacheLocked(db, account, key, value);
847 db.setTransactionSuccessful();
848 } finally {
849 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700850 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700851 }
852 }
853
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700854 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -0800855 if (result == null) {
856 Log.e(TAG, "the result is unexpectedly null", new Exception());
857 }
858 if (Log.isLoggable(TAG, Log.VERBOSE)) {
859 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
860 + response);
861 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700862 try {
863 response.onResult(result);
864 } catch (RemoteException e) {
865 // if the caller is dead then there is no one to care about remote
866 // exceptions
867 if (Log.isLoggable(TAG, Log.VERBOSE)) {
868 Log.v(TAG, "failure while notifying response", e);
869 }
870 }
871 }
872
Costin Manolache5f383ad92010-12-02 16:44:46 -0800873 void getAuthTokenLabel(final IAccountManagerResponse response,
874 final Account account, final String authTokenType) {
875 if (account == null) throw new IllegalArgumentException("account is null");
876 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
877
878 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
879
880 long identityToken = clearCallingIdentity();
881 try {
882 new Session(response, account.type, false,
883 false /* stripAuthTokenFromResult */) {
884 protected String toDebugString(long now) {
885 return super.toDebugString(now) + ", getAuthTokenLabel"
886 + ", " + account
887 + ", authTokenType " + authTokenType;
888 }
889
890 public void run() throws RemoteException {
891 mAuthenticator.getAuthTokenLabel(this, authTokenType);
892 }
893
894 public void onResult(Bundle result) {
895 if (result != null) {
896 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
897 Bundle bundle = new Bundle();
898 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
899 super.onResult(bundle);
900 return;
901 } else {
902 super.onResult(result);
903 }
904 }
905 }.bind();
906 } finally {
907 restoreCallingIdentity(identityToken);
908 }
909 }
910
Fred Quintanaa698f422009-04-08 19:14:54 -0700911 public void getAuthToken(IAccountManagerResponse response, final Account account,
912 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -0800913 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -0800914 if (Log.isLoggable(TAG, Log.VERBOSE)) {
915 Log.v(TAG, "getAuthToken: " + account
916 + ", response " + response
917 + ", authTokenType " + authTokenType
918 + ", notifyOnAuthFailure " + notifyOnAuthFailure
919 + ", expectActivityLaunch " + expectActivityLaunch
920 + ", caller's uid " + Binder.getCallingUid()
921 + ", pid " + Binder.getCallingPid());
922 }
Fred Quintana382601f2010-03-25 12:25:10 -0700923 if (response == null) throw new IllegalArgumentException("response is null");
924 if (account == null) throw new IllegalArgumentException("account is null");
925 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700926 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
927 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -0800928 final int callerPid = Binder.getCallingPid();
929
930 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
931 mAuthenticatorCache.getServiceInfo(
932 AuthenticatorDescription.newKey(account.type));
933 final boolean customTokens =
934 authenticatorInfo != null && authenticatorInfo.type.customTokens;
935
936 // skip the check if customTokens
937 final boolean permissionGranted = customTokens ||
938 permissionIsGranted(account, authTokenType, callerUid);
939
Costin Manolachec6684f92011-01-14 11:25:39 -0800940 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
941 loginOptionsIn;
Costin Manolachea40c6302010-12-13 14:50:45 -0800942 if (customTokens) {
943 // let authenticator know the identity of the caller
944 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
945 loginOptions.putInt(AccountManager.KEY_CALLER_PID, callerPid);
Costin Manolached6060452011-01-24 16:11:36 -0800946 if (notifyOnAuthFailure) {
947 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
948 }
Costin Manolachea40c6302010-12-13 14:50:45 -0800949 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700950
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700951 long identityToken = clearCallingIdentity();
952 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700953 // if the caller has permission, do the peek. otherwise go the more expensive
954 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -0800955 if (!customTokens && permissionGranted) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800956 String authToken = readAuthTokenInternal(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700957 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700958 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700959 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
960 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
961 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700962 onResult(response, result);
963 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700964 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700965 }
966
Fred Quintana8570f742010-02-18 10:32:54 -0800967 new Session(response, account.type, expectActivityLaunch,
968 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700969 protected String toDebugString(long now) {
970 if (loginOptions != null) loginOptions.keySet();
971 return super.toDebugString(now) + ", getAuthToken"
972 + ", " + account
973 + ", authTokenType " + authTokenType
974 + ", loginOptions " + loginOptions
975 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
976 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700977
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700978 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700979 // If the caller doesn't have permission then create and return the
980 // "grant permission" intent instead of the "getAuthToken" intent.
981 if (!permissionGranted) {
982 mAuthenticator.getAuthTokenLabel(this, authTokenType);
983 } else {
984 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
985 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700986 }
987
988 public void onResult(Bundle result) {
989 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700990 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700991 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
992 new AccountAuthenticatorResponse(this),
993 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700994 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700995 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700996 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700997 onResult(bundle);
998 return;
999 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001000 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001001 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001002 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1003 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001004 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001005 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001006 "the type and name should not be empty");
1007 return;
1008 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001009 if (!customTokens) {
1010 saveAuthTokenToDatabase(new Account(name, type),
1011 authTokenType, authToken);
1012 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001013 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001014
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001015 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001016 if (intent != null && notifyOnAuthFailure && !customTokens) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001017 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001018 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001019 intent);
1020 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001021 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001022 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001023 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001024 }.bind();
1025 } finally {
1026 restoreCallingIdentity(identityToken);
1027 }
Fred Quintana60307342009-03-24 22:48:12 -07001028 }
1029
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001030 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
1031 int uid = intent.getIntExtra(
1032 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1033 String authTokenType = intent.getStringExtra(
1034 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1035 String authTokenLabel = intent.getStringExtra(
1036 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1037
1038 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1039 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001040 final String titleAndSubtitle =
1041 mContext.getString(R.string.permission_request_notification_with_subtitle,
1042 account.name);
1043 final int index = titleAndSubtitle.indexOf('\n');
1044 final String title = titleAndSubtitle.substring(0, index);
1045 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001046 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -07001047 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001048 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -08001049 installNotification(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001050 }
1051
Costin Manolache5f383ad92010-12-02 16:44:46 -08001052 String getAccountLabel(String accountType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001053 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
Costin Manolache5f383ad92010-12-02 16:44:46 -08001054 mAuthenticatorCache.getServiceInfo(
1055 AuthenticatorDescription.newKey(accountType));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001056 if (serviceInfo == null) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001057 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001058 }
1059
1060 final Context authContext;
1061 try {
1062 authContext = mContext.createPackageContext(
Costin Manolache5f383ad92010-12-02 16:44:46 -08001063 serviceInfo.type.packageName, 0);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001064 } catch (PackageManager.NameNotFoundException e) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001065 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001066 }
Costin Manolache5f383ad92010-12-02 16:44:46 -08001067 return authContext.getString(serviceInfo.type.labelId);
1068 }
1069
1070 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1071 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001072
1073 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache9ec17362011-01-17 12:12:37 -08001074 // See FLAT_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
1075 // Since it was set in Eclair+ we can't change it without breaking apps using
1076 // the intent from a non-Activity context.
1077 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001078 intent.addCategory(
1079 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001080
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001081 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001082 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1083 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001084 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001085
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001086 return intent;
1087 }
1088
1089 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1090 int uid) {
1091 Integer id;
1092 synchronized(mCredentialsPermissionNotificationIds) {
1093 final Pair<Pair<Account, String>, Integer> key =
1094 new Pair<Pair<Account, String>, Integer>(
1095 new Pair<Account, String>(account, authTokenType), uid);
1096 id = mCredentialsPermissionNotificationIds.get(key);
1097 if (id == null) {
1098 id = mNotificationIds.incrementAndGet();
1099 mCredentialsPermissionNotificationIds.put(key, id);
1100 }
1101 }
1102 return id;
1103 }
1104
1105 private Integer getSigninRequiredNotificationId(Account account) {
1106 Integer id;
1107 synchronized(mSigninRequiredNotificationIds) {
1108 id = mSigninRequiredNotificationIds.get(account);
1109 if (id == null) {
1110 id = mNotificationIds.incrementAndGet();
1111 mSigninRequiredNotificationIds.put(account, id);
1112 }
1113 }
1114 return id;
1115 }
1116
Fred Quintana33269202009-04-20 16:05:10 -07001117 public void addAcount(final IAccountManagerResponse response, final String accountType,
1118 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -07001119 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintana56285a62010-12-02 14:20:51 -08001120 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1121 Log.v(TAG, "addAccount: accountType " + accountType
1122 + ", response " + response
1123 + ", authTokenType " + authTokenType
1124 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1125 + ", expectActivityLaunch " + expectActivityLaunch
1126 + ", caller's uid " + Binder.getCallingUid()
1127 + ", pid " + Binder.getCallingPid());
1128 }
Fred Quintana382601f2010-03-25 12:25:10 -07001129 if (response == null) throw new IllegalArgumentException("response is null");
1130 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001131 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001132 long identityToken = clearCallingIdentity();
1133 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001134 new Session(response, accountType, expectActivityLaunch,
1135 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001136 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001137 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001138 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001139 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001140
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001141 protected String toDebugString(long now) {
1142 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001143 + ", accountType " + accountType
1144 + ", requiredFeatures "
1145 + (requiredFeatures != null
1146 ? TextUtils.join(",", requiredFeatures)
1147 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001148 }
1149 }.bind();
1150 } finally {
1151 restoreCallingIdentity(identityToken);
1152 }
Fred Quintana60307342009-03-24 22:48:12 -07001153 }
1154
Fred Quintanaa698f422009-04-08 19:14:54 -07001155 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001156 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001157 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1158 Log.v(TAG, "confirmCredentials: " + account
1159 + ", response " + response
1160 + ", expectActivityLaunch " + expectActivityLaunch
1161 + ", caller's uid " + Binder.getCallingUid()
1162 + ", pid " + Binder.getCallingPid());
1163 }
Fred Quintana382601f2010-03-25 12:25:10 -07001164 if (response == null) throw new IllegalArgumentException("response is null");
1165 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001166 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001167 long identityToken = clearCallingIdentity();
1168 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001169 new Session(response, account.type, expectActivityLaunch,
1170 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001171 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001172 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001173 }
1174 protected String toDebugString(long now) {
1175 return super.toDebugString(now) + ", confirmCredentials"
1176 + ", " + account;
1177 }
1178 }.bind();
1179 } finally {
1180 restoreCallingIdentity(identityToken);
1181 }
Fred Quintana60307342009-03-24 22:48:12 -07001182 }
1183
Fred Quintanaa698f422009-04-08 19:14:54 -07001184 public void updateCredentials(IAccountManagerResponse response, final Account account,
1185 final String authTokenType, final boolean expectActivityLaunch,
1186 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001187 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1188 Log.v(TAG, "updateCredentials: " + account
1189 + ", response " + response
1190 + ", authTokenType " + authTokenType
1191 + ", expectActivityLaunch " + expectActivityLaunch
1192 + ", caller's uid " + Binder.getCallingUid()
1193 + ", pid " + Binder.getCallingPid());
1194 }
Fred Quintana382601f2010-03-25 12:25:10 -07001195 if (response == null) throw new IllegalArgumentException("response is null");
1196 if (account == null) throw new IllegalArgumentException("account is null");
1197 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001198 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001199 long identityToken = clearCallingIdentity();
1200 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001201 new Session(response, account.type, expectActivityLaunch,
1202 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001203 public void run() throws RemoteException {
1204 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1205 }
1206 protected String toDebugString(long now) {
1207 if (loginOptions != null) loginOptions.keySet();
1208 return super.toDebugString(now) + ", updateCredentials"
1209 + ", " + account
1210 + ", authTokenType " + authTokenType
1211 + ", loginOptions " + loginOptions;
1212 }
1213 }.bind();
1214 } finally {
1215 restoreCallingIdentity(identityToken);
1216 }
Fred Quintana60307342009-03-24 22:48:12 -07001217 }
1218
Fred Quintanaa698f422009-04-08 19:14:54 -07001219 public void editProperties(IAccountManagerResponse response, final String accountType,
1220 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001221 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1222 Log.v(TAG, "editProperties: accountType " + accountType
1223 + ", response " + response
1224 + ", expectActivityLaunch " + expectActivityLaunch
1225 + ", caller's uid " + Binder.getCallingUid()
1226 + ", pid " + Binder.getCallingPid());
1227 }
Fred Quintana382601f2010-03-25 12:25:10 -07001228 if (response == null) throw new IllegalArgumentException("response is null");
1229 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001230 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001231 long identityToken = clearCallingIdentity();
1232 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001233 new Session(response, accountType, expectActivityLaunch,
1234 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001235 public void run() throws RemoteException {
1236 mAuthenticator.editProperties(this, mAccountType);
1237 }
1238 protected String toDebugString(long now) {
1239 return super.toDebugString(now) + ", editProperties"
1240 + ", accountType " + accountType;
1241 }
1242 }.bind();
1243 } finally {
1244 restoreCallingIdentity(identityToken);
1245 }
Fred Quintana60307342009-03-24 22:48:12 -07001246 }
1247
Fred Quintana33269202009-04-20 16:05:10 -07001248 private class GetAccountsByTypeAndFeatureSession extends Session {
1249 private final String[] mFeatures;
1250 private volatile Account[] mAccountsOfType = null;
1251 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1252 private volatile int mCurrentAccount = 0;
1253
1254 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
1255 String type, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -08001256 super(response, type, false /* expectActivityLaunch */,
1257 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001258 mFeatures = features;
1259 }
1260
1261 public void run() throws RemoteException {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001262 synchronized (mCacheLock) {
1263 mAccountsOfType = getAccountsFromCacheLocked(mAccountType);
1264 }
Fred Quintana33269202009-04-20 16:05:10 -07001265 // check whether each account matches the requested features
1266 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1267 mCurrentAccount = 0;
1268
1269 checkAccount();
1270 }
1271
1272 public void checkAccount() {
1273 if (mCurrentAccount >= mAccountsOfType.length) {
1274 sendResult();
1275 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001276 }
Fred Quintana33269202009-04-20 16:05:10 -07001277
Fred Quintana29e94b82010-03-10 12:11:51 -08001278 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1279 if (accountAuthenticator == null) {
1280 // It is possible that the authenticator has died, which is indicated by
1281 // mAuthenticator being set to null. If this happens then just abort.
1282 // There is no need to send back a result or error in this case since
1283 // that already happened when mAuthenticator was cleared.
1284 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1285 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1286 + " connected to the authenticator, " + toDebugString());
1287 }
1288 return;
1289 }
Fred Quintana33269202009-04-20 16:05:10 -07001290 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001291 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001292 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001293 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001294 }
1295 }
1296
1297 public void onResult(Bundle result) {
1298 mNumResults++;
1299 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001300 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001301 return;
1302 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001303 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001304 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1305 }
1306 mCurrentAccount++;
1307 checkAccount();
1308 }
1309
1310 public void sendResult() {
1311 IAccountManagerResponse response = getResponseAndClose();
1312 if (response != null) {
1313 try {
1314 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1315 for (int i = 0; i < accounts.length; i++) {
1316 accounts[i] = mAccountsWithFeatures.get(i);
1317 }
Fred Quintana56285a62010-12-02 14:20:51 -08001318 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1319 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1320 + response);
1321 }
Fred Quintana33269202009-04-20 16:05:10 -07001322 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001323 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001324 response.onResult(result);
1325 } catch (RemoteException e) {
1326 // if the caller is dead then there is no one to care about remote exceptions
1327 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1328 Log.v(TAG, "failure while notifying response", e);
1329 }
1330 }
1331 }
1332 }
1333
1334
1335 protected String toDebugString(long now) {
1336 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1337 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1338 }
1339 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001340
1341 public Account[] getAccounts(String type) {
Fred Quintana56285a62010-12-02 14:20:51 -08001342 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1343 Log.v(TAG, "getAccounts: accountType " + type
1344 + ", caller's uid " + Binder.getCallingUid()
1345 + ", pid " + Binder.getCallingPid());
1346 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001347 checkReadAccountsPermission();
1348 long identityToken = clearCallingIdentity();
1349 try {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001350 synchronized (mCacheLock) {
1351 return getAccountsFromCacheLocked(type);
1352 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001353 } finally {
1354 restoreCallingIdentity(identityToken);
1355 }
1356 }
1357
1358 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001359 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001360 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1361 Log.v(TAG, "getAccounts: accountType " + type
1362 + ", response " + response
1363 + ", features " + stringArrayToString(features)
1364 + ", caller's uid " + Binder.getCallingUid()
1365 + ", pid " + Binder.getCallingPid());
1366 }
Fred Quintana382601f2010-03-25 12:25:10 -07001367 if (response == null) throw new IllegalArgumentException("response is null");
1368 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001369 checkReadAccountsPermission();
Fred Quintana33269202009-04-20 16:05:10 -07001370 long identityToken = clearCallingIdentity();
1371 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001372 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001373 Account[] accounts;
1374 synchronized (mCacheLock) {
1375 accounts = getAccountsFromCacheLocked(type);
1376 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001377 Bundle result = new Bundle();
1378 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1379 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001380 return;
1381 }
Fred Quintana33269202009-04-20 16:05:10 -07001382 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1383 } finally {
1384 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001385 }
1386 }
1387
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001388 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001389 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001390 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001391 try {
1392 if (cursor.moveToNext()) {
1393 return cursor.getLong(0);
1394 }
1395 return -1;
1396 } finally {
1397 cursor.close();
1398 }
1399 }
1400
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001401 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001402 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1403 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1404 new String[]{key}, null, null, null);
1405 try {
1406 if (cursor.moveToNext()) {
1407 return cursor.getLong(0);
1408 }
1409 return -1;
1410 } finally {
1411 cursor.close();
1412 }
1413 }
1414
Fred Quintanaa698f422009-04-08 19:14:54 -07001415 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001416 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001417 IAccountManagerResponse mResponse;
1418 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001419 final boolean mExpectActivityLaunch;
1420 final long mCreationTime;
1421
Fred Quintana33269202009-04-20 16:05:10 -07001422 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001423 private int mNumRequestContinued = 0;
1424 private int mNumErrors = 0;
1425
Fred Quintana60307342009-03-24 22:48:12 -07001426
1427 IAccountAuthenticator mAuthenticator = null;
1428
Fred Quintana8570f742010-02-18 10:32:54 -08001429 private final boolean mStripAuthTokenFromResult;
1430
Fred Quintanaa698f422009-04-08 19:14:54 -07001431 public Session(IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001432 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001433 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001434 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001435 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana8570f742010-02-18 10:32:54 -08001436 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001437 mResponse = response;
1438 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001439 mExpectActivityLaunch = expectActivityLaunch;
1440 mCreationTime = SystemClock.elapsedRealtime();
1441 synchronized (mSessions) {
1442 mSessions.put(toString(), this);
1443 }
1444 try {
1445 response.asBinder().linkToDeath(this, 0 /* flags */);
1446 } catch (RemoteException e) {
1447 mResponse = null;
1448 binderDied();
1449 }
Fred Quintana60307342009-03-24 22:48:12 -07001450 }
1451
Fred Quintanaa698f422009-04-08 19:14:54 -07001452 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001453 if (mResponse == null) {
1454 // this session has already been closed
1455 return null;
1456 }
Fred Quintana60307342009-03-24 22:48:12 -07001457 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001458 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001459 return response;
1460 }
1461
Fred Quintanaa698f422009-04-08 19:14:54 -07001462 private void close() {
1463 synchronized (mSessions) {
1464 if (mSessions.remove(toString()) == null) {
1465 // the session was already closed, so bail out now
1466 return;
1467 }
1468 }
1469 if (mResponse != null) {
1470 // stop listening for response deaths
1471 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1472
1473 // clear this so that we don't accidentally send any further results
1474 mResponse = null;
1475 }
1476 cancelTimeout();
1477 unbind();
1478 }
1479
1480 public void binderDied() {
1481 mResponse = null;
1482 close();
1483 }
1484
1485 protected String toDebugString() {
1486 return toDebugString(SystemClock.elapsedRealtime());
1487 }
1488
1489 protected String toDebugString(long now) {
1490 return "Session: expectLaunch " + mExpectActivityLaunch
1491 + ", connected " + (mAuthenticator != null)
1492 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1493 + "/" + mNumErrors + ")"
1494 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1495 }
1496
Fred Quintana60307342009-03-24 22:48:12 -07001497 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001498 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1499 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1500 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001501 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001502 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001503 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001504 }
1505 }
1506
1507 private void unbind() {
1508 if (mAuthenticator != null) {
1509 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001510 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001511 }
1512 }
1513
1514 public void scheduleTimeout() {
1515 mMessageHandler.sendMessageDelayed(
1516 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1517 }
1518
1519 public void cancelTimeout() {
1520 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1521 }
1522
Fred Quintanab839afc2009-10-14 15:57:28 -07001523 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001524 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001525 try {
1526 run();
1527 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001528 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001529 "remote exception");
1530 }
Fred Quintana60307342009-03-24 22:48:12 -07001531 }
1532
Fred Quintanab839afc2009-10-14 15:57:28 -07001533 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001534 mAuthenticator = null;
1535 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001536 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001537 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001538 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001539 }
1540 }
1541
Fred Quintanab839afc2009-10-14 15:57:28 -07001542 public abstract void run() throws RemoteException;
1543
Fred Quintana60307342009-03-24 22:48:12 -07001544 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001545 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001546 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001547 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001548 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001549 }
1550 }
1551
Fred Quintanaa698f422009-04-08 19:14:54 -07001552 public void onResult(Bundle result) {
1553 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001554 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1555 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1556 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001557 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1558 Account account = new Account(accountName, accountType);
1559 cancelNotification(getSigninRequiredNotificationId(account));
1560 }
Fred Quintana60307342009-03-24 22:48:12 -07001561 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001562 IAccountManagerResponse response;
1563 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001564 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001565 response = mResponse;
1566 } else {
1567 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001568 }
Fred Quintana60307342009-03-24 22:48:12 -07001569 if (response != null) {
1570 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001571 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001572 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1573 Log.v(TAG, getClass().getSimpleName()
1574 + " calling onError() on response " + response);
1575 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001576 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001577 "null bundle returned");
1578 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001579 if (mStripAuthTokenFromResult) {
1580 result.remove(AccountManager.KEY_AUTHTOKEN);
1581 }
Fred Quintana56285a62010-12-02 14:20:51 -08001582 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1583 Log.v(TAG, getClass().getSimpleName()
1584 + " calling onResult() on response " + response);
1585 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001586 response.onResult(result);
1587 }
Fred Quintana60307342009-03-24 22:48:12 -07001588 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001589 // if the caller is dead then there is no one to care about remote exceptions
1590 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1591 Log.v(TAG, "failure while notifying response", e);
1592 }
Fred Quintana60307342009-03-24 22:48:12 -07001593 }
1594 }
1595 }
Fred Quintana60307342009-03-24 22:48:12 -07001596
Fred Quintanaa698f422009-04-08 19:14:54 -07001597 public void onRequestContinued() {
1598 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001599 }
1600
1601 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001602 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001603 IAccountManagerResponse response = getResponseAndClose();
1604 if (response != null) {
1605 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001606 Log.v(TAG, getClass().getSimpleName()
1607 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001608 }
1609 try {
1610 response.onError(errorCode, errorMessage);
1611 } catch (RemoteException e) {
1612 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1613 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1614 }
1615 }
1616 } else {
1617 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1618 Log.v(TAG, "Session.onError: already closed");
1619 }
Fred Quintana60307342009-03-24 22:48:12 -07001620 }
1621 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001622
1623 /**
1624 * find the component name for the authenticator and initiate a bind
1625 * if no authenticator or the bind fails then return false, otherwise return true
1626 */
1627 private boolean bindToAuthenticator(String authenticatorType) {
1628 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1629 mAuthenticatorCache.getServiceInfo(
1630 AuthenticatorDescription.newKey(authenticatorType));
1631 if (authenticatorInfo == null) {
1632 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1633 Log.v(TAG, "there is no authenticator for " + authenticatorType
1634 + ", bailing out");
1635 }
1636 return false;
1637 }
1638
1639 Intent intent = new Intent();
1640 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1641 intent.setComponent(authenticatorInfo.componentName);
1642 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1643 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1644 }
1645 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1646 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1647 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1648 }
1649 return false;
1650 }
1651
1652
1653 return true;
1654 }
Fred Quintana60307342009-03-24 22:48:12 -07001655 }
1656
1657 private class MessageHandler extends Handler {
1658 MessageHandler(Looper looper) {
1659 super(looper);
1660 }
Costin Manolache3348f142009-09-29 18:58:36 -07001661
Fred Quintana60307342009-03-24 22:48:12 -07001662 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001663 switch (msg.what) {
1664 case MESSAGE_TIMED_OUT:
1665 Session session = (Session)msg.obj;
1666 session.onTimedOut();
1667 break;
1668
1669 default:
1670 throw new IllegalStateException("unhandled message: " + msg.what);
1671 }
1672 }
1673 }
1674
Oscar Montemayora8529f62009-11-18 10:14:20 -08001675 private static String getDatabaseName() {
1676 if(Environment.isEncryptedFilesystemEnabled()) {
1677 // Hard-coded path in case of encrypted file system
1678 return Environment.getSystemSecureDirectory().getPath() + File.separator + DATABASE_NAME;
1679 } else {
1680 // Regular path in case of non-encrypted file system
1681 return DATABASE_NAME;
1682 }
1683 }
1684
Fred Quintana60307342009-03-24 22:48:12 -07001685 private class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001686
Fred Quintana60307342009-03-24 22:48:12 -07001687 public DatabaseHelper(Context context) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001688 super(context, AccountManagerService.getDatabaseName(), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001689 }
1690
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001691 /**
1692 * This call needs to be made while the mCacheLock is held. The way to
1693 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
1694 * @param db The database.
1695 */
Fred Quintana60307342009-03-24 22:48:12 -07001696 @Override
1697 public void onCreate(SQLiteDatabase db) {
1698 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1699 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1700 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1701 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1702 + ACCOUNTS_PASSWORD + " TEXT, "
1703 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1704
1705 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1706 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1707 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1708 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1709 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1710 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1711
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001712 createGrantsTable(db);
1713
Fred Quintana60307342009-03-24 22:48:12 -07001714 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1715 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1716 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1717 + EXTRAS_KEY + " TEXT NOT NULL, "
1718 + EXTRAS_VALUE + " TEXT, "
1719 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1720
1721 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1722 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1723 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001724
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001725 createAccountsDeletionTrigger(db);
1726 }
1727
1728 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001729 db.execSQL(""
1730 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1731 + " BEGIN"
1732 + " DELETE FROM " + TABLE_AUTHTOKENS
1733 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1734 + " DELETE FROM " + TABLE_EXTRAS
1735 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001736 + " DELETE FROM " + TABLE_GRANTS
1737 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001738 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001739 }
1740
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001741 private void createGrantsTable(SQLiteDatabase db) {
1742 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1743 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1744 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1745 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1746 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1747 + "," + GRANTS_GRANTEE_UID + "))");
1748 }
1749
Fred Quintana60307342009-03-24 22:48:12 -07001750 @Override
1751 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001752 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001753
Fred Quintanaa698f422009-04-08 19:14:54 -07001754 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001755 // no longer need to do anything since the work is done
1756 // when upgrading from version 2
1757 oldVersion++;
1758 }
1759
1760 if (oldVersion == 2) {
1761 createGrantsTable(db);
1762 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1763 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001764 oldVersion++;
1765 }
Costin Manolache3348f142009-09-29 18:58:36 -07001766
1767 if (oldVersion == 3) {
1768 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1769 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1770 oldVersion++;
1771 }
Fred Quintana60307342009-03-24 22:48:12 -07001772 }
1773
1774 @Override
1775 public void onOpen(SQLiteDatabase db) {
1776 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1777 }
1778 }
1779
1780 private void setMetaValue(String key, String value) {
1781 ContentValues values = new ContentValues();
1782 values.put(META_KEY, key);
1783 values.put(META_VALUE, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001784 synchronized (mCacheLock) {
1785 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1786 }
Fred Quintana60307342009-03-24 22:48:12 -07001787 }
1788
Fred Quintana60307342009-03-24 22:48:12 -07001789 public IBinder onBind(Intent intent) {
1790 return asBinder();
1791 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001792
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001793 /**
1794 * Searches array of arguments for the specified string
1795 * @param args array of argument strings
1796 * @param value value to search for
1797 * @return true if the value is contained in the array
1798 */
1799 private static boolean scanArgs(String[] args, String value) {
1800 if (args != null) {
1801 for (String arg : args) {
1802 if (value.equals(arg)) {
1803 return true;
1804 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001805 }
1806 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001807 return false;
1808 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001809
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001810 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001811 synchronized (mCacheLock) {
1812 final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Fred Quintanaa698f422009-04-08 19:14:54 -07001813
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001814 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001815
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001816 if (isCheckinRequest) {
1817 // This is a checkin request. *Only* upload the account types and the count of each.
1818 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1819 null, null, ACCOUNTS_TYPE, null, null);
1820 try {
1821 while (cursor.moveToNext()) {
1822 // print type,count
1823 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1824 }
1825 } finally {
1826 if (cursor != null) {
1827 cursor.close();
1828 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001829 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001830 } else {
1831 Account[] accounts = getAccountsFromCacheLocked(null /* type */);
1832 fout.println("Accounts: " + accounts.length);
1833 for (Account account : accounts) {
1834 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001835 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001836
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001837 fout.println();
1838 synchronized (mSessions) {
1839 final long now = SystemClock.elapsedRealtime();
1840 fout.println("Active Sessions: " + mSessions.size());
1841 for (Session session : mSessions.values()) {
1842 fout.println(" " + session.toDebugString(now));
1843 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001844 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001845
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001846 fout.println();
1847 mAuthenticatorCache.dump(fd, fout, args);
1848 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001849 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001850 }
1851
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001852 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001853 long identityToken = clearCallingIdentity();
1854 try {
1855 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1856 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1857 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001858
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001859 if (intent.getComponent() != null &&
1860 GrantCredentialsPermissionActivity.class.getName().equals(
1861 intent.getComponent().getClassName())) {
1862 createNoCredentialsPermissionNotification(account, intent);
1863 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001864 final Integer notificationId = getSigninRequiredNotificationId(account);
1865 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001866 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1867 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001868 final String notificationTitleFormat =
1869 mContext.getText(R.string.notification_title).toString();
1870 n.setLatestEventInfo(mContext,
1871 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001872 message, PendingIntent.getActivity(
1873 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -08001874 installNotification(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001875 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001876 } finally {
1877 restoreCallingIdentity(identityToken);
1878 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001879 }
1880
Fred Quintana56285a62010-12-02 14:20:51 -08001881 protected void installNotification(final int notificationId, final Notification n) {
1882 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
1883 .notify(notificationId, n);
1884 }
1885
1886 protected void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001887 long identityToken = clearCallingIdentity();
1888 try {
1889 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001890 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001891 } finally {
1892 restoreCallingIdentity(identityToken);
1893 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001894 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001895
Fred Quintanab38eb142010-02-24 13:40:54 -08001896 /** Succeeds if any of the specified permissions are granted. */
1897 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001898 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08001899
1900 for (String perm : permissions) {
1901 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
1902 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001903 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08001904 }
1905 return;
1906 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001907 }
Fred Quintanab38eb142010-02-24 13:40:54 -08001908
1909 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08001910 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08001911 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001912 }
1913
Fred Quintana7be59642009-08-24 18:29:25 -07001914 private boolean inSystemImage(int callerUid) {
Fred Quintana56285a62010-12-02 14:20:51 -08001915 String[] packages = mPackageManager.getPackagesForUid(callerUid);
Fred Quintana7be59642009-08-24 18:29:25 -07001916 for (String name : packages) {
1917 try {
Fred Quintana56285a62010-12-02 14:20:51 -08001918 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
1919 if (packageInfo != null
1920 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07001921 return true;
1922 }
1923 } catch (PackageManager.NameNotFoundException e) {
1924 return false;
1925 }
1926 }
1927 return false;
1928 }
1929
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001930 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07001931 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07001932 final boolean fromAuthenticator = account != null
1933 && hasAuthenticatorUid(account.type, callerUid);
1934 final boolean hasExplicitGrants = account != null
1935 && hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001936 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1937 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08001938 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001939 + ": is authenticator? " + fromAuthenticator
1940 + ", has explicit permission? " + hasExplicitGrants);
1941 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001942 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001943 }
1944
Fred Quintana1a231912009-10-15 11:31:30 -07001945 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001946 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
1947 mAuthenticatorCache.getAllServices()) {
1948 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001949 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08001950 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001951 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001952 }
1953 }
1954 return false;
1955 }
1956
1957 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
1958 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
1959 return true;
1960 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001961 synchronized (mCacheLock) {
1962 final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1963 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
1964 account.name, account.type};
1965 final boolean permissionGranted =
1966 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
1967 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
1968 // TODO: Skip this check when running automated tests. Replace this
1969 // with a more general solution.
1970 Log.d(TAG, "no credentials permission for usage of " + account + ", "
1971 + authTokenType + " by uid " + Binder.getCallingUid()
1972 + " but ignoring since device is in test harness.");
1973 return true;
1974 }
1975 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001976 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001977 }
1978
1979 private void checkCallingUidAgainstAuthenticator(Account account) {
1980 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07001981 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001982 String msg = "caller uid " + uid + " is different than the authenticator's uid";
1983 Log.w(TAG, msg);
1984 throw new SecurityException(msg);
1985 }
1986 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1987 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
1988 }
1989 }
1990
1991 private void checkAuthenticateAccountsPermission(Account account) {
1992 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
1993 checkCallingUidAgainstAuthenticator(account);
1994 }
1995
1996 private void checkReadAccountsPermission() {
1997 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
1998 }
1999
2000 private void checkManageAccountsPermission() {
2001 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2002 }
2003
Fred Quintanab38eb142010-02-24 13:40:54 -08002004 private void checkManageAccountsOrUseCredentialsPermissions() {
2005 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2006 Manifest.permission.USE_CREDENTIALS);
2007 }
2008
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002009 /**
2010 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2011 * <p>
2012 * Although this is public it can only be accessed via the AccountManagerService object
2013 * which is in the system. This means we don't need to protect it with permissions.
2014 * @hide
2015 */
2016 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002017 if (account == null || authTokenType == null) {
2018 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002019 return;
2020 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002021 synchronized (mCacheLock) {
2022 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
2023 db.beginTransaction();
2024 try {
2025 long accountId = getAccountIdLocked(db, account);
2026 if (accountId >= 0) {
2027 ContentValues values = new ContentValues();
2028 values.put(GRANTS_ACCOUNTS_ID, accountId);
2029 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2030 values.put(GRANTS_GRANTEE_UID, uid);
2031 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2032 db.setTransactionSuccessful();
2033 }
2034 } finally {
2035 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002036 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002037 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002038 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002039 }
2040
2041 /**
2042 * Don't allow callers with the given uid permission to get credentials for
2043 * account/authTokenType.
2044 * <p>
2045 * Although this is public it can only be accessed via the AccountManagerService object
2046 * which is in the system. This means we don't need to protect it with permissions.
2047 * @hide
2048 */
2049 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002050 if (account == null || authTokenType == null) {
2051 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002052 return;
2053 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002054 synchronized (mCacheLock) {
2055 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
2056 db.beginTransaction();
2057 try {
2058 long accountId = getAccountIdLocked(db, account);
2059 if (accountId >= 0) {
2060 db.delete(TABLE_GRANTS,
2061 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2062 + GRANTS_GRANTEE_UID + "=?",
2063 new String[]{String.valueOf(accountId), authTokenType,
2064 String.valueOf(uid)});
2065 db.setTransactionSuccessful();
2066 }
2067 } finally {
2068 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002069 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002070 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002071 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002072 }
Fred Quintana56285a62010-12-02 14:20:51 -08002073
2074 static final private String stringArrayToString(String[] value) {
2075 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2076 }
2077
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002078 private void removeAccountFromCacheLocked(Account account) {
2079 final Account[] oldAccountsForType = mAccountCache.get(account.type);
2080 if (oldAccountsForType != null) {
2081 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2082 for (Account curAccount : oldAccountsForType) {
2083 if (!curAccount.equals(account)) {
2084 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002085 }
2086 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002087 if (newAccountsList.isEmpty()) {
2088 mAccountCache.remove(account.type);
2089 } else {
2090 Account[] newAccountsForType = new Account[newAccountsList.size()];
2091 newAccountsForType = newAccountsList.toArray(newAccountsForType);
2092 mAccountCache.put(account.type, newAccountsForType);
2093 }
Fred Quintana56285a62010-12-02 14:20:51 -08002094 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002095 mUserDataCache.remove(account);
2096 mAuthTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002097 }
2098
2099 /**
2100 * This assumes that the caller has already checked that the account is not already present.
2101 */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002102 private void insertAccountIntoCacheLocked(Account account) {
2103 Account[] accountsForType = mAccountCache.get(account.type);
2104 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2105 Account[] newAccountsForType = new Account[oldLength + 1];
2106 if (accountsForType != null) {
2107 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002108 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002109 newAccountsForType[oldLength] = account;
2110 mAccountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002111 }
2112
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002113 protected Account[] getAccountsFromCacheLocked(String accountType) {
2114 if (accountType != null) {
2115 final Account[] accounts = mAccountCache.get(accountType);
2116 if (accounts == null) {
2117 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002118 } else {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002119 return Arrays.copyOf(accounts, accounts.length);
Fred Quintana56285a62010-12-02 14:20:51 -08002120 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002121 } else {
2122 int totalLength = 0;
2123 for (Account[] accounts : mAccountCache.values()) {
2124 totalLength += accounts.length;
2125 }
2126 if (totalLength == 0) {
2127 return EMPTY_ACCOUNT_ARRAY;
2128 }
2129 Account[] accounts = new Account[totalLength];
2130 totalLength = 0;
2131 for (Account[] accountsOfType : mAccountCache.values()) {
2132 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2133 accountsOfType.length);
2134 totalLength += accountsOfType.length;
2135 }
2136 return accounts;
Fred Quintana56285a62010-12-02 14:20:51 -08002137 }
2138 }
2139
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002140 protected void writeUserDataIntoCacheLocked(final SQLiteDatabase db, Account account,
2141 String key, String value) {
2142 HashMap<String, String> userDataForAccount = mUserDataCache.get(account);
2143 if (userDataForAccount == null) {
2144 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
2145 mUserDataCache.put(account, userDataForAccount);
2146 }
2147 if (value == null) {
2148 userDataForAccount.remove(key);
2149 } else {
2150 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002151 }
2152 }
2153
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002154 protected void writeAuthTokenIntoCacheLocked(final SQLiteDatabase db, Account account,
2155 String key, String value) {
2156 HashMap<String, String> authTokensForAccount = mAuthTokenCache.get(account);
2157 if (authTokensForAccount == null) {
2158 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
2159 mAuthTokenCache.put(account, authTokensForAccount);
2160 }
2161 if (value == null) {
2162 authTokensForAccount.remove(key);
2163 } else {
2164 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002165 }
2166 }
2167
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002168 protected String readAuthTokenInternal(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08002169 synchronized (mCacheLock) {
2170 HashMap<String, String> authTokensForAccount = mAuthTokenCache.get(account);
2171 if (authTokensForAccount == null) {
2172 // need to populate the cache for this account
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002173 final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
2174 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Fred Quintana56285a62010-12-02 14:20:51 -08002175 mAuthTokenCache.put(account, authTokensForAccount);
2176 }
2177 return authTokensForAccount.get(authTokenType);
2178 }
2179 }
2180
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002181 protected String readUserDataInternal(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -08002182 synchronized (mCacheLock) {
2183 HashMap<String, String> userDataForAccount = mUserDataCache.get(account);
2184 if (userDataForAccount == null) {
2185 // need to populate the cache for this account
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002186 final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
2187 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Fred Quintana56285a62010-12-02 14:20:51 -08002188 mUserDataCache.put(account, userDataForAccount);
2189 }
2190 return userDataForAccount.get(key);
2191 }
2192 }
2193
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002194 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2195 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002196 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002197 Cursor cursor = db.query(TABLE_EXTRAS,
2198 COLUMNS_EXTRAS_KEY_AND_VALUE,
2199 SELECTION_USERDATA_BY_ACCOUNT,
2200 new String[]{account.name, account.type},
2201 null, null, null);
2202 try {
2203 while (cursor.moveToNext()) {
2204 final String tmpkey = cursor.getString(0);
2205 final String value = cursor.getString(1);
2206 userDataForAccount.put(tmpkey, value);
2207 }
2208 } finally {
2209 cursor.close();
2210 }
2211 return userDataForAccount;
2212 }
2213
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002214 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2215 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002216 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002217 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2218 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2219 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2220 new String[]{account.name, account.type},
2221 null, null, null);
2222 try {
2223 while (cursor.moveToNext()) {
2224 final String type = cursor.getString(0);
2225 final String authToken = cursor.getString(1);
2226 authTokensForAccount.put(type, authToken);
2227 }
2228 } finally {
2229 cursor.close();
2230 }
2231 return authTokensForAccount;
2232 }
Fred Quintana60307342009-03-24 22:48:12 -07002233}