blob: 81be2aafc55f4ceb8e8aa7a5fd9dd4523884c9bc [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.accounts;
18
Fred Quintana56285a62010-12-02 14:20:51 -080019import com.android.internal.R;
20import com.android.internal.telephony.ITelephony;
21import com.android.internal.telephony.TelephonyIntents;
22
Doug Zongker885cfc232009-10-21 16:52:44 -070023import android.Manifest;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080024import android.app.ActivityManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070025import android.app.Notification;
26import android.app.NotificationManager;
27import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070028import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070029import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070030import android.content.ContentValues;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070034import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070035import android.content.pm.ApplicationInfo;
36import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070037import android.content.pm.PackageManager;
38import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070039import android.content.pm.RegisteredServicesCacheListener;
Fred Quintana60307342009-03-24 22:48:12 -070040import android.database.Cursor;
41import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070042import android.database.sqlite.SQLiteDatabase;
43import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070044import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070045import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080046import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070047import android.os.Handler;
48import android.os.HandlerThread;
49import android.os.IBinder;
50import android.os.Looper;
51import android.os.Message;
52import android.os.RemoteException;
Doug Zongker885cfc232009-10-21 16:52:44 -070053import android.os.ServiceManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070054import android.os.SystemClock;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070055import android.os.SystemProperties;
Fred Quintana60307342009-03-24 22:48:12 -070056import android.telephony.TelephonyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070057import android.text.TextUtils;
58import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070059import android.util.Pair;
Fred Quintana60307342009-03-24 22:48:12 -070060
Oscar Montemayora8529f62009-11-18 10:14:20 -080061import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import java.io.FileDescriptor;
63import java.io.PrintWriter;
64import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080065import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070067import java.util.HashMap;
Fred Quintana56285a62010-12-02 14:20:51 -080068import java.util.LinkedHashMap;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070069import java.util.concurrent.atomic.AtomicInteger;
70import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070071
Fred Quintana60307342009-03-24 22:48:12 -070072/**
73 * A system service that provides account, password, and authtoken management for all
74 * accounts on the device. Some of these calls are implemented with the help of the corresponding
75 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
76 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
77 * AccountManager accountManager =
78 * (AccountManager)context.getSystemService(Context.ACCOUNT_SERVICE)
Fred Quintana33269202009-04-20 16:05:10 -070079 * @hide
Fred Quintana60307342009-03-24 22:48:12 -070080 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -070081public class AccountManagerService
82 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -080083 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Costin Manolache3348f142009-09-29 18:58:36 -070084 private static final String GOOGLE_ACCOUNT_TYPE = "com.google";
Jim Miller50c05f32009-09-21 19:07:44 -070085
Fred Quintana60307342009-03-24 22:48:12 -070086 private static final String TAG = "AccountManagerService";
87
88 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
89 private static final String DATABASE_NAME = "accounts.db";
Costin Manolache3348f142009-09-29 18:58:36 -070090 private static final int DATABASE_VERSION = 4;
Fred Quintana60307342009-03-24 22:48:12 -070091
92 private final Context mContext;
93
Fred Quintana56285a62010-12-02 14:20:51 -080094 private final PackageManager mPackageManager;
95
Fred Quintana60307342009-03-24 22:48:12 -070096 private HandlerThread mMessageThread;
97 private final MessageHandler mMessageHandler;
98
99 // Messages that can be sent on mHandler
100 private static final int MESSAGE_TIMED_OUT = 3;
Fred Quintana60307342009-03-24 22:48:12 -0700101
Fred Quintana56285a62010-12-02 14:20:51 -0800102 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700103 private final DatabaseHelper mOpenHelper;
104 private final SimWatcher mSimWatcher;
105
106 private static final String TABLE_ACCOUNTS = "accounts";
107 private static final String ACCOUNTS_ID = "_id";
108 private static final String ACCOUNTS_NAME = "name";
109 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700110 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700111 private static final String ACCOUNTS_PASSWORD = "password";
112
113 private static final String TABLE_AUTHTOKENS = "authtokens";
114 private static final String AUTHTOKENS_ID = "_id";
115 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
116 private static final String AUTHTOKENS_TYPE = "type";
117 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
118
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700119 private static final String TABLE_GRANTS = "grants";
120 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
121 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
122 private static final String GRANTS_GRANTEE_UID = "uid";
123
Fred Quintana60307342009-03-24 22:48:12 -0700124 private static final String TABLE_EXTRAS = "extras";
125 private static final String EXTRAS_ID = "_id";
126 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
127 private static final String EXTRAS_KEY = "key";
128 private static final String EXTRAS_VALUE = "value";
129
130 private static final String TABLE_META = "meta";
131 private static final String META_KEY = "key";
132 private static final String META_VALUE = "value";
133
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700134 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
135 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700136 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700137
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700138 private static final String COUNT_OF_MATCHING_GRANTS = ""
139 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
140 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
141 + " AND " + GRANTS_GRANTEE_UID + "=?"
142 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
143 + " AND " + ACCOUNTS_NAME + "=?"
144 + " AND " + ACCOUNTS_TYPE + "=?";
145
Fred Quintana56285a62010-12-02 14:20:51 -0800146 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
147 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
148 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
149 AUTHTOKENS_AUTHTOKEN};
150
151 private static final String SELECTION_USERDATA_BY_ACCOUNT =
152 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
153 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
154
Fred Quintanaa698f422009-04-08 19:14:54 -0700155 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700156 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
157
158 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
159 mCredentialsPermissionNotificationIds =
160 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
161 private final HashMap<Account, Integer> mSigninRequiredNotificationIds =
162 new HashMap<Account, Integer>();
163 private static AtomicReference<AccountManagerService> sThis =
164 new AtomicReference<AccountManagerService>();
165
Fred Quintana31957f12009-10-21 13:43:10 -0700166 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700167
168 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700169 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700170 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
171 }
172
Fred Quintana56285a62010-12-02 14:20:51 -0800173 private final Object mCacheLock = new Object();
174 /** protected by the {@link #mCacheLock} */
175 private final HashMap<String, Account[]> mAccountCache = new HashMap<String, Account[]>();
176 /** protected by the {@link #mCacheLock} */
177 private HashMap<Account, HashMap<String, String>> mUserDataCache =
178 new HashMap<Account, HashMap<String, String>>();
179 /** protected by the {@link #mCacheLock} */
180 private HashMap<Account, HashMap<String, String>> mAuthTokenCache =
181 new HashMap<Account, HashMap<String, String>>();
182
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700183 /**
184 * This should only be called by system code. One should only call this after the service
185 * has started.
186 * @return a reference to the AccountManagerService instance
187 * @hide
188 */
189 public static AccountManagerService getSingleton() {
190 return sThis.get();
191 }
Fred Quintana60307342009-03-24 22:48:12 -0700192
Fred Quintana56285a62010-12-02 14:20:51 -0800193 public AccountManagerService(Context context) {
194 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700195 }
196
Fred Quintana56285a62010-12-02 14:20:51 -0800197 public AccountManagerService(Context context, PackageManager packageManager,
198 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700199 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800200 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700201
202 mOpenHelper = new DatabaseHelper(mContext);
203
204 mMessageThread = new HandlerThread("AccountManagerService");
205 mMessageThread.start();
206 mMessageHandler = new MessageHandler(mMessageThread.getLooper());
207
Fred Quintana56285a62010-12-02 14:20:51 -0800208 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800209 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700210
Doug Zongker885cfc232009-10-21 16:52:44 -0700211 mSimWatcher = new SimWatcher(mContext);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700212 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800213
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800214 IntentFilter intentFilter = new IntentFilter();
215 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
216 intentFilter.addDataScheme("package");
217 mContext.registerReceiver(new BroadcastReceiver() {
218 @Override
219 public void onReceive(Context context1, Intent intent) {
220 purgeOldGrants();
221 }
222 }, intentFilter);
223 purgeOldGrants();
224
Fred Quintana56285a62010-12-02 14:20:51 -0800225 validateAccountsAndPopulateCache();
Fred Quintanaafa92b82009-12-01 16:27:03 -0800226 }
227
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800228 private void purgeOldGrants() {
229 synchronized (mCacheLock) {
230 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
231 final Cursor cursor = db.query(TABLE_GRANTS,
232 new String[]{GRANTS_GRANTEE_UID},
233 null, null, GRANTS_GRANTEE_UID, null, null);
234 try {
235 while (cursor.moveToNext()) {
236 final int uid = cursor.getInt(0);
237 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
238 if (packageExists) {
239 continue;
240 }
241 Log.d(TAG, "deleting grants for UID " + uid
242 + " because its package is no longer installed");
243 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
244 new String[]{Integer.toString(uid)});
245 }
246 } finally {
247 cursor.close();
248 }
249 }
250 }
251
Fred Quintana56285a62010-12-02 14:20:51 -0800252 private void validateAccountsAndPopulateCache() {
Fred Quintanaafa92b82009-12-01 16:27:03 -0800253 boolean accountDeleted = false;
254 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
255 Cursor cursor = db.query(TABLE_ACCOUNTS,
256 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
257 null, null, null, null, null);
258 try {
Fred Quintana56285a62010-12-02 14:20:51 -0800259 synchronized (mCacheLock) {
260 mAccountCache.clear();
261 final HashMap<String, ArrayList<String>> accountNamesByType =
262 new HashMap<String, ArrayList<String>>();
263 while (cursor.moveToNext()) {
264 final long accountId = cursor.getLong(0);
265 final String accountType = cursor.getString(1);
266 final String accountName = cursor.getString(2);
267 if (mAuthenticatorCache.getServiceInfo(
268 AuthenticatorDescription.newKey(accountType)) == null) {
269 Log.d(TAG, "deleting account " + accountName + " because type "
270 + accountType + " no longer has a registered authenticator");
271 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
272 accountDeleted = true;
273 final Account account = new Account(accountName, accountType);
274 mUserDataCache.remove(account);
275 mAuthTokenCache.remove(account);
276 } else {
277 ArrayList<String> accountNames = accountNamesByType.get(accountType);
278 if (accountNames == null) {
279 accountNames = new ArrayList<String>();
280 accountNamesByType.put(accountType, accountNames);
281 }
282 accountNames.add(accountName);
283 }
284 }
285 for (HashMap.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
286 final String accountType = cur.getKey();
287 final ArrayList<String> accountNames = cur.getValue();
288 final Account[] accountsForType = new Account[accountNames.size()];
289 int i = 0;
290 for (String accountName : accountNames) {
291 accountsForType[i] = new Account(accountName, accountType);
292 ++i;
293 }
294 mAccountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800295 }
296 }
297 } finally {
298 cursor.close();
299 if (accountDeleted) {
300 sendAccountsChangedBroadcast();
301 }
302 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700303 }
304
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800305 public void onServiceChanged(AuthenticatorDescription desc, boolean removed) {
Fred Quintana56285a62010-12-02 14:20:51 -0800306 validateAccountsAndPopulateCache();
Fred Quintana60307342009-03-24 22:48:12 -0700307 }
308
Fred Quintanaa698f422009-04-08 19:14:54 -0700309 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800310 if (Log.isLoggable(TAG, Log.VERBOSE)) {
311 Log.v(TAG, "getPassword: " + account
312 + ", caller's uid " + Binder.getCallingUid()
313 + ", pid " + Binder.getCallingPid());
314 }
Fred Quintana382601f2010-03-25 12:25:10 -0700315 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700316 checkAuthenticateAccountsPermission(account);
317
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700318 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700319 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700320 return readPasswordFromDatabase(account);
321 } finally {
322 restoreCallingIdentity(identityToken);
323 }
324 }
325
326 private String readPasswordFromDatabase(Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700327 if (account == null) {
328 return null;
329 }
330
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700331 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
332 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
333 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
334 new String[]{account.name, account.type}, null, null, null);
335 try {
336 if (cursor.moveToNext()) {
337 return cursor.getString(0);
338 }
339 return null;
340 } finally {
341 cursor.close();
342 }
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 Quintana56285a62010-12-02 14:20:51 -0800357 return readUserDataFromCache(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 Quintanaffd0cb042009-08-15 21:45:26 -0700399 return insertAccountIntoDatabase(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 Quintanaffd0cb042009-08-15 21:45:26 -0700405 private boolean insertAccountIntoDatabase(Account account, String password, Bundle extras) {
406 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
Fred Quintana743dfad2010-07-15 10:59:25 -0700407 if (account == null) {
408 return false;
409 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700410 db.beginTransaction();
411 try {
412 long numMatches = DatabaseUtils.longForQuery(db,
413 "select count(*) from " + TABLE_ACCOUNTS
414 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
415 new String[]{account.name, account.type});
416 if (numMatches > 0) {
Fred Quintana56285a62010-12-02 14:20:51 -0800417 Log.w(TAG, "insertAccountIntoDatabase: " + account
418 + ", skipping since the account already exists");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700419 return false;
420 }
421 ContentValues values = new ContentValues();
422 values.put(ACCOUNTS_NAME, account.name);
423 values.put(ACCOUNTS_TYPE, account.type);
424 values.put(ACCOUNTS_PASSWORD, password);
425 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
426 if (accountId < 0) {
Fred Quintana56285a62010-12-02 14:20:51 -0800427 Log.w(TAG, "insertAccountIntoDatabase: " + account
428 + ", skipping the DB insert failed");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700429 return false;
430 }
431 if (extras != null) {
432 for (String key : extras.keySet()) {
433 final String value = extras.getString(key);
434 if (insertExtra(db, accountId, key, value) < 0) {
Fred Quintana56285a62010-12-02 14:20:51 -0800435 Log.w(TAG, "insertAccountIntoDatabase: " + account
436 + ", skipping since insertExtra failed for key " + key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700437 return false;
438 }
439 }
440 }
441 db.setTransactionSuccessful();
Fred Quintana56285a62010-12-02 14:20:51 -0800442 insertAccountIntoCache(account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700443 } finally {
444 db.endTransaction();
445 }
Fred Quintanaafd2f542010-12-17 14:12:03 -0800446 sendAccountsChangedBroadcast();
Fred Quintana743dfad2010-07-15 10:59:25 -0700447 return true;
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700448 }
449
Fred Quintana60307342009-03-24 22:48:12 -0700450 private long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
451 ContentValues values = new ContentValues();
452 values.put(EXTRAS_KEY, key);
453 values.put(EXTRAS_ACCOUNTS_ID, accountId);
454 values.put(EXTRAS_VALUE, value);
455 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
456 }
457
Fred Quintana3084a6f2010-01-14 18:02:03 -0800458 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800459 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800460 if (Log.isLoggable(TAG, Log.VERBOSE)) {
461 Log.v(TAG, "hasFeatures: " + account
462 + ", response " + response
463 + ", features " + stringArrayToString(features)
464 + ", caller's uid " + Binder.getCallingUid()
465 + ", pid " + Binder.getCallingPid());
466 }
Fred Quintana382601f2010-03-25 12:25:10 -0700467 if (response == null) throw new IllegalArgumentException("response is null");
468 if (account == null) throw new IllegalArgumentException("account is null");
469 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800470 checkReadAccountsPermission();
471 long identityToken = clearCallingIdentity();
472 try {
473 new TestFeaturesSession(response, account, features).bind();
474 } finally {
475 restoreCallingIdentity(identityToken);
476 }
477 }
478
479 private class TestFeaturesSession extends Session {
480 private final String[] mFeatures;
481 private final Account mAccount;
482
483 public TestFeaturesSession(IAccountManagerResponse response,
484 Account account, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -0800485 super(response, account.type, false /* expectActivityLaunch */,
486 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800487 mFeatures = features;
488 mAccount = account;
489 }
490
491 public void run() throws RemoteException {
492 try {
493 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
494 } catch (RemoteException e) {
495 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
496 }
497 }
498
499 public void onResult(Bundle result) {
500 IAccountManagerResponse response = getResponseAndClose();
501 if (response != null) {
502 try {
503 if (result == null) {
504 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
505 return;
506 }
Fred Quintana56285a62010-12-02 14:20:51 -0800507 if (Log.isLoggable(TAG, Log.VERBOSE)) {
508 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
509 + response);
510 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800511 final Bundle newResult = new Bundle();
512 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
513 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
514 response.onResult(newResult);
515 } catch (RemoteException e) {
516 // if the caller is dead then there is no one to care about remote exceptions
517 if (Log.isLoggable(TAG, Log.VERBOSE)) {
518 Log.v(TAG, "failure while notifying response", e);
519 }
520 }
521 }
522 }
523
524 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800525 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800526 + ", " + mAccount
527 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
528 }
529 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800530
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700531 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800532 if (Log.isLoggable(TAG, Log.VERBOSE)) {
533 Log.v(TAG, "removeAccount: " + account
534 + ", response " + response
535 + ", caller's uid " + Binder.getCallingUid()
536 + ", pid " + Binder.getCallingPid());
537 }
Fred Quintana382601f2010-03-25 12:25:10 -0700538 if (response == null) throw new IllegalArgumentException("response is null");
539 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700540 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700541 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800542
543 cancelNotification(getSigninRequiredNotificationId(account));
544 synchronized(mCredentialsPermissionNotificationIds) {
545 for (Pair<Pair<Account, String>, Integer> pair:
546 mCredentialsPermissionNotificationIds.keySet()) {
547 if (account.equals(pair.first.first)) {
548 int id = mCredentialsPermissionNotificationIds.get(pair);
549 cancelNotification(id);
550 }
551 }
552 }
553
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700554 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700555 new RemoveAccountSession(response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700556 } finally {
557 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700558 }
Fred Quintana60307342009-03-24 22:48:12 -0700559 }
560
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700561 private class RemoveAccountSession extends Session {
562 final Account mAccount;
563 public RemoveAccountSession(IAccountManagerResponse response, Account account) {
Fred Quintana8570f742010-02-18 10:32:54 -0800564 super(response, account.type, false /* expectActivityLaunch */,
565 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700566 mAccount = account;
567 }
568
569 protected String toDebugString(long now) {
570 return super.toDebugString(now) + ", removeAccount"
571 + ", account " + mAccount;
572 }
573
574 public void run() throws RemoteException {
575 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
576 }
577
578 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700579 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
580 && !result.containsKey(AccountManager.KEY_INTENT)) {
581 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700582 if (removalAllowed) {
583 removeAccount(mAccount);
584 }
585 IAccountManagerResponse response = getResponseAndClose();
586 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800587 if (Log.isLoggable(TAG, Log.VERBOSE)) {
588 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
589 + response);
590 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700591 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700592 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700593 try {
594 response.onResult(result2);
595 } catch (RemoteException e) {
596 // ignore
597 }
598 }
599 }
600 super.onResult(result);
601 }
602 }
603
Fred Quintana56285a62010-12-02 14:20:51 -0800604 protected void removeAccount(Account account) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700605 final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
606 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
607 new String[]{account.name, account.type});
Fred Quintana56285a62010-12-02 14:20:51 -0800608 removeAccountFromCache(account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700609 sendAccountsChangedBroadcast();
610 }
611
Fred Quintanaa698f422009-04-08 19:14:54 -0700612 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800613 if (Log.isLoggable(TAG, Log.VERBOSE)) {
614 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
615 + ", caller's uid " + Binder.getCallingUid()
616 + ", pid " + Binder.getCallingPid());
617 }
Fred Quintana382601f2010-03-25 12:25:10 -0700618 if (accountType == null) throw new IllegalArgumentException("accountType is null");
619 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800620 checkManageAccountsOrUseCredentialsPermissions();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700621 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700622 try {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700623 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
624 db.beginTransaction();
625 try {
626 invalidateAuthToken(db, accountType, authToken);
627 db.setTransactionSuccessful();
628 } finally {
629 db.endTransaction();
630 }
Fred Quintana60307342009-03-24 22:48:12 -0700631 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700632 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700633 }
634 }
635
636 private void invalidateAuthToken(SQLiteDatabase db, String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700637 if (authToken == null || accountType == null) {
638 return;
639 }
Fred Quintana33269202009-04-20 16:05:10 -0700640 Cursor cursor = db.rawQuery(
641 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
642 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
643 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
644 + " FROM " + TABLE_ACCOUNTS
645 + " JOIN " + TABLE_AUTHTOKENS
646 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
647 + " = " + AUTHTOKENS_ACCOUNTS_ID
648 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
649 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
650 new String[]{authToken, accountType});
651 try {
652 while (cursor.moveToNext()) {
653 long authTokenId = cursor.getLong(0);
654 String accountName = cursor.getString(1);
655 String authTokenType = cursor.getString(2);
656 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Fred Quintana56285a62010-12-02 14:20:51 -0800657 writeAuthTokenIntoCache(new Account(accountName, accountType), authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700658 }
Fred Quintana33269202009-04-20 16:05:10 -0700659 } finally {
660 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700661 }
662 }
663
664 private boolean saveAuthTokenToDatabase(Account account, String type, String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700665 if (account == null || type == null) {
666 return false;
667 }
Fred Quintana6dfd1382009-09-16 17:32:42 -0700668 cancelNotification(getSigninRequiredNotificationId(account));
Fred Quintana60307342009-03-24 22:48:12 -0700669 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
670 db.beginTransaction();
671 try {
Fred Quintana33269202009-04-20 16:05:10 -0700672 long accountId = getAccountId(db, account);
673 if (accountId < 0) {
674 return false;
675 }
676 db.delete(TABLE_AUTHTOKENS,
677 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
678 new String[]{type});
679 ContentValues values = new ContentValues();
680 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
681 values.put(AUTHTOKENS_TYPE, type);
682 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
683 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintana60307342009-03-24 22:48:12 -0700684 db.setTransactionSuccessful();
Fred Quintana56285a62010-12-02 14:20:51 -0800685 writeAuthTokenIntoCache(account, type, authToken);
Fred Quintana60307342009-03-24 22:48:12 -0700686 return true;
687 }
688 return false;
689 } finally {
690 db.endTransaction();
691 }
692 }
693
Fred Quintanaa698f422009-04-08 19:14:54 -0700694 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -0800695 if (Log.isLoggable(TAG, Log.VERBOSE)) {
696 Log.v(TAG, "peekAuthToken: " + account
697 + ", authTokenType " + authTokenType
698 + ", caller's uid " + Binder.getCallingUid()
699 + ", pid " + Binder.getCallingPid());
700 }
Fred Quintana382601f2010-03-25 12:25:10 -0700701 if (account == null) throw new IllegalArgumentException("account is null");
702 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700703 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700704 long identityToken = clearCallingIdentity();
705 try {
Fred Quintana56285a62010-12-02 14:20:51 -0800706 return readAuthTokenFromCache(account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700707 } finally {
708 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700709 }
Fred Quintana60307342009-03-24 22:48:12 -0700710 }
711
Fred Quintanaa698f422009-04-08 19:14:54 -0700712 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800713 if (Log.isLoggable(TAG, Log.VERBOSE)) {
714 Log.v(TAG, "setAuthToken: " + account
715 + ", authTokenType " + authTokenType
716 + ", caller's uid " + Binder.getCallingUid()
717 + ", pid " + Binder.getCallingPid());
718 }
Fred Quintana382601f2010-03-25 12:25:10 -0700719 if (account == null) throw new IllegalArgumentException("account is null");
720 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700721 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700722 long identityToken = clearCallingIdentity();
723 try {
Fred Quintana6dfd1382009-09-16 17:32:42 -0700724 saveAuthTokenToDatabase(account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700725 } finally {
726 restoreCallingIdentity(identityToken);
727 }
Fred Quintana60307342009-03-24 22:48:12 -0700728 }
729
Fred Quintanaa698f422009-04-08 19:14:54 -0700730 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -0800731 if (Log.isLoggable(TAG, Log.VERBOSE)) {
732 Log.v(TAG, "setAuthToken: " + account
733 + ", caller's uid " + Binder.getCallingUid()
734 + ", pid " + Binder.getCallingPid());
735 }
Fred Quintana382601f2010-03-25 12:25:10 -0700736 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700737 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700738 long identityToken = clearCallingIdentity();
739 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700740 setPasswordInDB(account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700741 } finally {
742 restoreCallingIdentity(identityToken);
743 }
Fred Quintana60307342009-03-24 22:48:12 -0700744 }
745
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700746 private void setPasswordInDB(Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -0700747 if (account == null) {
748 return;
749 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800750 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
751 db.beginTransaction();
752 try {
753 final ContentValues values = new ContentValues();
754 values.put(ACCOUNTS_PASSWORD, password);
755 final long accountId = getAccountId(db, account);
756 if (accountId >= 0) {
757 final String[] argsAccountId = {String.valueOf(accountId)};
758 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
759 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Costin Manolachef5ffe892011-01-19 09:35:32 -0800760 synchronized (mCacheLock) {
761 mAuthTokenCache.remove(account);
762 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -0800763 db.setTransactionSuccessful();
764 }
765 } finally {
766 db.endTransaction();
767 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700768 sendAccountsChangedBroadcast();
769 }
770
Fred Quintana33269202009-04-20 16:05:10 -0700771 private void sendAccountsChangedBroadcast() {
Fred Quintana56285a62010-12-02 14:20:51 -0800772 Log.i(TAG, "the accounts changed, sending broadcast of "
773 + ACCOUNTS_CHANGED_INTENT.getAction());
Fred Quintana33269202009-04-20 16:05:10 -0700774 mContext.sendBroadcast(ACCOUNTS_CHANGED_INTENT);
775 }
776
Fred Quintanaa698f422009-04-08 19:14:54 -0700777 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800778 if (Log.isLoggable(TAG, Log.VERBOSE)) {
779 Log.v(TAG, "clearPassword: " + account
780 + ", caller's uid " + Binder.getCallingUid()
781 + ", pid " + Binder.getCallingPid());
782 }
Fred Quintana382601f2010-03-25 12:25:10 -0700783 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700784 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700785 long identityToken = clearCallingIdentity();
786 try {
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700787 setPasswordInDB(account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700788 } finally {
789 restoreCallingIdentity(identityToken);
790 }
Fred Quintana60307342009-03-24 22:48:12 -0700791 }
792
Fred Quintanaa698f422009-04-08 19:14:54 -0700793 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -0800794 if (Log.isLoggable(TAG, Log.VERBOSE)) {
795 Log.v(TAG, "setUserData: " + account
796 + ", key " + key
797 + ", caller's uid " + Binder.getCallingUid()
798 + ", pid " + Binder.getCallingPid());
799 }
Fred Quintana382601f2010-03-25 12:25:10 -0700800 if (key == null) throw new IllegalArgumentException("key is null");
801 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700802 checkAuthenticateAccountsPermission(account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700803 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700804 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700805 writeUserdataIntoDatabase(account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -0700806 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700807 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700808 }
809 }
810
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700811 private void writeUserdataIntoDatabase(Account account, String key, String value) {
Fred Quintana31957f12009-10-21 13:43:10 -0700812 if (account == null || key == null) {
813 return;
814 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700815 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
816 db.beginTransaction();
817 try {
818 long accountId = getAccountId(db, account);
819 if (accountId < 0) {
820 return;
821 }
822 long extrasId = getExtrasId(db, accountId, key);
823 if (extrasId < 0 ) {
824 extrasId = insertExtra(db, accountId, key, value);
825 if (extrasId < 0) {
826 return;
827 }
828 } else {
829 ContentValues values = new ContentValues();
830 values.put(EXTRAS_VALUE, value);
831 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
832 return;
833 }
834
835 }
836 db.setTransactionSuccessful();
Fred Quintana56285a62010-12-02 14:20:51 -0800837 writeUserDataIntoCache(account, key, value);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700838 } finally {
839 db.endTransaction();
840 }
841 }
842
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700843 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -0800844 if (result == null) {
845 Log.e(TAG, "the result is unexpectedly null", new Exception());
846 }
847 if (Log.isLoggable(TAG, Log.VERBOSE)) {
848 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
849 + response);
850 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700851 try {
852 response.onResult(result);
853 } catch (RemoteException e) {
854 // if the caller is dead then there is no one to care about remote
855 // exceptions
856 if (Log.isLoggable(TAG, Log.VERBOSE)) {
857 Log.v(TAG, "failure while notifying response", e);
858 }
859 }
860 }
861
Costin Manolache5f383ad92010-12-02 16:44:46 -0800862 void getAuthTokenLabel(final IAccountManagerResponse response,
863 final Account account, final String authTokenType) {
864 if (account == null) throw new IllegalArgumentException("account is null");
865 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
866
867 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
868
869 long identityToken = clearCallingIdentity();
870 try {
871 new Session(response, account.type, false,
872 false /* stripAuthTokenFromResult */) {
873 protected String toDebugString(long now) {
874 return super.toDebugString(now) + ", getAuthTokenLabel"
875 + ", " + account
876 + ", authTokenType " + authTokenType;
877 }
878
879 public void run() throws RemoteException {
880 mAuthenticator.getAuthTokenLabel(this, authTokenType);
881 }
882
883 public void onResult(Bundle result) {
884 if (result != null) {
885 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
886 Bundle bundle = new Bundle();
887 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
888 super.onResult(bundle);
889 return;
890 } else {
891 super.onResult(result);
892 }
893 }
894 }.bind();
895 } finally {
896 restoreCallingIdentity(identityToken);
897 }
898 }
899
Fred Quintanaa698f422009-04-08 19:14:54 -0700900 public void getAuthToken(IAccountManagerResponse response, final Account account,
901 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -0800902 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -0800903 if (Log.isLoggable(TAG, Log.VERBOSE)) {
904 Log.v(TAG, "getAuthToken: " + account
905 + ", response " + response
906 + ", authTokenType " + authTokenType
907 + ", notifyOnAuthFailure " + notifyOnAuthFailure
908 + ", expectActivityLaunch " + expectActivityLaunch
909 + ", caller's uid " + Binder.getCallingUid()
910 + ", pid " + Binder.getCallingPid());
911 }
Fred Quintana382601f2010-03-25 12:25:10 -0700912 if (response == null) throw new IllegalArgumentException("response is null");
913 if (account == null) throw new IllegalArgumentException("account is null");
914 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700915 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
916 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -0800917 final int callerPid = Binder.getCallingPid();
918
919 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
920 mAuthenticatorCache.getServiceInfo(
921 AuthenticatorDescription.newKey(account.type));
922 final boolean customTokens =
923 authenticatorInfo != null && authenticatorInfo.type.customTokens;
924
925 // skip the check if customTokens
926 final boolean permissionGranted = customTokens ||
927 permissionIsGranted(account, authTokenType, callerUid);
928
Costin Manolachec6684f92011-01-14 11:25:39 -0800929 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
930 loginOptionsIn;
Costin Manolachea40c6302010-12-13 14:50:45 -0800931 if (customTokens) {
932 // let authenticator know the identity of the caller
933 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
934 loginOptions.putInt(AccountManager.KEY_CALLER_PID, callerPid);
Costin Manolached6060452011-01-24 16:11:36 -0800935 if (notifyOnAuthFailure) {
936 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
937 }
Costin Manolachea40c6302010-12-13 14:50:45 -0800938 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700939
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700940 long identityToken = clearCallingIdentity();
941 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700942 // if the caller has permission, do the peek. otherwise go the more expensive
943 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -0800944 if (!customTokens && permissionGranted) {
Fred Quintana56285a62010-12-02 14:20:51 -0800945 String authToken = readAuthTokenFromCache(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700946 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700947 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700948 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
949 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
950 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700951 onResult(response, result);
952 return;
Fred Quintanaa698f422009-04-08 19:14:54 -0700953 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700954 }
955
Fred Quintana8570f742010-02-18 10:32:54 -0800956 new Session(response, account.type, expectActivityLaunch,
957 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700958 protected String toDebugString(long now) {
959 if (loginOptions != null) loginOptions.keySet();
960 return super.toDebugString(now) + ", getAuthToken"
961 + ", " + account
962 + ", authTokenType " + authTokenType
963 + ", loginOptions " + loginOptions
964 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
965 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700966
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700967 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700968 // If the caller doesn't have permission then create and return the
969 // "grant permission" intent instead of the "getAuthToken" intent.
970 if (!permissionGranted) {
971 mAuthenticator.getAuthTokenLabel(this, authTokenType);
972 } else {
973 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
974 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700975 }
976
977 public void onResult(Bundle result) {
978 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700979 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700980 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
981 new AccountAuthenticatorResponse(this),
982 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700983 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700984 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700985 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700986 onResult(bundle);
987 return;
988 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700989 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700990 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700991 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
992 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700993 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700994 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700995 "the type and name should not be empty");
996 return;
997 }
Costin Manolachea40c6302010-12-13 14:50:45 -0800998 if (!customTokens) {
999 saveAuthTokenToDatabase(new Account(name, type),
1000 authTokenType, authToken);
1001 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001002 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001003
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001004 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001005 if (intent != null && notifyOnAuthFailure && !customTokens) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001006 doNotification(
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001007 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001008 intent);
1009 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001010 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001011 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001012 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001013 }.bind();
1014 } finally {
1015 restoreCallingIdentity(identityToken);
1016 }
Fred Quintana60307342009-03-24 22:48:12 -07001017 }
1018
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001019 private void createNoCredentialsPermissionNotification(Account account, Intent intent) {
1020 int uid = intent.getIntExtra(
1021 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1022 String authTokenType = intent.getStringExtra(
1023 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1024 String authTokenLabel = intent.getStringExtra(
1025 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1026
1027 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1028 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001029 final String titleAndSubtitle =
1030 mContext.getString(R.string.permission_request_notification_with_subtitle,
1031 account.name);
1032 final int index = titleAndSubtitle.indexOf('\n');
1033 final String title = titleAndSubtitle.substring(0, index);
1034 final String subtitle = titleAndSubtitle.substring(index + 1);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001035 n.setLatestEventInfo(mContext,
Eric Fischeree452ee2009-08-31 17:58:06 -07001036 title, subtitle,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001037 PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -08001038 installNotification(getCredentialPermissionNotificationId(account, authTokenType, uid), n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001039 }
1040
Costin Manolache5f383ad92010-12-02 16:44:46 -08001041 String getAccountLabel(String accountType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001042 RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo =
Costin Manolache5f383ad92010-12-02 16:44:46 -08001043 mAuthenticatorCache.getServiceInfo(
1044 AuthenticatorDescription.newKey(accountType));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001045 if (serviceInfo == null) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001046 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001047 }
1048
1049 final Context authContext;
1050 try {
1051 authContext = mContext.createPackageContext(
Costin Manolache5f383ad92010-12-02 16:44:46 -08001052 serviceInfo.type.packageName, 0);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001053 } catch (PackageManager.NameNotFoundException e) {
Costin Manolache5f383ad92010-12-02 16:44:46 -08001054 throw new IllegalArgumentException("unknown account type: " + accountType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001055 }
Costin Manolache5f383ad92010-12-02 16:44:46 -08001056 return authContext.getString(serviceInfo.type.labelId);
1057 }
1058
1059 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1060 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001061
1062 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache9ec17362011-01-17 12:12:37 -08001063 // See FLAT_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
1064 // Since it was set in Eclair+ we can't change it without breaking apps using
1065 // the intent from a non-Activity context.
1066 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001067 intent.addCategory(
1068 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001069
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001070 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001071 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1072 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001073 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001074
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001075 return intent;
1076 }
1077
1078 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1079 int uid) {
1080 Integer id;
1081 synchronized(mCredentialsPermissionNotificationIds) {
1082 final Pair<Pair<Account, String>, Integer> key =
1083 new Pair<Pair<Account, String>, Integer>(
1084 new Pair<Account, String>(account, authTokenType), uid);
1085 id = mCredentialsPermissionNotificationIds.get(key);
1086 if (id == null) {
1087 id = mNotificationIds.incrementAndGet();
1088 mCredentialsPermissionNotificationIds.put(key, id);
1089 }
1090 }
1091 return id;
1092 }
1093
1094 private Integer getSigninRequiredNotificationId(Account account) {
1095 Integer id;
1096 synchronized(mSigninRequiredNotificationIds) {
1097 id = mSigninRequiredNotificationIds.get(account);
1098 if (id == null) {
1099 id = mNotificationIds.incrementAndGet();
1100 mSigninRequiredNotificationIds.put(account, id);
1101 }
1102 }
1103 return id;
1104 }
1105
Fred Quintana33269202009-04-20 16:05:10 -07001106 public void addAcount(final IAccountManagerResponse response, final String accountType,
1107 final String authTokenType, final String[] requiredFeatures,
Fred Quintanaa698f422009-04-08 19:14:54 -07001108 final boolean expectActivityLaunch, final Bundle options) {
Fred Quintana56285a62010-12-02 14:20:51 -08001109 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1110 Log.v(TAG, "addAccount: accountType " + accountType
1111 + ", response " + response
1112 + ", authTokenType " + authTokenType
1113 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1114 + ", expectActivityLaunch " + expectActivityLaunch
1115 + ", caller's uid " + Binder.getCallingUid()
1116 + ", pid " + Binder.getCallingPid());
1117 }
Fred Quintana382601f2010-03-25 12:25:10 -07001118 if (response == null) throw new IllegalArgumentException("response is null");
1119 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001120 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001121 long identityToken = clearCallingIdentity();
1122 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001123 new Session(response, accountType, expectActivityLaunch,
1124 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001125 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001126 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001127 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001128 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001129
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001130 protected String toDebugString(long now) {
1131 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001132 + ", accountType " + accountType
1133 + ", requiredFeatures "
1134 + (requiredFeatures != null
1135 ? TextUtils.join(",", requiredFeatures)
1136 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001137 }
1138 }.bind();
1139 } finally {
1140 restoreCallingIdentity(identityToken);
1141 }
Fred Quintana60307342009-03-24 22:48:12 -07001142 }
1143
Fred Quintanaa698f422009-04-08 19:14:54 -07001144 public void confirmCredentials(IAccountManagerResponse response,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001145 final Account account, final Bundle options, final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001146 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1147 Log.v(TAG, "confirmCredentials: " + account
1148 + ", response " + response
1149 + ", expectActivityLaunch " + expectActivityLaunch
1150 + ", caller's uid " + Binder.getCallingUid()
1151 + ", pid " + Binder.getCallingPid());
1152 }
Fred Quintana382601f2010-03-25 12:25:10 -07001153 if (response == null) throw new IllegalArgumentException("response is null");
1154 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001155 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001156 long identityToken = clearCallingIdentity();
1157 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001158 new Session(response, account.type, expectActivityLaunch,
1159 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001160 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001161 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001162 }
1163 protected String toDebugString(long now) {
1164 return super.toDebugString(now) + ", confirmCredentials"
1165 + ", " + account;
1166 }
1167 }.bind();
1168 } finally {
1169 restoreCallingIdentity(identityToken);
1170 }
Fred Quintana60307342009-03-24 22:48:12 -07001171 }
1172
Fred Quintanaa698f422009-04-08 19:14:54 -07001173 public void updateCredentials(IAccountManagerResponse response, final Account account,
1174 final String authTokenType, final boolean expectActivityLaunch,
1175 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001176 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1177 Log.v(TAG, "updateCredentials: " + account
1178 + ", response " + response
1179 + ", authTokenType " + authTokenType
1180 + ", expectActivityLaunch " + expectActivityLaunch
1181 + ", caller's uid " + Binder.getCallingUid()
1182 + ", pid " + Binder.getCallingPid());
1183 }
Fred Quintana382601f2010-03-25 12:25:10 -07001184 if (response == null) throw new IllegalArgumentException("response is null");
1185 if (account == null) throw new IllegalArgumentException("account is null");
1186 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001187 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001188 long identityToken = clearCallingIdentity();
1189 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001190 new Session(response, account.type, expectActivityLaunch,
1191 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001192 public void run() throws RemoteException {
1193 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1194 }
1195 protected String toDebugString(long now) {
1196 if (loginOptions != null) loginOptions.keySet();
1197 return super.toDebugString(now) + ", updateCredentials"
1198 + ", " + account
1199 + ", authTokenType " + authTokenType
1200 + ", loginOptions " + loginOptions;
1201 }
1202 }.bind();
1203 } finally {
1204 restoreCallingIdentity(identityToken);
1205 }
Fred Quintana60307342009-03-24 22:48:12 -07001206 }
1207
Fred Quintanaa698f422009-04-08 19:14:54 -07001208 public void editProperties(IAccountManagerResponse response, final String accountType,
1209 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001210 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1211 Log.v(TAG, "editProperties: accountType " + accountType
1212 + ", response " + response
1213 + ", expectActivityLaunch " + expectActivityLaunch
1214 + ", caller's uid " + Binder.getCallingUid()
1215 + ", pid " + Binder.getCallingPid());
1216 }
Fred Quintana382601f2010-03-25 12:25:10 -07001217 if (response == null) throw new IllegalArgumentException("response is null");
1218 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001219 checkManageAccountsPermission();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001220 long identityToken = clearCallingIdentity();
1221 try {
Fred Quintana8570f742010-02-18 10:32:54 -08001222 new Session(response, accountType, expectActivityLaunch,
1223 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001224 public void run() throws RemoteException {
1225 mAuthenticator.editProperties(this, mAccountType);
1226 }
1227 protected String toDebugString(long now) {
1228 return super.toDebugString(now) + ", editProperties"
1229 + ", accountType " + accountType;
1230 }
1231 }.bind();
1232 } finally {
1233 restoreCallingIdentity(identityToken);
1234 }
Fred Quintana60307342009-03-24 22:48:12 -07001235 }
1236
Fred Quintana33269202009-04-20 16:05:10 -07001237 private class GetAccountsByTypeAndFeatureSession extends Session {
1238 private final String[] mFeatures;
1239 private volatile Account[] mAccountsOfType = null;
1240 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1241 private volatile int mCurrentAccount = 0;
1242
1243 public GetAccountsByTypeAndFeatureSession(IAccountManagerResponse response,
1244 String type, String[] features) {
Fred Quintana8570f742010-02-18 10:32:54 -08001245 super(response, type, false /* expectActivityLaunch */,
1246 true /* stripAuthTokenFromResult */);
Fred Quintana33269202009-04-20 16:05:10 -07001247 mFeatures = features;
1248 }
1249
1250 public void run() throws RemoteException {
Fred Quintana56285a62010-12-02 14:20:51 -08001251 mAccountsOfType = getAccountsByTypeFromCache(mAccountType);
Fred Quintana33269202009-04-20 16:05:10 -07001252 // check whether each account matches the requested features
1253 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1254 mCurrentAccount = 0;
1255
1256 checkAccount();
1257 }
1258
1259 public void checkAccount() {
1260 if (mCurrentAccount >= mAccountsOfType.length) {
1261 sendResult();
1262 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001263 }
Fred Quintana33269202009-04-20 16:05:10 -07001264
Fred Quintana29e94b82010-03-10 12:11:51 -08001265 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1266 if (accountAuthenticator == null) {
1267 // It is possible that the authenticator has died, which is indicated by
1268 // mAuthenticator being set to null. If this happens then just abort.
1269 // There is no need to send back a result or error in this case since
1270 // that already happened when mAuthenticator was cleared.
1271 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1272 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1273 + " connected to the authenticator, " + toDebugString());
1274 }
1275 return;
1276 }
Fred Quintana33269202009-04-20 16:05:10 -07001277 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001278 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001279 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001280 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001281 }
1282 }
1283
1284 public void onResult(Bundle result) {
1285 mNumResults++;
1286 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001287 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001288 return;
1289 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001290 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001291 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1292 }
1293 mCurrentAccount++;
1294 checkAccount();
1295 }
1296
1297 public void sendResult() {
1298 IAccountManagerResponse response = getResponseAndClose();
1299 if (response != null) {
1300 try {
1301 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1302 for (int i = 0; i < accounts.length; i++) {
1303 accounts[i] = mAccountsWithFeatures.get(i);
1304 }
Fred Quintana56285a62010-12-02 14:20:51 -08001305 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1306 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1307 + response);
1308 }
Fred Quintana33269202009-04-20 16:05:10 -07001309 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001310 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001311 response.onResult(result);
1312 } catch (RemoteException e) {
1313 // if the caller is dead then there is no one to care about remote exceptions
1314 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1315 Log.v(TAG, "failure while notifying response", e);
1316 }
1317 }
1318 }
1319 }
1320
1321
1322 protected String toDebugString(long now) {
1323 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1324 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1325 }
1326 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001327
1328 public Account[] getAccounts(String type) {
Fred Quintana56285a62010-12-02 14:20:51 -08001329 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1330 Log.v(TAG, "getAccounts: accountType " + type
1331 + ", caller's uid " + Binder.getCallingUid()
1332 + ", pid " + Binder.getCallingPid());
1333 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001334 checkReadAccountsPermission();
1335 long identityToken = clearCallingIdentity();
1336 try {
Fred Quintana56285a62010-12-02 14:20:51 -08001337 return getAccountsByTypeFromCache(type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001338 } finally {
1339 restoreCallingIdentity(identityToken);
1340 }
1341 }
1342
1343 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001344 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001345 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1346 Log.v(TAG, "getAccounts: accountType " + type
1347 + ", response " + response
1348 + ", features " + stringArrayToString(features)
1349 + ", caller's uid " + Binder.getCallingUid()
1350 + ", pid " + Binder.getCallingPid());
1351 }
Fred Quintana382601f2010-03-25 12:25:10 -07001352 if (response == null) throw new IllegalArgumentException("response is null");
1353 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001354 checkReadAccountsPermission();
Fred Quintana33269202009-04-20 16:05:10 -07001355 long identityToken = clearCallingIdentity();
1356 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001357 if (features == null || features.length == 0) {
Fred Quintana56285a62010-12-02 14:20:51 -08001358 Account[] accounts = getAccountsByTypeFromCache(type);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001359 Bundle result = new Bundle();
1360 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1361 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001362 return;
1363 }
Fred Quintana33269202009-04-20 16:05:10 -07001364 new GetAccountsByTypeAndFeatureSession(response, type, features).bind();
1365 } finally {
1366 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001367 }
1368 }
1369
Fred Quintana60307342009-03-24 22:48:12 -07001370 private long getAccountId(SQLiteDatabase db, Account account) {
1371 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001372 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001373 try {
1374 if (cursor.moveToNext()) {
1375 return cursor.getLong(0);
1376 }
1377 return -1;
1378 } finally {
1379 cursor.close();
1380 }
1381 }
1382
1383 private long getExtrasId(SQLiteDatabase db, long accountId, String key) {
1384 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1385 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1386 new String[]{key}, null, null, null);
1387 try {
1388 if (cursor.moveToNext()) {
1389 return cursor.getLong(0);
1390 }
1391 return -1;
1392 } finally {
1393 cursor.close();
1394 }
1395 }
1396
Fred Quintanaa698f422009-04-08 19:14:54 -07001397 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001398 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001399 IAccountManagerResponse mResponse;
1400 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001401 final boolean mExpectActivityLaunch;
1402 final long mCreationTime;
1403
Fred Quintana33269202009-04-20 16:05:10 -07001404 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001405 private int mNumRequestContinued = 0;
1406 private int mNumErrors = 0;
1407
Fred Quintana60307342009-03-24 22:48:12 -07001408
1409 IAccountAuthenticator mAuthenticator = null;
1410
Fred Quintana8570f742010-02-18 10:32:54 -08001411 private final boolean mStripAuthTokenFromResult;
1412
Fred Quintanaa698f422009-04-08 19:14:54 -07001413 public Session(IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001414 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001415 super();
Fred Quintanaa698f422009-04-08 19:14:54 -07001416 if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001417 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintana8570f742010-02-18 10:32:54 -08001418 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001419 mResponse = response;
1420 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001421 mExpectActivityLaunch = expectActivityLaunch;
1422 mCreationTime = SystemClock.elapsedRealtime();
1423 synchronized (mSessions) {
1424 mSessions.put(toString(), this);
1425 }
1426 try {
1427 response.asBinder().linkToDeath(this, 0 /* flags */);
1428 } catch (RemoteException e) {
1429 mResponse = null;
1430 binderDied();
1431 }
Fred Quintana60307342009-03-24 22:48:12 -07001432 }
1433
Fred Quintanaa698f422009-04-08 19:14:54 -07001434 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07001435 if (mResponse == null) {
1436 // this session has already been closed
1437 return null;
1438 }
Fred Quintana60307342009-03-24 22:48:12 -07001439 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07001440 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07001441 return response;
1442 }
1443
Fred Quintanaa698f422009-04-08 19:14:54 -07001444 private void close() {
1445 synchronized (mSessions) {
1446 if (mSessions.remove(toString()) == null) {
1447 // the session was already closed, so bail out now
1448 return;
1449 }
1450 }
1451 if (mResponse != null) {
1452 // stop listening for response deaths
1453 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
1454
1455 // clear this so that we don't accidentally send any further results
1456 mResponse = null;
1457 }
1458 cancelTimeout();
1459 unbind();
1460 }
1461
1462 public void binderDied() {
1463 mResponse = null;
1464 close();
1465 }
1466
1467 protected String toDebugString() {
1468 return toDebugString(SystemClock.elapsedRealtime());
1469 }
1470
1471 protected String toDebugString(long now) {
1472 return "Session: expectLaunch " + mExpectActivityLaunch
1473 + ", connected " + (mAuthenticator != null)
1474 + ", stats (" + mNumResults + "/" + mNumRequestContinued
1475 + "/" + mNumErrors + ")"
1476 + ", lifetime " + ((now - mCreationTime) / 1000.0);
1477 }
1478
Fred Quintana60307342009-03-24 22:48:12 -07001479 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001480 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1481 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
1482 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001483 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001484 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001485 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07001486 }
1487 }
1488
1489 private void unbind() {
1490 if (mAuthenticator != null) {
1491 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07001492 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07001493 }
1494 }
1495
1496 public void scheduleTimeout() {
1497 mMessageHandler.sendMessageDelayed(
1498 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
1499 }
1500
1501 public void cancelTimeout() {
1502 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
1503 }
1504
Fred Quintanab839afc2009-10-14 15:57:28 -07001505 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07001506 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07001507 try {
1508 run();
1509 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001510 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001511 "remote exception");
1512 }
Fred Quintana60307342009-03-24 22:48:12 -07001513 }
1514
Fred Quintanab839afc2009-10-14 15:57:28 -07001515 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001516 mAuthenticator = null;
1517 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001518 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001519 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001520 "disconnected");
Fred Quintana60307342009-03-24 22:48:12 -07001521 }
1522 }
1523
Fred Quintanab839afc2009-10-14 15:57:28 -07001524 public abstract void run() throws RemoteException;
1525
Fred Quintana60307342009-03-24 22:48:12 -07001526 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07001527 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001528 if (response != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001529 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07001530 "timeout");
Fred Quintana60307342009-03-24 22:48:12 -07001531 }
1532 }
1533
Fred Quintanaa698f422009-04-08 19:14:54 -07001534 public void onResult(Bundle result) {
1535 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001536 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
1537 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1538 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001539 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
1540 Account account = new Account(accountName, accountType);
1541 cancelNotification(getSigninRequiredNotificationId(account));
1542 }
Fred Quintana60307342009-03-24 22:48:12 -07001543 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001544 IAccountManagerResponse response;
1545 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001546 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001547 response = mResponse;
1548 } else {
1549 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07001550 }
Fred Quintana60307342009-03-24 22:48:12 -07001551 if (response != null) {
1552 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07001553 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001554 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1555 Log.v(TAG, getClass().getSimpleName()
1556 + " calling onError() on response " + response);
1557 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001558 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07001559 "null bundle returned");
1560 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08001561 if (mStripAuthTokenFromResult) {
1562 result.remove(AccountManager.KEY_AUTHTOKEN);
1563 }
Fred Quintana56285a62010-12-02 14:20:51 -08001564 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1565 Log.v(TAG, getClass().getSimpleName()
1566 + " calling onResult() on response " + response);
1567 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001568 response.onResult(result);
1569 }
Fred Quintana60307342009-03-24 22:48:12 -07001570 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001571 // if the caller is dead then there is no one to care about remote exceptions
1572 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1573 Log.v(TAG, "failure while notifying response", e);
1574 }
Fred Quintana60307342009-03-24 22:48:12 -07001575 }
1576 }
1577 }
Fred Quintana60307342009-03-24 22:48:12 -07001578
Fred Quintanaa698f422009-04-08 19:14:54 -07001579 public void onRequestContinued() {
1580 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07001581 }
1582
1583 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001584 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07001585 IAccountManagerResponse response = getResponseAndClose();
1586 if (response != null) {
1587 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001588 Log.v(TAG, getClass().getSimpleName()
1589 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07001590 }
1591 try {
1592 response.onError(errorCode, errorMessage);
1593 } catch (RemoteException e) {
1594 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1595 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
1596 }
1597 }
1598 } else {
1599 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1600 Log.v(TAG, "Session.onError: already closed");
1601 }
Fred Quintana60307342009-03-24 22:48:12 -07001602 }
1603 }
Fred Quintanab839afc2009-10-14 15:57:28 -07001604
1605 /**
1606 * find the component name for the authenticator and initiate a bind
1607 * if no authenticator or the bind fails then return false, otherwise return true
1608 */
1609 private boolean bindToAuthenticator(String authenticatorType) {
1610 AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo =
1611 mAuthenticatorCache.getServiceInfo(
1612 AuthenticatorDescription.newKey(authenticatorType));
1613 if (authenticatorInfo == null) {
1614 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1615 Log.v(TAG, "there is no authenticator for " + authenticatorType
1616 + ", bailing out");
1617 }
1618 return false;
1619 }
1620
1621 Intent intent = new Intent();
1622 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
1623 intent.setComponent(authenticatorInfo.componentName);
1624 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1625 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
1626 }
1627 if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
1628 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1629 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
1630 }
1631 return false;
1632 }
1633
1634
1635 return true;
1636 }
Fred Quintana60307342009-03-24 22:48:12 -07001637 }
1638
1639 private class MessageHandler extends Handler {
1640 MessageHandler(Looper looper) {
1641 super(looper);
1642 }
Costin Manolache3348f142009-09-29 18:58:36 -07001643
Fred Quintana60307342009-03-24 22:48:12 -07001644 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07001645 switch (msg.what) {
1646 case MESSAGE_TIMED_OUT:
1647 Session session = (Session)msg.obj;
1648 session.onTimedOut();
1649 break;
1650
1651 default:
1652 throw new IllegalStateException("unhandled message: " + msg.what);
1653 }
1654 }
1655 }
1656
Oscar Montemayora8529f62009-11-18 10:14:20 -08001657 private static String getDatabaseName() {
1658 if(Environment.isEncryptedFilesystemEnabled()) {
1659 // Hard-coded path in case of encrypted file system
1660 return Environment.getSystemSecureDirectory().getPath() + File.separator + DATABASE_NAME;
1661 } else {
1662 // Regular path in case of non-encrypted file system
1663 return DATABASE_NAME;
1664 }
1665 }
1666
Fred Quintana60307342009-03-24 22:48:12 -07001667 private class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001668
Fred Quintana60307342009-03-24 22:48:12 -07001669 public DatabaseHelper(Context context) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08001670 super(context, AccountManagerService.getDatabaseName(), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07001671 }
1672
1673 @Override
1674 public void onCreate(SQLiteDatabase db) {
1675 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
1676 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1677 + ACCOUNTS_NAME + " TEXT NOT NULL, "
1678 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
1679 + ACCOUNTS_PASSWORD + " TEXT, "
1680 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
1681
1682 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
1683 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1684 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1685 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
1686 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
1687 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
1688
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001689 createGrantsTable(db);
1690
Fred Quintana60307342009-03-24 22:48:12 -07001691 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
1692 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
1693 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
1694 + EXTRAS_KEY + " TEXT NOT NULL, "
1695 + EXTRAS_VALUE + " TEXT, "
1696 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
1697
1698 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
1699 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
1700 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07001701
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001702 createAccountsDeletionTrigger(db);
1703 }
1704
1705 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001706 db.execSQL(""
1707 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
1708 + " BEGIN"
1709 + " DELETE FROM " + TABLE_AUTHTOKENS
1710 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
1711 + " DELETE FROM " + TABLE_EXTRAS
1712 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001713 + " DELETE FROM " + TABLE_GRANTS
1714 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07001715 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07001716 }
1717
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001718 private void createGrantsTable(SQLiteDatabase db) {
1719 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
1720 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
1721 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
1722 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
1723 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
1724 + "," + GRANTS_GRANTEE_UID + "))");
1725 }
1726
Fred Quintana60307342009-03-24 22:48:12 -07001727 @Override
1728 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07001729 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07001730
Fred Quintanaa698f422009-04-08 19:14:54 -07001731 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001732 // no longer need to do anything since the work is done
1733 // when upgrading from version 2
1734 oldVersion++;
1735 }
1736
1737 if (oldVersion == 2) {
1738 createGrantsTable(db);
1739 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
1740 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07001741 oldVersion++;
1742 }
Costin Manolache3348f142009-09-29 18:58:36 -07001743
1744 if (oldVersion == 3) {
1745 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
1746 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
1747 oldVersion++;
1748 }
Fred Quintana60307342009-03-24 22:48:12 -07001749 }
1750
1751 @Override
1752 public void onOpen(SQLiteDatabase db) {
1753 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
1754 }
1755 }
1756
1757 private void setMetaValue(String key, String value) {
1758 ContentValues values = new ContentValues();
1759 values.put(META_KEY, key);
1760 values.put(META_VALUE, value);
1761 mOpenHelper.getWritableDatabase().replace(TABLE_META, META_KEY, values);
1762 }
1763
1764 private String getMetaValue(String key) {
1765 Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_META,
1766 new String[]{META_VALUE}, META_KEY + "=?", new String[]{key}, null, null, null);
1767 try {
1768 if (c.moveToNext()) {
1769 return c.getString(0);
1770 }
1771 return null;
1772 } finally {
1773 c.close();
1774 }
1775 }
1776
1777 private class SimWatcher extends BroadcastReceiver {
1778 public SimWatcher(Context context) {
1779 // Re-scan the SIM card when the SIM state changes, and also if
1780 // the disk recovers from a full state (we may have failed to handle
1781 // things properly while the disk was full).
1782 final IntentFilter filter = new IntentFilter();
1783 filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
1784 filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
1785 context.registerReceiver(this, filter);
1786 }
Costin Manolache3348f142009-09-29 18:58:36 -07001787
Fred Quintana60307342009-03-24 22:48:12 -07001788 /**
1789 * Compare the IMSI to the one stored in the login service's
1790 * database. If they differ, erase all passwords and
1791 * authtokens (and store the new IMSI).
1792 */
1793 @Override
1794 public void onReceive(Context context, Intent intent) {
Doug Zongker885cfc232009-10-21 16:52:44 -07001795 // Check IMSI on every update; nothing happens if the IMSI
1796 // is missing or unchanged.
1797 TelephonyManager telephonyManager =
1798 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
1799 if (telephonyManager == null) {
1800 Log.w(TAG, "failed to get TelephonyManager");
1801 return;
1802 }
1803 String imsi = telephonyManager.getSubscriberId();
1804
1805 // If the subscriber ID is an empty string, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001806 if (TextUtils.isEmpty(imsi)) return;
1807
Doug Zongker885cfc232009-10-21 16:52:44 -07001808 // If the current IMSI matches what's stored, don't do anything.
Fred Quintana60307342009-03-24 22:48:12 -07001809 String storedImsi = getMetaValue("imsi");
Fred Quintana60307342009-03-24 22:48:12 -07001810 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1811 Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
1812 }
Doug Zongker885cfc232009-10-21 16:52:44 -07001813 if (imsi.equals(storedImsi)) return;
1814
1815 // If a CDMA phone is unprovisioned, getSubscriberId()
1816 // will return a different value, but we *don't* erase the
1817 // passwords. We only erase them if it has a different
1818 // subscriber ID once it's provisioned.
Wink Saville9d72be32011-02-01 19:22:15 -08001819 if (telephonyManager.getCurrentPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
Doug Zongker885cfc232009-10-21 16:52:44 -07001820 IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
1821 if (service == null) {
1822 Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
1823 return;
1824 }
1825 ITelephony telephony = ITelephony.Stub.asInterface(service);
1826 if (telephony == null) {
1827 Log.w(TAG, "failed to get ITelephony interface");
1828 return;
1829 }
1830 boolean needsProvisioning;
1831 try {
Wink Saville4d8ae852010-05-24 17:50:32 -07001832 needsProvisioning = telephony.needsOtaServiceProvisioning();
Doug Zongker885cfc232009-10-21 16:52:44 -07001833 } catch (RemoteException e) {
1834 Log.w(TAG, "exception while checking provisioning", e);
1835 // default to NOT wiping out the passwords
1836 needsProvisioning = true;
1837 }
1838 if (needsProvisioning) {
1839 // if the phone needs re-provisioning, don't do anything.
1840 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1841 Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
1842 storedImsi);
1843 }
1844 return;
1845 }
1846 }
Fred Quintana60307342009-03-24 22:48:12 -07001847
jsh5b462472009-09-01 16:13:55 -07001848 if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
Jim Miller27844c32009-09-11 17:14:04 -07001849 Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
1850 + "stored=" + storedImsi + ", current=" + imsi + ")");
Fred Quintana60307342009-03-24 22:48:12 -07001851 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1852 db.beginTransaction();
1853 try {
1854 db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
1855 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
Costin Manolachef5ffe892011-01-19 09:35:32 -08001856
1857 synchronized (mCacheLock) {
1858 mAuthTokenCache = new HashMap<Account, HashMap<String, String>>();
1859 }
1860
Fred Quintana60307342009-03-24 22:48:12 -07001861 db.setTransactionSuccessful();
1862 } finally {
1863 db.endTransaction();
1864 }
Fred Quintana743dfad2010-07-15 10:59:25 -07001865 sendAccountsChangedBroadcast();
Fred Quintana60307342009-03-24 22:48:12 -07001866 }
1867 setMetaValue("imsi", imsi);
1868 }
1869 }
1870
1871 public IBinder onBind(Intent intent) {
1872 return asBinder();
1873 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001874
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001875 /**
1876 * Searches array of arguments for the specified string
1877 * @param args array of argument strings
1878 * @param value value to search for
1879 * @return true if the value is contained in the array
1880 */
1881 private static boolean scanArgs(String[] args, String value) {
1882 if (args != null) {
1883 for (String arg : args) {
1884 if (value.equals(arg)) {
1885 return true;
1886 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001887 }
1888 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001889 return false;
1890 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001891
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001892 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
1893 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Fred Quintanaa698f422009-04-08 19:14:54 -07001894
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001895 if (isCheckinRequest) {
1896 // This is a checkin request. *Only* upload the account types and the count of each.
1897 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1898
1899 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
1900 null, null, ACCOUNTS_TYPE, null, null);
1901 try {
1902 while (cursor.moveToNext()) {
1903 // print type,count
1904 fout.println(cursor.getString(0) + "," + cursor.getString(1));
1905 }
1906 } finally {
1907 if (cursor != null) {
1908 cursor.close();
1909 }
1910 }
1911 } else {
Fred Quintana56285a62010-12-02 14:20:51 -08001912 Account[] accounts = getAccountsByTypeFromCache(null /* type */);
Fred Quintana307da1a2010-01-21 14:24:20 -08001913 fout.println("Accounts: " + accounts.length);
1914 for (Account account : accounts) {
1915 fout.println(" " + account);
1916 }
1917
1918 fout.println();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001919 synchronized (mSessions) {
1920 final long now = SystemClock.elapsedRealtime();
Fred Quintana307da1a2010-01-21 14:24:20 -08001921 fout.println("Active Sessions: " + mSessions.size());
Jason Parks1cd7d0e2009-09-28 14:48:34 -07001922 for (Session session : mSessions.values()) {
1923 fout.println(" " + session.toDebugString(now));
1924 }
1925 }
1926
1927 fout.println();
1928 mAuthenticatorCache.dump(fd, fout, args);
1929 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001930 }
1931
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001932 private void doNotification(Account account, CharSequence message, Intent intent) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001933 long identityToken = clearCallingIdentity();
1934 try {
1935 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1936 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
1937 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001938
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001939 if (intent.getComponent() != null &&
1940 GrantCredentialsPermissionActivity.class.getName().equals(
1941 intent.getComponent().getClassName())) {
1942 createNoCredentialsPermissionNotification(account, intent);
1943 } else {
Fred Quintana33f889a2009-09-14 17:31:26 -07001944 final Integer notificationId = getSigninRequiredNotificationId(account);
1945 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001946 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1947 0 /* when */);
Fred Quintana33f889a2009-09-14 17:31:26 -07001948 final String notificationTitleFormat =
1949 mContext.getText(R.string.notification_title).toString();
1950 n.setLatestEventInfo(mContext,
1951 String.format(notificationTitleFormat, account.name),
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001952 message, PendingIntent.getActivity(
1953 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
Fred Quintana56285a62010-12-02 14:20:51 -08001954 installNotification(notificationId, n);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001955 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001956 } finally {
1957 restoreCallingIdentity(identityToken);
1958 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001959 }
1960
Fred Quintana56285a62010-12-02 14:20:51 -08001961 protected void installNotification(final int notificationId, final Notification n) {
1962 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
1963 .notify(notificationId, n);
1964 }
1965
1966 protected void cancelNotification(int id) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001967 long identityToken = clearCallingIdentity();
1968 try {
1969 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001970 .cancel(id);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001971 } finally {
1972 restoreCallingIdentity(identityToken);
1973 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001974 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001975
Fred Quintanab38eb142010-02-24 13:40:54 -08001976 /** Succeeds if any of the specified permissions are granted. */
1977 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001978 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08001979
1980 for (String perm : permissions) {
1981 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
1982 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08001983 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08001984 }
1985 return;
1986 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001987 }
Fred Quintanab38eb142010-02-24 13:40:54 -08001988
1989 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08001990 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08001991 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001992 }
1993
Fred Quintana7be59642009-08-24 18:29:25 -07001994 private boolean inSystemImage(int callerUid) {
Fred Quintana56285a62010-12-02 14:20:51 -08001995 String[] packages = mPackageManager.getPackagesForUid(callerUid);
Fred Quintana7be59642009-08-24 18:29:25 -07001996 for (String name : packages) {
1997 try {
Fred Quintana56285a62010-12-02 14:20:51 -08001998 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
1999 if (packageInfo != null
2000 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002001 return true;
2002 }
2003 } catch (PackageManager.NameNotFoundException e) {
2004 return false;
2005 }
2006 }
2007 return false;
2008 }
2009
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002010 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002011 final boolean inSystemImage = inSystemImage(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002012 final boolean fromAuthenticator = account != null
2013 && hasAuthenticatorUid(account.type, callerUid);
2014 final boolean hasExplicitGrants = account != null
2015 && hasExplicitlyGrantedPermission(account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002016 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2017 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002018 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002019 + ": is authenticator? " + fromAuthenticator
2020 + ", has explicit permission? " + hasExplicitGrants);
2021 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002022 return fromAuthenticator || hasExplicitGrants || inSystemImage;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002023 }
2024
Fred Quintana1a231912009-10-15 11:31:30 -07002025 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002026 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
2027 mAuthenticatorCache.getAllServices()) {
2028 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002029 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002030 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002031 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002032 }
2033 }
2034 return false;
2035 }
2036
2037 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType) {
2038 if (Binder.getCallingUid() == android.os.Process.SYSTEM_UID) {
2039 return true;
2040 }
2041 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
2042 String[] args = {String.valueOf(Binder.getCallingUid()), authTokenType,
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002043 account.name, account.type};
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002044 final boolean permissionGranted =
2045 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -08002046 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002047 // TODO: Skip this check when running automated tests. Replace this
2048 // with a more general solution.
Fred Quintana751fdc02010-02-09 14:13:18 -08002049 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002050 + authTokenType + " by uid " + Binder.getCallingUid()
Brett Chabot3b4fcbc2011-01-09 13:41:02 -08002051 + " but ignoring since device is in test harness.");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002052 return true;
2053 }
2054 return permissionGranted;
2055 }
2056
2057 private void checkCallingUidAgainstAuthenticator(Account account) {
2058 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002059 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002060 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2061 Log.w(TAG, msg);
2062 throw new SecurityException(msg);
2063 }
2064 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2065 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2066 }
2067 }
2068
2069 private void checkAuthenticateAccountsPermission(Account account) {
2070 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2071 checkCallingUidAgainstAuthenticator(account);
2072 }
2073
2074 private void checkReadAccountsPermission() {
2075 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2076 }
2077
2078 private void checkManageAccountsPermission() {
2079 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2080 }
2081
Fred Quintanab38eb142010-02-24 13:40:54 -08002082 private void checkManageAccountsOrUseCredentialsPermissions() {
2083 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2084 Manifest.permission.USE_CREDENTIALS);
2085 }
2086
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002087 /**
2088 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2089 * <p>
2090 * Although this is public it can only be accessed via the AccountManagerService object
2091 * which is in the system. This means we don't need to protect it with permissions.
2092 * @hide
2093 */
2094 public void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002095 if (account == null || authTokenType == null) {
2096 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002097 return;
2098 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002099 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
2100 db.beginTransaction();
2101 try {
2102 long accountId = getAccountId(db, account);
2103 if (accountId >= 0) {
2104 ContentValues values = new ContentValues();
2105 values.put(GRANTS_ACCOUNTS_ID, accountId);
2106 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2107 values.put(GRANTS_GRANTEE_UID, uid);
2108 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2109 db.setTransactionSuccessful();
2110 }
2111 } finally {
2112 db.endTransaction();
2113 }
2114 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
2115 }
2116
2117 /**
2118 * Don't allow callers with the given uid permission to get credentials for
2119 * account/authTokenType.
2120 * <p>
2121 * Although this is public it can only be accessed via the AccountManagerService object
2122 * which is in the system. This means we don't need to protect it with permissions.
2123 * @hide
2124 */
2125 public void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002126 if (account == null || authTokenType == null) {
2127 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002128 return;
2129 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002130 SQLiteDatabase db = mOpenHelper.getWritableDatabase();
2131 db.beginTransaction();
2132 try {
2133 long accountId = getAccountId(db, account);
2134 if (accountId >= 0) {
2135 db.delete(TABLE_GRANTS,
2136 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2137 + GRANTS_GRANTEE_UID + "=?",
2138 new String[]{String.valueOf(accountId), authTokenType,
2139 String.valueOf(uid)});
2140 db.setTransactionSuccessful();
2141 }
2142 } finally {
2143 db.endTransaction();
2144 }
2145 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid));
2146 }
Fred Quintana56285a62010-12-02 14:20:51 -08002147
2148 static final private String stringArrayToString(String[] value) {
2149 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2150 }
2151
2152 private void removeAccountFromCache(Account account) {
2153 synchronized (mCacheLock) {
2154 final Account[] oldAccountsForType = mAccountCache.get(account.type);
2155 if (oldAccountsForType != null) {
2156 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2157 for (Account curAccount : oldAccountsForType) {
2158 if (!curAccount.equals(account)) {
2159 newAccountsList.add(curAccount);
2160 }
2161 }
2162 if (newAccountsList.isEmpty()) {
2163 mAccountCache.remove(account.type);
2164 } else {
2165 Account[] newAccountsForType = new Account[newAccountsList.size()];
2166 newAccountsForType = newAccountsList.toArray(newAccountsForType);
2167 mAccountCache.put(account.type, newAccountsForType);
2168 }
2169 }
2170 mUserDataCache.remove(account);
2171 mAuthTokenCache.remove(account);
2172 }
2173 }
2174
2175 /**
2176 * This assumes that the caller has already checked that the account is not already present.
2177 */
2178 private void insertAccountIntoCache(Account account) {
2179 synchronized (mCacheLock) {
2180 Account[] accountsForType = mAccountCache.get(account.type);
2181 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2182 Account[] newAccountsForType = new Account[oldLength + 1];
2183 if (accountsForType != null) {
2184 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
2185 }
2186 newAccountsForType[oldLength] = account;
2187 mAccountCache.put(account.type, newAccountsForType);
2188 }
2189 }
2190
2191 protected Account[] getAccountsByTypeFromCache(String accountType) {
2192 synchronized (mCacheLock) {
2193 if (accountType != null) {
2194 final Account[] accounts = mAccountCache.get(accountType);
2195 if (accounts == null) {
2196 return EMPTY_ACCOUNT_ARRAY;
2197 } else {
2198 return Arrays.copyOf(accounts, accounts.length);
2199 }
2200 } else {
2201 int totalLength = 0;
2202 for (Account[] accounts : mAccountCache.values()) {
2203 totalLength += accounts.length;
2204 }
2205 if (totalLength == 0) {
2206 return EMPTY_ACCOUNT_ARRAY;
2207 }
2208 Account[] accounts = new Account[totalLength];
2209 totalLength = 0;
2210 for (Account[] accountsOfType : mAccountCache.values()) {
2211 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2212 accountsOfType.length);
2213 totalLength += accountsOfType.length;
2214 }
2215 return accounts;
2216 }
2217 }
2218 }
2219
2220 protected void writeUserDataIntoCache(Account account, String key, String value) {
2221 synchronized (mCacheLock) {
2222 HashMap<String, String> userDataForAccount = mUserDataCache.get(account);
2223 if (userDataForAccount == null) {
2224 userDataForAccount = readUserDataForAccountFromDatabase(account);
2225 mUserDataCache.put(account, userDataForAccount);
2226 }
2227 if (value == null) {
2228 userDataForAccount.remove(key);
2229 } else {
2230 userDataForAccount.put(key, value);
2231 }
2232 }
2233 }
2234
2235 protected void writeAuthTokenIntoCache(Account account, String key, String value) {
2236 synchronized (mCacheLock) {
2237 HashMap<String, String> authTokensForAccount = mAuthTokenCache.get(account);
2238 if (authTokensForAccount == null) {
2239 authTokensForAccount = readAuthTokensForAccountFromDatabase(account);
2240 mAuthTokenCache.put(account, authTokensForAccount);
2241 }
2242 if (value == null) {
2243 authTokensForAccount.remove(key);
2244 } else {
2245 authTokensForAccount.put(key, value);
2246 }
2247 }
2248 }
2249
2250 protected String readAuthTokenFromCache(Account account, String authTokenType) {
2251 synchronized (mCacheLock) {
2252 HashMap<String, String> authTokensForAccount = mAuthTokenCache.get(account);
2253 if (authTokensForAccount == null) {
2254 // need to populate the cache for this account
2255 authTokensForAccount = readAuthTokensForAccountFromDatabase(account);
2256 mAuthTokenCache.put(account, authTokensForAccount);
2257 }
2258 return authTokensForAccount.get(authTokenType);
2259 }
2260 }
2261
2262 protected String readUserDataFromCache(Account account, String key) {
2263 synchronized (mCacheLock) {
2264 HashMap<String, String> userDataForAccount = mUserDataCache.get(account);
2265 if (userDataForAccount == null) {
2266 // need to populate the cache for this account
2267 userDataForAccount = readUserDataForAccountFromDatabase(account);
2268 mUserDataCache.put(account, userDataForAccount);
2269 }
2270 return userDataForAccount.get(key);
2271 }
2272 }
2273
2274 protected HashMap<String, String> readUserDataForAccountFromDatabase(Account account) {
2275 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
2276 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
2277 Cursor cursor = db.query(TABLE_EXTRAS,
2278 COLUMNS_EXTRAS_KEY_AND_VALUE,
2279 SELECTION_USERDATA_BY_ACCOUNT,
2280 new String[]{account.name, account.type},
2281 null, null, null);
2282 try {
2283 while (cursor.moveToNext()) {
2284 final String tmpkey = cursor.getString(0);
2285 final String value = cursor.getString(1);
2286 userDataForAccount.put(tmpkey, value);
2287 }
2288 } finally {
2289 cursor.close();
2290 }
2291 return userDataForAccount;
2292 }
2293
2294 protected HashMap<String, String> readAuthTokensForAccountFromDatabase(Account account) {
2295 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
2296 SQLiteDatabase db = mOpenHelper.getReadableDatabase();
2297 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2298 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2299 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2300 new String[]{account.name, account.type},
2301 null, null, null);
2302 try {
2303 while (cursor.moveToNext()) {
2304 final String type = cursor.getString(0);
2305 final String authToken = cursor.getString(1);
2306 authTokensForAccount.put(type, authToken);
2307 }
2308 } finally {
2309 cursor.close();
2310 }
2311 return authTokensForAccount;
2312 }
Fred Quintana60307342009-03-24 22:48:12 -07002313}