blob: dd9ae4c9397e3656712cc40c60c0ee529a696ea8 [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
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080020import android.accounts.Account;
21import android.accounts.AccountAndUser;
22import android.accounts.AccountAuthenticatorResponse;
23import android.accounts.AccountManager;
24import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070025import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080026import android.accounts.GrantCredentialsPermissionActivity;
27import android.accounts.IAccountAuthenticator;
28import android.accounts.IAccountAuthenticatorResponse;
29import android.accounts.IAccountManager;
30import android.accounts.IAccountManagerResponse;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080031import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070032import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070033import android.app.AppGlobals;
Doug Zongker885cfc232009-10-21 16:52:44 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Fred Quintanaa698f422009-04-08 19:14:54 -070037import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070038import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070039import android.content.ContentValues;
40import android.content.Context;
41import android.content.Intent;
42import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070043import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070044import android.content.pm.ApplicationInfo;
45import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070046import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070047import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070048import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070049import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070050import android.content.pm.ResolveInfo;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070051import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070052import android.database.Cursor;
53import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070054import android.database.sqlite.SQLiteDatabase;
55import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070056import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070057import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080058import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070059import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070060import android.os.IBinder;
61import android.os.Looper;
62import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070063import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070064import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import android.os.RemoteException;
66import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070068import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.text.TextUtils;
70import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070071import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070072import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080073import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070074
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070075import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080076import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080077import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070078import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070079import com.google.android.collect.Lists;
80import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070081
Oscar Montemayora8529f62009-11-18 10:14:20 -080082import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070083import java.io.FileDescriptor;
84import java.io.PrintWriter;
85import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080086import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070087import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070088import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070089import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080090import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070091import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080092import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070093import java.util.concurrent.atomic.AtomicInteger;
94import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070095
Fred Quintana60307342009-03-24 22:48:12 -070096/**
97 * A system service that provides account, password, and authtoken management for all
98 * accounts on the device. Some of these calls are implemented with the help of the corresponding
99 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
100 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700101 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700102 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700103 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700104public class AccountManagerService
105 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800106 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700107 private static final String TAG = "AccountManagerService";
108
109 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
110 private static final String DATABASE_NAME = "accounts.db";
Amith Yamasani67df64b2012-12-14 12:09:36 -0800111 private static final int DATABASE_VERSION = 5;
Fred Quintana60307342009-03-24 22:48:12 -0700112
113 private final Context mContext;
114
Fred Quintana56285a62010-12-02 14:20:51 -0800115 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700116 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800117
Fred Quintana60307342009-03-24 22:48:12 -0700118 private final MessageHandler mMessageHandler;
119
120 // Messages that can be sent on mHandler
121 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700122 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700123
Fred Quintana56285a62010-12-02 14:20:51 -0800124 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700125
126 private static final String TABLE_ACCOUNTS = "accounts";
127 private static final String ACCOUNTS_ID = "_id";
128 private static final String ACCOUNTS_NAME = "name";
129 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700130 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700131 private static final String ACCOUNTS_PASSWORD = "password";
132
133 private static final String TABLE_AUTHTOKENS = "authtokens";
134 private static final String AUTHTOKENS_ID = "_id";
135 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
136 private static final String AUTHTOKENS_TYPE = "type";
137 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
138
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700139 private static final String TABLE_GRANTS = "grants";
140 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
141 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
142 private static final String GRANTS_GRANTEE_UID = "uid";
143
Fred Quintana60307342009-03-24 22:48:12 -0700144 private static final String TABLE_EXTRAS = "extras";
145 private static final String EXTRAS_ID = "_id";
146 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
147 private static final String EXTRAS_KEY = "key";
148 private static final String EXTRAS_VALUE = "value";
149
150 private static final String TABLE_META = "meta";
151 private static final String META_KEY = "key";
152 private static final String META_VALUE = "value";
153
Amith Yamasani67df64b2012-12-14 12:09:36 -0800154 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
155
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700156 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
157 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700158 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700159
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700160 private static final String COUNT_OF_MATCHING_GRANTS = ""
161 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
162 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
163 + " AND " + GRANTS_GRANTEE_UID + "=?"
164 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
165 + " AND " + ACCOUNTS_NAME + "=?"
166 + " AND " + ACCOUNTS_TYPE + "=?";
167
Fred Quintana56285a62010-12-02 14:20:51 -0800168 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
169 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
170 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
171 AUTHTOKENS_AUTHTOKEN};
172
173 private static final String SELECTION_USERDATA_BY_ACCOUNT =
174 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
175 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
176
Fred Quintanaa698f422009-04-08 19:14:54 -0700177 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700178 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
179
Amith Yamasani04e0d262012-02-14 11:50:53 -0800180 static class UserAccounts {
181 private final int userId;
182 private final DatabaseHelper openHelper;
183 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
184 credentialsPermissionNotificationIds =
185 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
186 private final HashMap<Account, Integer> signinRequiredNotificationIds =
187 new HashMap<Account, Integer>();
188 private final Object cacheLock = new Object();
189 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700190 private final HashMap<String, Account[]> accountCache =
191 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800192 /** protected by the {@link #cacheLock} */
193 private HashMap<Account, HashMap<String, String>> userDataCache =
194 new HashMap<Account, HashMap<String, String>>();
195 /** protected by the {@link #cacheLock} */
196 private HashMap<Account, HashMap<String, String>> authTokenCache =
197 new HashMap<Account, HashMap<String, String>>();
198
199 UserAccounts(Context context, int userId) {
200 this.userId = userId;
201 synchronized (cacheLock) {
202 openHelper = new DatabaseHelper(context, userId);
203 }
204 }
205 }
206
207 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
208
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700209 private static AtomicReference<AccountManagerService> sThis =
210 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700211 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700212
213 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700214 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700215 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
216 }
217
Fred Quintana56285a62010-12-02 14:20:51 -0800218
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700219 /**
220 * This should only be called by system code. One should only call this after the service
221 * has started.
222 * @return a reference to the AccountManagerService instance
223 * @hide
224 */
225 public static AccountManagerService getSingleton() {
226 return sThis.get();
227 }
Fred Quintana60307342009-03-24 22:48:12 -0700228
Fred Quintana56285a62010-12-02 14:20:51 -0800229 public AccountManagerService(Context context) {
230 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700231 }
232
Fred Quintana56285a62010-12-02 14:20:51 -0800233 public AccountManagerService(Context context, PackageManager packageManager,
234 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700235 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800236 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700237
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700238 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700239
Fred Quintana56285a62010-12-02 14:20:51 -0800240 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800241 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700242
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700243 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800244
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800245 IntentFilter intentFilter = new IntentFilter();
246 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
247 intentFilter.addDataScheme("package");
248 mContext.registerReceiver(new BroadcastReceiver() {
249 @Override
250 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800251 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800252 }
253 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800254
Amith Yamasani13593602012-03-22 16:16:17 -0700255 IntentFilter userFilter = new IntentFilter();
256 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800257 userFilter.addAction(Intent.ACTION_USER_STARTED);
258 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700259 @Override
260 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800261 String action = intent.getAction();
262 if (Intent.ACTION_USER_REMOVED.equals(action)) {
263 onUserRemoved(intent);
264 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
265 onUserStarted(intent);
266 }
Amith Yamasani13593602012-03-22 16:16:17 -0700267 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800268 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800269 }
270
Dianne Hackborn164371f2013-10-01 19:10:13 -0700271 @Override
272 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
273 throws RemoteException {
274 try {
275 return super.onTransact(code, data, reply, flags);
276 } catch (RuntimeException e) {
277 // The account manager only throws security exceptions, so let's
278 // log all others.
279 if (!(e instanceof SecurityException)) {
280 Slog.wtf(TAG, "Account Manager Crash", e);
281 }
282 throw e;
283 }
284 }
285
Kenny Root26ff6622012-07-30 12:58:03 -0700286 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700287 }
288
Amith Yamasani258848d2012-08-10 17:06:33 -0700289 private UserManager getUserManager() {
290 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700291 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700292 }
293 return mUserManager;
294 }
295
Amith Yamasani04e0d262012-02-14 11:50:53 -0800296 private UserAccounts initUser(int userId) {
297 synchronized (mUsers) {
298 UserAccounts accounts = mUsers.get(userId);
299 if (accounts == null) {
300 accounts = new UserAccounts(mContext, userId);
301 mUsers.append(userId, accounts);
302 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700303 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800304 }
305 return accounts;
306 }
307 }
308
309 private void purgeOldGrantsAll() {
310 synchronized (mUsers) {
311 for (int i = 0; i < mUsers.size(); i++) {
312 purgeOldGrants(mUsers.valueAt(i));
313 }
314 }
315 }
316
317 private void purgeOldGrants(UserAccounts accounts) {
318 synchronized (accounts.cacheLock) {
319 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800320 final Cursor cursor = db.query(TABLE_GRANTS,
321 new String[]{GRANTS_GRANTEE_UID},
322 null, null, GRANTS_GRANTEE_UID, null, null);
323 try {
324 while (cursor.moveToNext()) {
325 final int uid = cursor.getInt(0);
326 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
327 if (packageExists) {
328 continue;
329 }
330 Log.d(TAG, "deleting grants for UID " + uid
331 + " because its package is no longer installed");
332 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
333 new String[]{Integer.toString(uid)});
334 }
335 } finally {
336 cursor.close();
337 }
338 }
339 }
340
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700341 /**
342 * Validate internal set of accounts against installed authenticators for
343 * given user. Clears cached authenticators before validating.
344 */
345 public void validateAccounts(int userId) {
346 final UserAccounts accounts = getUserAccounts(userId);
347
348 // Invalidate user-specific cache to make sure we catch any
349 // removed authenticators.
350 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
351 }
352
353 /**
354 * Validate internal set of accounts against installed authenticators for
355 * given user. Clear cached authenticators before validating when requested.
356 */
357 private void validateAccountsInternal(
358 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
359 if (invalidateAuthenticatorCache) {
360 mAuthenticatorCache.invalidateCache(accounts.userId);
361 }
362
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700363 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
364 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
365 mAuthenticatorCache.getAllServices(accounts.userId)) {
366 knownAuth.add(service.type);
367 }
368
Amith Yamasani04e0d262012-02-14 11:50:53 -0800369 synchronized (accounts.cacheLock) {
370 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800371 boolean accountDeleted = false;
372 Cursor cursor = db.query(TABLE_ACCOUNTS,
373 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
374 null, null, null, null, null);
375 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800376 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800377 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700378 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800379 while (cursor.moveToNext()) {
380 final long accountId = cursor.getLong(0);
381 final String accountType = cursor.getString(1);
382 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700383
384 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700385 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800386 + accountType + " no longer has a registered authenticator");
387 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
388 accountDeleted = true;
389 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800390 accounts.userDataCache.remove(account);
391 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800392 } else {
393 ArrayList<String> accountNames = accountNamesByType.get(accountType);
394 if (accountNames == null) {
395 accountNames = new ArrayList<String>();
396 accountNamesByType.put(accountType, accountNames);
397 }
398 accountNames.add(accountName);
399 }
400 }
Andy McFadden2f362292012-01-20 14:43:38 -0800401 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800402 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800403 final String accountType = cur.getKey();
404 final ArrayList<String> accountNames = cur.getValue();
405 final Account[] accountsForType = new Account[accountNames.size()];
406 int i = 0;
407 for (String accountName : accountNames) {
408 accountsForType[i] = new Account(accountName, accountType);
409 ++i;
410 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800411 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800412 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800413 } finally {
414 cursor.close();
415 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800416 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800417 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800418 }
419 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700420 }
421
Amith Yamasani04e0d262012-02-14 11:50:53 -0800422 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700423 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800424 }
425
426 protected UserAccounts getUserAccounts(int userId) {
427 synchronized (mUsers) {
428 UserAccounts accounts = mUsers.get(userId);
429 if (accounts == null) {
430 accounts = initUser(userId);
431 mUsers.append(userId, accounts);
432 }
433 return accounts;
434 }
435 }
436
Amith Yamasani13593602012-03-22 16:16:17 -0700437 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700438 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700439 if (userId < 1) return;
440
441 UserAccounts accounts;
442 synchronized (mUsers) {
443 accounts = mUsers.get(userId);
444 mUsers.remove(userId);
445 }
446 if (accounts == null) {
447 File dbFile = new File(getDatabaseName(userId));
448 dbFile.delete();
449 return;
450 }
451
452 synchronized (accounts.cacheLock) {
453 accounts.openHelper.close();
454 File dbFile = new File(getDatabaseName(userId));
455 dbFile.delete();
456 }
457 }
458
Amith Yamasani67df64b2012-12-14 12:09:36 -0800459 private void onUserStarted(Intent intent) {
460 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
461 if (userId < 1) return;
462
463 // Check if there's a shared account that needs to be created as an account
464 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
465 if (sharedAccounts == null || sharedAccounts.length == 0) return;
466 Account[] accounts = getAccountsAsUser(null, userId);
467 for (Account sa : sharedAccounts) {
468 if (ArrayUtils.contains(accounts, sa)) continue;
469 // Account doesn't exist. Copy it now.
470 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
471 }
472 }
473
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700474 @Override
475 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700476 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700477 }
478
Fred Quintanaa698f422009-04-08 19:14:54 -0700479 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800480 if (Log.isLoggable(TAG, Log.VERBOSE)) {
481 Log.v(TAG, "getPassword: " + account
482 + ", caller's uid " + Binder.getCallingUid()
483 + ", pid " + Binder.getCallingPid());
484 }
Fred Quintana382601f2010-03-25 12:25:10 -0700485 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700486 checkAuthenticateAccountsPermission(account);
487
Amith Yamasani04e0d262012-02-14 11:50:53 -0800488 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700489 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700490 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800491 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700492 } finally {
493 restoreCallingIdentity(identityToken);
494 }
495 }
496
Amith Yamasani04e0d262012-02-14 11:50:53 -0800497 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700498 if (account == null) {
499 return null;
500 }
501
Amith Yamasani04e0d262012-02-14 11:50:53 -0800502 synchronized (accounts.cacheLock) {
503 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800504 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
505 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
506 new String[]{account.name, account.type}, null, null, null);
507 try {
508 if (cursor.moveToNext()) {
509 return cursor.getString(0);
510 }
511 return null;
512 } finally {
513 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700514 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 }
516 }
517
518 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800519 if (Log.isLoggable(TAG, Log.VERBOSE)) {
520 Log.v(TAG, "getUserData: " + account
521 + ", key " + key
522 + ", caller's uid " + Binder.getCallingUid()
523 + ", pid " + Binder.getCallingPid());
524 }
Fred Quintana382601f2010-03-25 12:25:10 -0700525 if (account == null) throw new IllegalArgumentException("account is null");
526 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700527 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800528 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700529 long identityToken = clearCallingIdentity();
530 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800531 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700532 } finally {
533 restoreCallingIdentity(identityToken);
534 }
535 }
536
Fred Quintana97889762009-06-15 12:29:24 -0700537 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800538 if (Log.isLoggable(TAG, Log.VERBOSE)) {
539 Log.v(TAG, "getAuthenticatorTypes: "
540 + "caller's uid " + Binder.getCallingUid()
541 + ", pid " + Binder.getCallingPid());
542 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700543 final int userId = UserHandle.getCallingUserId();
544 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700545 try {
Fred Quintana97889762009-06-15 12:29:24 -0700546 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700547 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700548 AuthenticatorDescription[] types =
549 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700550 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700551 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700552 : authenticatorCollection) {
553 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700554 i++;
555 }
556 return types;
557 } finally {
558 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700559 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700560 }
561
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700562 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700563 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800564 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700565 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800566 + ", caller's uid " + Binder.getCallingUid()
567 + ", pid " + Binder.getCallingPid());
568 }
Fred Quintana382601f2010-03-25 12:25:10 -0700569 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700570 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700571 /*
572 * Child users are not allowed to add accounts. Only the accounts that are
573 * shared by the parent profile can be added to child profile.
574 *
575 * TODO: Only allow accounts that were shared to be added by
576 * a limited user.
577 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700578
Amith Yamasani04e0d262012-02-14 11:50:53 -0800579 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700580 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700581 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700582 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800583 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700584 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700585 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700586 }
587 }
588
Amith Yamasani67df64b2012-12-14 12:09:36 -0800589 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
590 final UserAccounts fromAccounts = getUserAccounts(userFrom);
591 final UserAccounts toAccounts = getUserAccounts(userTo);
592 if (fromAccounts == null || toAccounts == null) {
593 return false;
594 }
595
596 long identityToken = clearCallingIdentity();
597 try {
598 new Session(fromAccounts, null, account.type, false,
599 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700600 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800601 protected String toDebugString(long now) {
602 return super.toDebugString(now) + ", getAccountCredentialsForClone"
603 + ", " + account.type;
604 }
605
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700606 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800607 public void run() throws RemoteException {
608 mAuthenticator.getAccountCredentialsForCloning(this, account);
609 }
610
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700611 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800612 public void onResult(Bundle result) {
613 if (result != null) {
614 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
615 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800616 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800617 }
618 return;
619 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800620 super.onResult(result);
621 }
622 }
623 }.bind();
624 } finally {
625 restoreCallingIdentity(identityToken);
626 }
627 return true;
628 }
629
Amith Yamasani67df64b2012-12-14 12:09:36 -0800630 void completeCloningAccount(final Bundle result, final Account account,
631 final UserAccounts targetUser) {
632 long id = clearCallingIdentity();
633 try {
634 new Session(targetUser, null, account.type, false,
635 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700636 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800637 protected String toDebugString(long now) {
638 return super.toDebugString(now) + ", getAccountCredentialsForClone"
639 + ", " + account.type;
640 }
641
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700642 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800643 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700644 // Confirm that the owner's account still exists before this step.
645 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
646 synchronized (owner.cacheLock) {
647 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
648 for (Account acc : ownerAccounts) {
649 if (acc.equals(account)) {
650 mAuthenticator.addAccountFromCredentials(this, account, result);
651 break;
652 }
653 }
654 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800655 }
656
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700657 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800658 public void onResult(Bundle result) {
659 if (result != null) {
660 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
661 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800662 } else {
663 // TODO: Show error notification
664 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800665 }
666 return;
667 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800668 super.onResult(result);
669 }
670 }
671
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700672 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800673 public void onError(int errorCode, String errorMessage) {
674 super.onError(errorCode, errorMessage);
675 // TODO: Show error notification to user
676 // TODO: Should we remove the shadow account so that it doesn't keep trying?
677 }
678
679 }.bind();
680 } finally {
681 restoreCallingIdentity(id);
682 }
683 }
684
Amith Yamasani04e0d262012-02-14 11:50:53 -0800685 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800686 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700687 if (account == null) {
688 return false;
689 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800690 synchronized (accounts.cacheLock) {
691 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800692 db.beginTransaction();
693 try {
694 long numMatches = DatabaseUtils.longForQuery(db,
695 "select count(*) from " + TABLE_ACCOUNTS
696 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
697 new String[]{account.name, account.type});
698 if (numMatches > 0) {
699 Log.w(TAG, "insertAccountIntoDatabase: " + account
700 + ", skipping since the account already exists");
701 return false;
702 }
703 ContentValues values = new ContentValues();
704 values.put(ACCOUNTS_NAME, account.name);
705 values.put(ACCOUNTS_TYPE, account.type);
706 values.put(ACCOUNTS_PASSWORD, password);
707 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
708 if (accountId < 0) {
709 Log.w(TAG, "insertAccountIntoDatabase: " + account
710 + ", skipping the DB insert failed");
711 return false;
712 }
713 if (extras != null) {
714 for (String key : extras.keySet()) {
715 final String value = extras.getString(key);
716 if (insertExtraLocked(db, accountId, key, value) < 0) {
717 Log.w(TAG, "insertAccountIntoDatabase: " + account
718 + ", skipping since insertExtra failed for key " + key);
719 return false;
720 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700721 }
722 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800723 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800724 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800725 } finally {
726 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700727 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800728 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700729 }
730 if (accounts.userId == UserHandle.USER_OWNER) {
731 addAccountToLimitedUsers(account);
732 }
733 return true;
734 }
735
736 /**
737 * Adds the account to all limited users as shared accounts. If the user is currently
738 * running, then clone the account too.
739 * @param account the account to share with limited users
740 */
741 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700742 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700743 for (UserInfo user : users) {
744 if (user.isRestricted()) {
745 addSharedAccountAsUser(account, user.id);
746 try {
747 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
748 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
749 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
750 account));
751 }
752 } catch (RemoteException re) {
753 // Shouldn't happen
754 }
755 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700756 }
757 }
758
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800759 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700760 ContentValues values = new ContentValues();
761 values.put(EXTRAS_KEY, key);
762 values.put(EXTRAS_ACCOUNTS_ID, accountId);
763 values.put(EXTRAS_VALUE, value);
764 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
765 }
766
Fred Quintana3084a6f2010-01-14 18:02:03 -0800767 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800768 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800769 if (Log.isLoggable(TAG, Log.VERBOSE)) {
770 Log.v(TAG, "hasFeatures: " + account
771 + ", response " + response
772 + ", features " + stringArrayToString(features)
773 + ", caller's uid " + Binder.getCallingUid()
774 + ", pid " + Binder.getCallingPid());
775 }
Fred Quintana382601f2010-03-25 12:25:10 -0700776 if (response == null) throw new IllegalArgumentException("response is null");
777 if (account == null) throw new IllegalArgumentException("account is null");
778 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800779 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800780 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800781 long identityToken = clearCallingIdentity();
782 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800783 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800784 } finally {
785 restoreCallingIdentity(identityToken);
786 }
787 }
788
789 private class TestFeaturesSession extends Session {
790 private final String[] mFeatures;
791 private final Account mAccount;
792
Amith Yamasani04e0d262012-02-14 11:50:53 -0800793 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800794 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800795 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800796 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800797 mFeatures = features;
798 mAccount = account;
799 }
800
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700801 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800802 public void run() throws RemoteException {
803 try {
804 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
805 } catch (RemoteException e) {
806 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
807 }
808 }
809
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700810 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800811 public void onResult(Bundle result) {
812 IAccountManagerResponse response = getResponseAndClose();
813 if (response != null) {
814 try {
815 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700816 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800817 return;
818 }
Fred Quintana56285a62010-12-02 14:20:51 -0800819 if (Log.isLoggable(TAG, Log.VERBOSE)) {
820 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
821 + response);
822 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800823 final Bundle newResult = new Bundle();
824 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
825 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
826 response.onResult(newResult);
827 } catch (RemoteException e) {
828 // if the caller is dead then there is no one to care about remote exceptions
829 if (Log.isLoggable(TAG, Log.VERBOSE)) {
830 Log.v(TAG, "failure while notifying response", e);
831 }
832 }
833 }
834 }
835
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700836 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800837 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800838 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800839 + ", " + mAccount
840 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
841 }
842 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800843
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700844 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800845 if (Log.isLoggable(TAG, Log.VERBOSE)) {
846 Log.v(TAG, "removeAccount: " + account
847 + ", response " + response
848 + ", caller's uid " + Binder.getCallingUid()
849 + ", pid " + Binder.getCallingPid());
850 }
Fred Quintana382601f2010-03-25 12:25:10 -0700851 if (response == null) throw new IllegalArgumentException("response is null");
852 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700853 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700854 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800855 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800856 if (!canUserModifyAccounts(Binder.getCallingUid())) {
857 try {
858 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
859 "User cannot modify accounts");
860 } catch (RemoteException re) {
861 }
862 }
863
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700864 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800865
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700866 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800867 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800868 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800869 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800870 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800871 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700872 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800873 }
874 }
875 }
876
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700877 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800878 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700879 } finally {
880 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700881 }
Fred Quintana60307342009-03-24 22:48:12 -0700882 }
883
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700884 private class RemoveAccountSession extends Session {
885 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800886 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
887 Account account) {
888 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800889 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700890 mAccount = account;
891 }
892
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700893 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700894 protected String toDebugString(long now) {
895 return super.toDebugString(now) + ", removeAccount"
896 + ", account " + mAccount;
897 }
898
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700899 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700900 public void run() throws RemoteException {
901 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
902 }
903
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700904 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700905 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700906 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
907 && !result.containsKey(AccountManager.KEY_INTENT)) {
908 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700909 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800910 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700911 }
912 IAccountManagerResponse response = getResponseAndClose();
913 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800914 if (Log.isLoggable(TAG, Log.VERBOSE)) {
915 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
916 + response);
917 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700918 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700919 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700920 try {
921 response.onResult(result2);
922 } catch (RemoteException e) {
923 // ignore
924 }
925 }
926 }
927 super.onResult(result);
928 }
929 }
930
Amith Yamasani04e0d262012-02-14 11:50:53 -0800931 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800932 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800933 removeAccountInternal(getUserAccountsForCaller(), account);
934 }
935
936 private void removeAccountInternal(UserAccounts accounts, Account account) {
937 synchronized (accounts.cacheLock) {
938 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800939 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
940 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800941 removeAccountFromCacheLocked(accounts, account);
942 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800943 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800944 if (accounts.userId == UserHandle.USER_OWNER) {
945 // Owner's account was removed, remove from any users that are sharing
946 // this account.
947 long id = Binder.clearCallingIdentity();
948 try {
949 List<UserInfo> users = mUserManager.getUsers(true);
950 for (UserInfo user : users) {
951 if (!user.isPrimary() && user.isRestricted()) {
952 removeSharedAccountAsUser(account, user.id);
953 }
954 }
955 } finally {
956 Binder.restoreCallingIdentity(id);
957 }
958 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700959 }
960
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400961 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700962 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800963 if (Log.isLoggable(TAG, Log.VERBOSE)) {
964 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
965 + ", caller's uid " + Binder.getCallingUid()
966 + ", pid " + Binder.getCallingPid());
967 }
Fred Quintana382601f2010-03-25 12:25:10 -0700968 if (accountType == null) throw new IllegalArgumentException("accountType is null");
969 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800970 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800971 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700972 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700973 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800974 synchronized (accounts.cacheLock) {
975 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800976 db.beginTransaction();
977 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800978 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800979 db.setTransactionSuccessful();
980 } finally {
981 db.endTransaction();
982 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700983 }
Fred Quintana60307342009-03-24 22:48:12 -0700984 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700985 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700986 }
987 }
988
Amith Yamasani04e0d262012-02-14 11:50:53 -0800989 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
990 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700991 if (authToken == null || accountType == null) {
992 return;
993 }
Fred Quintana33269202009-04-20 16:05:10 -0700994 Cursor cursor = db.rawQuery(
995 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
996 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
997 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
998 + " FROM " + TABLE_ACCOUNTS
999 + " JOIN " + TABLE_AUTHTOKENS
1000 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1001 + " = " + AUTHTOKENS_ACCOUNTS_ID
1002 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1003 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1004 new String[]{authToken, accountType});
1005 try {
1006 while (cursor.moveToNext()) {
1007 long authTokenId = cursor.getLong(0);
1008 String accountName = cursor.getString(1);
1009 String authTokenType = cursor.getString(2);
1010 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001011 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001012 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -07001013 }
Fred Quintana33269202009-04-20 16:05:10 -07001014 } finally {
1015 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001016 }
1017 }
1018
Amith Yamasani04e0d262012-02-14 11:50:53 -08001019 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1020 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001021 if (account == null || type == null) {
1022 return false;
1023 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001024 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1025 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001026 synchronized (accounts.cacheLock) {
1027 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001028 db.beginTransaction();
1029 try {
1030 long accountId = getAccountIdLocked(db, account);
1031 if (accountId < 0) {
1032 return false;
1033 }
1034 db.delete(TABLE_AUTHTOKENS,
1035 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1036 new String[]{type});
1037 ContentValues values = new ContentValues();
1038 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1039 values.put(AUTHTOKENS_TYPE, type);
1040 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1041 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1042 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001043 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001044 return true;
1045 }
Fred Quintana33269202009-04-20 16:05:10 -07001046 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001047 } finally {
1048 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001049 }
Fred Quintana60307342009-03-24 22:48:12 -07001050 }
1051 }
1052
Fred Quintanaa698f422009-04-08 19:14:54 -07001053 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001054 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1055 Log.v(TAG, "peekAuthToken: " + account
1056 + ", authTokenType " + authTokenType
1057 + ", caller's uid " + Binder.getCallingUid()
1058 + ", pid " + Binder.getCallingPid());
1059 }
Fred Quintana382601f2010-03-25 12:25:10 -07001060 if (account == null) throw new IllegalArgumentException("account is null");
1061 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001062 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001063 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001064 long identityToken = clearCallingIdentity();
1065 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001066 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001067 } finally {
1068 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001069 }
Fred Quintana60307342009-03-24 22:48:12 -07001070 }
1071
Fred Quintanaa698f422009-04-08 19:14:54 -07001072 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001073 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1074 Log.v(TAG, "setAuthToken: " + account
1075 + ", authTokenType " + authTokenType
1076 + ", caller's uid " + Binder.getCallingUid()
1077 + ", pid " + Binder.getCallingPid());
1078 }
Fred Quintana382601f2010-03-25 12:25:10 -07001079 if (account == null) throw new IllegalArgumentException("account is null");
1080 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001081 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001082 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001083 long identityToken = clearCallingIdentity();
1084 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001085 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001086 } finally {
1087 restoreCallingIdentity(identityToken);
1088 }
Fred Quintana60307342009-03-24 22:48:12 -07001089 }
1090
Fred Quintanaa698f422009-04-08 19:14:54 -07001091 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001092 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1093 Log.v(TAG, "setAuthToken: " + account
1094 + ", caller's uid " + Binder.getCallingUid()
1095 + ", pid " + Binder.getCallingPid());
1096 }
Fred Quintana382601f2010-03-25 12:25:10 -07001097 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001098 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001099 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001100 long identityToken = clearCallingIdentity();
1101 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001102 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001103 } finally {
1104 restoreCallingIdentity(identityToken);
1105 }
Fred Quintana60307342009-03-24 22:48:12 -07001106 }
1107
Amith Yamasani04e0d262012-02-14 11:50:53 -08001108 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001109 if (account == null) {
1110 return;
1111 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001112 synchronized (accounts.cacheLock) {
1113 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001114 db.beginTransaction();
1115 try {
1116 final ContentValues values = new ContentValues();
1117 values.put(ACCOUNTS_PASSWORD, password);
1118 final long accountId = getAccountIdLocked(db, account);
1119 if (accountId >= 0) {
1120 final String[] argsAccountId = {String.valueOf(accountId)};
1121 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1122 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001123 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001124 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001125 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001126 } finally {
1127 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001128 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001129 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001130 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001131 }
1132
Amith Yamasani04e0d262012-02-14 11:50:53 -08001133 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001134 Log.i(TAG, "the accounts changed, sending broadcast of "
1135 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001136 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001137 }
1138
Fred Quintanaa698f422009-04-08 19:14:54 -07001139 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001140 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1141 Log.v(TAG, "clearPassword: " + account
1142 + ", caller's uid " + Binder.getCallingUid()
1143 + ", pid " + Binder.getCallingPid());
1144 }
Fred Quintana382601f2010-03-25 12:25:10 -07001145 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001146 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001147 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001148 long identityToken = clearCallingIdentity();
1149 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001150 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001151 } finally {
1152 restoreCallingIdentity(identityToken);
1153 }
Fred Quintana60307342009-03-24 22:48:12 -07001154 }
1155
Fred Quintanaa698f422009-04-08 19:14:54 -07001156 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001157 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1158 Log.v(TAG, "setUserData: " + account
1159 + ", key " + key
1160 + ", caller's uid " + Binder.getCallingUid()
1161 + ", pid " + Binder.getCallingPid());
1162 }
Fred Quintana382601f2010-03-25 12:25:10 -07001163 if (key == null) throw new IllegalArgumentException("key is null");
1164 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001165 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001166 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001167 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001168 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001169 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001170 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001171 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001172 }
1173 }
1174
Amith Yamasani04e0d262012-02-14 11:50:53 -08001175 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1176 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001177 if (account == null || key == null) {
1178 return;
1179 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001180 synchronized (accounts.cacheLock) {
1181 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001182 db.beginTransaction();
1183 try {
1184 long accountId = getAccountIdLocked(db, account);
1185 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001186 return;
1187 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001188 long extrasId = getExtrasIdLocked(db, accountId, key);
1189 if (extrasId < 0 ) {
1190 extrasId = insertExtraLocked(db, accountId, key, value);
1191 if (extrasId < 0) {
1192 return;
1193 }
1194 } else {
1195 ContentValues values = new ContentValues();
1196 values.put(EXTRAS_VALUE, value);
1197 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1198 return;
1199 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001200
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001201 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001202 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001203 db.setTransactionSuccessful();
1204 } finally {
1205 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001206 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001207 }
1208 }
1209
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001210 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001211 if (result == null) {
1212 Log.e(TAG, "the result is unexpectedly null", new Exception());
1213 }
1214 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1215 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1216 + response);
1217 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001218 try {
1219 response.onResult(result);
1220 } catch (RemoteException e) {
1221 // if the caller is dead then there is no one to care about remote
1222 // exceptions
1223 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1224 Log.v(TAG, "failure while notifying response", e);
1225 }
1226 }
1227 }
1228
Fred Quintanad9640ec2012-05-23 12:37:00 -07001229 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1230 final String authTokenType)
1231 throws RemoteException {
1232 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001233 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1234
Fred Quintanad9640ec2012-05-23 12:37:00 -07001235 final int callingUid = getCallingUid();
1236 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001237 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001238 throw new SecurityException("can only call from system");
1239 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001240 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001241 long identityToken = clearCallingIdentity();
1242 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001243 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001244 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001245 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001246 protected String toDebugString(long now) {
1247 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001248 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001249 + ", authTokenType " + authTokenType;
1250 }
1251
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001252 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001253 public void run() throws RemoteException {
1254 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1255 }
1256
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001257 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001258 public void onResult(Bundle result) {
1259 if (result != null) {
1260 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1261 Bundle bundle = new Bundle();
1262 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1263 super.onResult(bundle);
1264 return;
1265 } else {
1266 super.onResult(result);
1267 }
1268 }
1269 }.bind();
1270 } finally {
1271 restoreCallingIdentity(identityToken);
1272 }
1273 }
1274
Fred Quintanaa698f422009-04-08 19:14:54 -07001275 public void getAuthToken(IAccountManagerResponse response, final Account account,
1276 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001277 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001278 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1279 Log.v(TAG, "getAuthToken: " + account
1280 + ", response " + response
1281 + ", authTokenType " + authTokenType
1282 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1283 + ", expectActivityLaunch " + expectActivityLaunch
1284 + ", caller's uid " + Binder.getCallingUid()
1285 + ", pid " + Binder.getCallingPid());
1286 }
Fred Quintana382601f2010-03-25 12:25:10 -07001287 if (response == null) throw new IllegalArgumentException("response is null");
1288 if (account == null) throw new IllegalArgumentException("account is null");
1289 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001290 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001291 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001292 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1293 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1294 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001295 final boolean customTokens =
1296 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1297
Amith Yamasanid20ea2f2013-05-08 12:57:01 -07001298 // Check to see that the app is authorized to access the account, in case it's a
1299 // restricted account.
1300 if (!ArrayUtils.contains(getAccounts((String) null), account)) {
1301 throw new IllegalArgumentException("no such account");
1302 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001303 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001304 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001305 final boolean permissionGranted = customTokens ||
1306 permissionIsGranted(account, authTokenType, callerUid);
1307
Costin Manolachec6684f92011-01-14 11:25:39 -08001308 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1309 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001310 // let authenticator know the identity of the caller
1311 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1312 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1313 if (notifyOnAuthFailure) {
1314 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001315 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001316
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001317 long identityToken = clearCallingIdentity();
1318 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001319 // if the caller has permission, do the peek. otherwise go the more expensive
1320 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001321 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001322 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001323 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001324 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001325 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1326 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1327 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001328 onResult(response, result);
1329 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001330 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001331 }
1332
Amith Yamasani04e0d262012-02-14 11:50:53 -08001333 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001334 false /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001335 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001336 protected String toDebugString(long now) {
1337 if (loginOptions != null) loginOptions.keySet();
1338 return super.toDebugString(now) + ", getAuthToken"
1339 + ", " + account
1340 + ", authTokenType " + authTokenType
1341 + ", loginOptions " + loginOptions
1342 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1343 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001344
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001345 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001346 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001347 // If the caller doesn't have permission then create and return the
1348 // "grant permission" intent instead of the "getAuthToken" intent.
1349 if (!permissionGranted) {
1350 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1351 } else {
1352 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1353 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001354 }
1355
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001356 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001357 public void onResult(Bundle result) {
1358 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001359 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001360 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1361 new AccountAuthenticatorResponse(this),
1362 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001363 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001364 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001365 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001366 onResult(bundle);
1367 return;
1368 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001369 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001370 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001371 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1372 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001373 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001374 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001375 "the type and name should not be empty");
1376 return;
1377 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001378 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001379 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001380 authTokenType, authToken);
1381 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001382 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001383
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001384 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001385 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001386 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001387 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001388 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001389 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001390 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001391 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001392 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001393 }.bind();
1394 } finally {
1395 restoreCallingIdentity(identityToken);
1396 }
Fred Quintana60307342009-03-24 22:48:12 -07001397 }
1398
Dianne Hackborn41203752012-08-31 14:05:51 -07001399 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1400 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001401 int uid = intent.getIntExtra(
1402 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1403 String authTokenType = intent.getStringExtra(
1404 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1405 String authTokenLabel = intent.getStringExtra(
1406 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1407
1408 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1409 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001410 final String titleAndSubtitle =
1411 mContext.getString(R.string.permission_request_notification_with_subtitle,
1412 account.name);
1413 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001414 String title = titleAndSubtitle;
1415 String subtitle = "";
1416 if (index > 0) {
1417 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001418 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001419 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001420 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001421 n.setLatestEventInfo(mContext, title, subtitle,
1422 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001423 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1424 installNotification(getCredentialPermissionNotificationId(
1425 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001426 }
1427
Costin Manolache5f383ad92010-12-02 16:44:46 -08001428 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1429 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001430
1431 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001432 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001433 // Since it was set in Eclair+ we can't change it without breaking apps using
1434 // the intent from a non-Activity context.
1435 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001436 intent.addCategory(
1437 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001438
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001439 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001440 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1441 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001442 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001443
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001444 return intent;
1445 }
1446
1447 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1448 int uid) {
1449 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001450 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001451 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001452 final Pair<Pair<Account, String>, Integer> key =
1453 new Pair<Pair<Account, String>, Integer>(
1454 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001455 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001456 if (id == null) {
1457 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001458 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001459 }
1460 }
1461 return id;
1462 }
1463
Amith Yamasani04e0d262012-02-14 11:50:53 -08001464 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001465 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001466 synchronized (accounts.signinRequiredNotificationIds) {
1467 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001468 if (id == null) {
1469 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001470 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001471 }
1472 }
1473 return id;
1474 }
1475
Amith Yamasani27db4682013-03-30 17:07:47 -07001476 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001477 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001478 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001479 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1480 Log.v(TAG, "addAccount: accountType " + accountType
1481 + ", response " + response
1482 + ", authTokenType " + authTokenType
1483 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1484 + ", expectActivityLaunch " + expectActivityLaunch
1485 + ", caller's uid " + Binder.getCallingUid()
1486 + ", pid " + Binder.getCallingPid());
1487 }
Fred Quintana382601f2010-03-25 12:25:10 -07001488 if (response == null) throw new IllegalArgumentException("response is null");
1489 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001490 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001491
Amith Yamasani71e6c692013-03-24 17:39:28 -07001492 // Is user disallowed from modifying accounts?
Amith Yamasani27db4682013-03-30 17:07:47 -07001493 if (!canUserModifyAccounts(Binder.getCallingUid())) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001494 try {
1495 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1496 "User is not allowed to add an account!");
1497 } catch (RemoteException re) {
1498 }
Amith Yamasani23c8b962013-04-10 13:37:18 -07001499 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1500 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1501 long identityToken = clearCallingIdentity();
1502 try {
1503 mContext.startActivityAsUser(cantAddAccount, UserHandle.CURRENT);
1504 } finally {
1505 restoreCallingIdentity(identityToken);
1506 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001507 return;
1508 }
1509
Amith Yamasani04e0d262012-02-14 11:50:53 -08001510 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001511 final int pid = Binder.getCallingPid();
1512 final int uid = Binder.getCallingUid();
1513 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1514 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1515 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1516
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001517 long identityToken = clearCallingIdentity();
1518 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001519 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001520 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001521 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001522 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001523 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001524 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001525 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001526
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001527 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001528 protected String toDebugString(long now) {
1529 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001530 + ", accountType " + accountType
1531 + ", requiredFeatures "
1532 + (requiredFeatures != null
1533 ? TextUtils.join(",", requiredFeatures)
1534 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001535 }
1536 }.bind();
1537 } finally {
1538 restoreCallingIdentity(identityToken);
1539 }
Fred Quintana60307342009-03-24 22:48:12 -07001540 }
1541
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001542 @Override
1543 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1544 final Account account, final Bundle options, final boolean expectActivityLaunch,
1545 int userId) {
1546 // Only allow the system process to read accounts of other users
1547 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001548 && Binder.getCallingUid() != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001549 && mContext.checkCallingOrSelfPermission(
1550 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1551 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001552 throw new SecurityException("User " + UserHandle.getCallingUserId()
1553 + " trying to confirm account credentials for " + userId);
1554 }
1555
Fred Quintana56285a62010-12-02 14:20:51 -08001556 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1557 Log.v(TAG, "confirmCredentials: " + account
1558 + ", response " + response
1559 + ", expectActivityLaunch " + expectActivityLaunch
1560 + ", caller's uid " + Binder.getCallingUid()
1561 + ", pid " + Binder.getCallingPid());
1562 }
Fred Quintana382601f2010-03-25 12:25:10 -07001563 if (response == null) throw new IllegalArgumentException("response is null");
1564 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001565 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001566 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001567 long identityToken = clearCallingIdentity();
1568 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001569 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001570 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001571 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001572 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001573 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001574 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001575 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001576 protected String toDebugString(long now) {
1577 return super.toDebugString(now) + ", confirmCredentials"
1578 + ", " + account;
1579 }
1580 }.bind();
1581 } finally {
1582 restoreCallingIdentity(identityToken);
1583 }
Fred Quintana60307342009-03-24 22:48:12 -07001584 }
1585
Fred Quintanaa698f422009-04-08 19:14:54 -07001586 public void updateCredentials(IAccountManagerResponse response, final Account account,
1587 final String authTokenType, final boolean expectActivityLaunch,
1588 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001589 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1590 Log.v(TAG, "updateCredentials: " + account
1591 + ", response " + response
1592 + ", authTokenType " + authTokenType
1593 + ", expectActivityLaunch " + expectActivityLaunch
1594 + ", caller's uid " + Binder.getCallingUid()
1595 + ", pid " + Binder.getCallingPid());
1596 }
Fred Quintana382601f2010-03-25 12:25:10 -07001597 if (response == null) throw new IllegalArgumentException("response is null");
1598 if (account == null) throw new IllegalArgumentException("account is null");
1599 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001600 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001601 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001602 long identityToken = clearCallingIdentity();
1603 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001604 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001605 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001606 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001607 public void run() throws RemoteException {
1608 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1609 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001610 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001611 protected String toDebugString(long now) {
1612 if (loginOptions != null) loginOptions.keySet();
1613 return super.toDebugString(now) + ", updateCredentials"
1614 + ", " + account
1615 + ", authTokenType " + authTokenType
1616 + ", loginOptions " + loginOptions;
1617 }
1618 }.bind();
1619 } finally {
1620 restoreCallingIdentity(identityToken);
1621 }
Fred Quintana60307342009-03-24 22:48:12 -07001622 }
1623
Fred Quintanaa698f422009-04-08 19:14:54 -07001624 public void editProperties(IAccountManagerResponse response, final String accountType,
1625 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001626 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1627 Log.v(TAG, "editProperties: accountType " + accountType
1628 + ", response " + response
1629 + ", expectActivityLaunch " + expectActivityLaunch
1630 + ", caller's uid " + Binder.getCallingUid()
1631 + ", pid " + Binder.getCallingPid());
1632 }
Fred Quintana382601f2010-03-25 12:25:10 -07001633 if (response == null) throw new IllegalArgumentException("response is null");
1634 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001635 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001636 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001637 long identityToken = clearCallingIdentity();
1638 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001639 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001640 true /* stripAuthTokenFromResult */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001641 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001642 public void run() throws RemoteException {
1643 mAuthenticator.editProperties(this, mAccountType);
1644 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001645 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001646 protected String toDebugString(long now) {
1647 return super.toDebugString(now) + ", editProperties"
1648 + ", accountType " + accountType;
1649 }
1650 }.bind();
1651 } finally {
1652 restoreCallingIdentity(identityToken);
1653 }
Fred Quintana60307342009-03-24 22:48:12 -07001654 }
1655
Fred Quintana33269202009-04-20 16:05:10 -07001656 private class GetAccountsByTypeAndFeatureSession extends Session {
1657 private final String[] mFeatures;
1658 private volatile Account[] mAccountsOfType = null;
1659 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1660 private volatile int mCurrentAccount = 0;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001661 private int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001662
Amith Yamasani04e0d262012-02-14 11:50:53 -08001663 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001664 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001665 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001666 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001667 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001668 mFeatures = features;
1669 }
1670
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001671 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001672 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001673 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001674 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1675 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001676 }
Fred Quintana33269202009-04-20 16:05:10 -07001677 // check whether each account matches the requested features
1678 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1679 mCurrentAccount = 0;
1680
1681 checkAccount();
1682 }
1683
1684 public void checkAccount() {
1685 if (mCurrentAccount >= mAccountsOfType.length) {
1686 sendResult();
1687 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001688 }
Fred Quintana33269202009-04-20 16:05:10 -07001689
Fred Quintana29e94b82010-03-10 12:11:51 -08001690 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1691 if (accountAuthenticator == null) {
1692 // It is possible that the authenticator has died, which is indicated by
1693 // mAuthenticator being set to null. If this happens then just abort.
1694 // There is no need to send back a result or error in this case since
1695 // that already happened when mAuthenticator was cleared.
1696 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1697 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1698 + " connected to the authenticator, " + toDebugString());
1699 }
1700 return;
1701 }
Fred Quintana33269202009-04-20 16:05:10 -07001702 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001703 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001704 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001705 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001706 }
1707 }
1708
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001709 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001710 public void onResult(Bundle result) {
1711 mNumResults++;
1712 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001713 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001714 return;
1715 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001716 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001717 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1718 }
1719 mCurrentAccount++;
1720 checkAccount();
1721 }
1722
1723 public void sendResult() {
1724 IAccountManagerResponse response = getResponseAndClose();
1725 if (response != null) {
1726 try {
1727 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1728 for (int i = 0; i < accounts.length; i++) {
1729 accounts[i] = mAccountsWithFeatures.get(i);
1730 }
Fred Quintana56285a62010-12-02 14:20:51 -08001731 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1732 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1733 + response);
1734 }
Fred Quintana33269202009-04-20 16:05:10 -07001735 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001736 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001737 response.onResult(result);
1738 } catch (RemoteException e) {
1739 // if the caller is dead then there is no one to care about remote exceptions
1740 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1741 Log.v(TAG, "failure while notifying response", e);
1742 }
1743 }
1744 }
1745 }
1746
1747
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001748 @Override
Fred Quintana33269202009-04-20 16:05:10 -07001749 protected String toDebugString(long now) {
1750 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1751 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1752 }
1753 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001754
Amith Yamasani04e0d262012-02-14 11:50:53 -08001755 /**
1756 * Returns the accounts for a specific user
1757 * @hide
1758 */
1759 public Account[] getAccounts(int userId) {
1760 checkReadAccountsPermission();
1761 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001762 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001763 long identityToken = clearCallingIdentity();
1764 try {
1765 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001766 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001767 }
1768 } finally {
1769 restoreCallingIdentity(identityToken);
1770 }
1771 }
1772
Amith Yamasanif29f2362012-04-05 18:29:52 -07001773 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001774 * Returns accounts for all running users.
1775 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001776 * @hide
1777 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001778 public AccountAndUser[] getRunningAccounts() {
1779 final int[] runningUserIds;
1780 try {
1781 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1782 } catch (RemoteException e) {
1783 // Running in system_server; should never happen
1784 throw new RuntimeException(e);
1785 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001786 return getAccounts(runningUserIds);
1787 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001788
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001789 /** {@hide} */
1790 public AccountAndUser[] getAllAccounts() {
1791 final List<UserInfo> users = getUserManager().getUsers();
1792 final int[] userIds = new int[users.size()];
1793 for (int i = 0; i < userIds.length; i++) {
1794 userIds[i] = users.get(i).id;
1795 }
1796 return getAccounts(userIds);
1797 }
1798
1799 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001800 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1801 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001802 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001803 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001804 if (userAccounts == null) continue;
1805 synchronized (userAccounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001806 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
Amith Yamasani27db4682013-03-30 17:07:47 -07001807 Binder.getCallingUid(), null);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001808 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001809 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001810 }
1811 }
1812 }
1813 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001814
1815 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1816 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001817 }
1818
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001819 @Override
1820 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001821 return getAccountsAsUser(type, userId, null, -1);
1822 }
1823
1824 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
1825 int packageUid) {
1826 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001827 // Only allow the system process to read accounts of other users
1828 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001829 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001830 && mContext.checkCallingOrSelfPermission(
1831 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1832 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001833 throw new SecurityException("User " + UserHandle.getCallingUserId()
1834 + " trying to get account for " + userId);
1835 }
1836
Fred Quintana56285a62010-12-02 14:20:51 -08001837 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1838 Log.v(TAG, "getAccounts: accountType " + type
1839 + ", caller's uid " + Binder.getCallingUid()
1840 + ", pid " + Binder.getCallingPid());
1841 }
Amith Yamasani27db4682013-03-30 17:07:47 -07001842 // If the original calling app was using the framework account chooser activity, we'll
1843 // be passed in the original caller's uid here, which is what should be used for filtering.
1844 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
1845 callingUid = packageUid;
1846 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001847 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001848 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001849 long identityToken = clearCallingIdentity();
1850 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001851 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001852 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001853 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001854 } finally {
1855 restoreCallingIdentity(identityToken);
1856 }
1857 }
1858
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001859 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001860 public boolean addSharedAccountAsUser(Account account, int userId) {
1861 userId = handleIncomingUser(userId);
1862 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1863 ContentValues values = new ContentValues();
1864 values.put(ACCOUNTS_NAME, account.name);
1865 values.put(ACCOUNTS_TYPE, account.type);
1866 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1867 new String[] {account.name, account.type});
1868 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1869 if (accountId < 0) {
1870 Log.w(TAG, "insertAccountIntoDatabase: " + account
1871 + ", skipping the DB insert failed");
1872 return false;
1873 }
1874 return true;
1875 }
1876
1877 @Override
1878 public boolean removeSharedAccountAsUser(Account account, int userId) {
1879 userId = handleIncomingUser(userId);
1880 UserAccounts accounts = getUserAccounts(userId);
1881 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1882 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1883 new String[] {account.name, account.type});
1884 if (r > 0) {
1885 removeAccountInternal(accounts, account);
1886 }
1887 return r > 0;
1888 }
1889
1890 @Override
1891 public Account[] getSharedAccountsAsUser(int userId) {
1892 userId = handleIncomingUser(userId);
1893 UserAccounts accounts = getUserAccounts(userId);
1894 ArrayList<Account> accountList = new ArrayList<Account>();
1895 Cursor cursor = null;
1896 try {
1897 cursor = accounts.openHelper.getReadableDatabase()
1898 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1899 null, null, null, null, null);
1900 if (cursor != null && cursor.moveToFirst()) {
1901 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1902 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1903 do {
1904 accountList.add(new Account(cursor.getString(nameIndex),
1905 cursor.getString(typeIndex)));
1906 } while (cursor.moveToNext());
1907 }
1908 } finally {
1909 if (cursor != null) {
1910 cursor.close();
1911 }
1912 }
1913 Account[] accountArray = new Account[accountList.size()];
1914 accountList.toArray(accountArray);
1915 return accountArray;
1916 }
1917
1918 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001919 public Account[] getAccounts(String type) {
1920 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1921 }
1922
Amith Yamasani27db4682013-03-30 17:07:47 -07001923 @Override
1924 public Account[] getAccountsForPackage(String packageName, int uid) {
1925 int callingUid = Binder.getCallingUid();
1926 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
1927 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
1928 + callingUid + " with uid=" + uid);
1929 }
1930 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
1931 }
1932
Amith Yamasani3b458ad2013-04-18 18:40:07 -07001933 @Override
1934 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
1935 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
1936 int packageUid = -1;
1937 try {
1938 packageUid = AppGlobals.getPackageManager().getPackageUid(
1939 packageName, UserHandle.getCallingUserId());
1940 } catch (RemoteException re) {
1941 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
1942 return new Account[0];
1943 }
1944 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
1945 }
1946
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001947 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001948 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001949 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1950 Log.v(TAG, "getAccounts: accountType " + type
1951 + ", response " + response
1952 + ", features " + stringArrayToString(features)
1953 + ", caller's uid " + Binder.getCallingUid()
1954 + ", pid " + Binder.getCallingPid());
1955 }
Fred Quintana382601f2010-03-25 12:25:10 -07001956 if (response == null) throw new IllegalArgumentException("response is null");
1957 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001958 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001959 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001960 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001961 long identityToken = clearCallingIdentity();
1962 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001963 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001964 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001965 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001966 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001967 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001968 Bundle result = new Bundle();
1969 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1970 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001971 return;
1972 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001973 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
1974 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001975 } finally {
1976 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001977 }
1978 }
1979
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001980 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001981 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001982 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001983 try {
1984 if (cursor.moveToNext()) {
1985 return cursor.getLong(0);
1986 }
1987 return -1;
1988 } finally {
1989 cursor.close();
1990 }
1991 }
1992
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001993 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001994 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1995 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1996 new String[]{key}, null, null, null);
1997 try {
1998 if (cursor.moveToNext()) {
1999 return cursor.getLong(0);
2000 }
2001 return -1;
2002 } finally {
2003 cursor.close();
2004 }
2005 }
2006
Fred Quintanaa698f422009-04-08 19:14:54 -07002007 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002008 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002009 IAccountManagerResponse mResponse;
2010 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002011 final boolean mExpectActivityLaunch;
2012 final long mCreationTime;
2013
Fred Quintana33269202009-04-20 16:05:10 -07002014 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002015 private int mNumRequestContinued = 0;
2016 private int mNumErrors = 0;
2017
Fred Quintana60307342009-03-24 22:48:12 -07002018 IAccountAuthenticator mAuthenticator = null;
2019
Fred Quintana8570f742010-02-18 10:32:54 -08002020 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002021 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002022
Amith Yamasani04e0d262012-02-14 11:50:53 -08002023 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08002024 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07002025 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002026 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002027 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002028 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002029 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002030 mResponse = response;
2031 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002032 mExpectActivityLaunch = expectActivityLaunch;
2033 mCreationTime = SystemClock.elapsedRealtime();
2034 synchronized (mSessions) {
2035 mSessions.put(toString(), this);
2036 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002037 if (response != null) {
2038 try {
2039 response.asBinder().linkToDeath(this, 0 /* flags */);
2040 } catch (RemoteException e) {
2041 mResponse = null;
2042 binderDied();
2043 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002044 }
Fred Quintana60307342009-03-24 22:48:12 -07002045 }
2046
Fred Quintanaa698f422009-04-08 19:14:54 -07002047 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002048 if (mResponse == null) {
2049 // this session has already been closed
2050 return null;
2051 }
Fred Quintana60307342009-03-24 22:48:12 -07002052 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002053 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002054 return response;
2055 }
2056
Fred Quintanaa698f422009-04-08 19:14:54 -07002057 private void close() {
2058 synchronized (mSessions) {
2059 if (mSessions.remove(toString()) == null) {
2060 // the session was already closed, so bail out now
2061 return;
2062 }
2063 }
2064 if (mResponse != null) {
2065 // stop listening for response deaths
2066 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2067
2068 // clear this so that we don't accidentally send any further results
2069 mResponse = null;
2070 }
2071 cancelTimeout();
2072 unbind();
2073 }
2074
2075 public void binderDied() {
2076 mResponse = null;
2077 close();
2078 }
2079
2080 protected String toDebugString() {
2081 return toDebugString(SystemClock.elapsedRealtime());
2082 }
2083
2084 protected String toDebugString(long now) {
2085 return "Session: expectLaunch " + mExpectActivityLaunch
2086 + ", connected " + (mAuthenticator != null)
2087 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2088 + "/" + mNumErrors + ")"
2089 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2090 }
2091
Fred Quintana60307342009-03-24 22:48:12 -07002092 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002093 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2094 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2095 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002096 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002097 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002098 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002099 }
2100 }
2101
2102 private void unbind() {
2103 if (mAuthenticator != null) {
2104 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002105 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002106 }
2107 }
2108
2109 public void scheduleTimeout() {
2110 mMessageHandler.sendMessageDelayed(
2111 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2112 }
2113
2114 public void cancelTimeout() {
2115 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2116 }
2117
Fred Quintanab839afc2009-10-14 15:57:28 -07002118 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002119 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002120 try {
2121 run();
2122 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002123 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002124 "remote exception");
2125 }
Fred Quintana60307342009-03-24 22:48:12 -07002126 }
2127
Fred Quintanab839afc2009-10-14 15:57:28 -07002128 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002129 mAuthenticator = null;
2130 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002131 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002132 try {
2133 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2134 "disconnected");
2135 } catch (RemoteException e) {
2136 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2137 Log.v(TAG, "Session.onServiceDisconnected: "
2138 + "caught RemoteException while responding", e);
2139 }
2140 }
Fred Quintana60307342009-03-24 22:48:12 -07002141 }
2142 }
2143
Fred Quintanab839afc2009-10-14 15:57:28 -07002144 public abstract void run() throws RemoteException;
2145
Fred Quintana60307342009-03-24 22:48:12 -07002146 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002147 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002148 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002149 try {
2150 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2151 "timeout");
2152 } catch (RemoteException e) {
2153 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2154 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2155 e);
2156 }
2157 }
Fred Quintana60307342009-03-24 22:48:12 -07002158 }
2159 }
2160
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002161 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002162 public void onResult(Bundle result) {
2163 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002164 Intent intent = null;
2165 if (result != null
2166 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2167 /*
2168 * The Authenticator API allows third party authenticators to
2169 * supply arbitrary intents to other apps that they can run,
2170 * this can be very bad when those apps are in the system like
2171 * the System Settings.
2172 */
2173 PackageManager pm = mContext.getPackageManager();
2174 ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
2175 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2176 int authenticatorUid = Binder.getCallingUid();
2177 if (PackageManager.SIGNATURE_MATCH !=
2178 pm.checkSignatures(authenticatorUid, targetUid)) {
2179 throw new SecurityException(
2180 "Activity to be started with KEY_INTENT must " +
2181 "share Authenticator's signatures");
2182 }
2183 }
2184 if (result != null
2185 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002186 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2187 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002188 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2189 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002190 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2191 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002192 }
Fred Quintana60307342009-03-24 22:48:12 -07002193 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002194 IAccountManagerResponse response;
2195 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002196 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002197 response = mResponse;
2198 } else {
2199 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002200 }
Fred Quintana60307342009-03-24 22:48:12 -07002201 if (response != null) {
2202 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002203 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002204 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2205 Log.v(TAG, getClass().getSimpleName()
2206 + " calling onError() on response " + response);
2207 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002208 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002209 "null bundle returned");
2210 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002211 if (mStripAuthTokenFromResult) {
2212 result.remove(AccountManager.KEY_AUTHTOKEN);
2213 }
Fred Quintana56285a62010-12-02 14:20:51 -08002214 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2215 Log.v(TAG, getClass().getSimpleName()
2216 + " calling onResult() on response " + response);
2217 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002218 response.onResult(result);
2219 }
Fred Quintana60307342009-03-24 22:48:12 -07002220 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002221 // if the caller is dead then there is no one to care about remote exceptions
2222 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2223 Log.v(TAG, "failure while notifying response", e);
2224 }
Fred Quintana60307342009-03-24 22:48:12 -07002225 }
2226 }
2227 }
Fred Quintana60307342009-03-24 22:48:12 -07002228
Fred Quintanaa698f422009-04-08 19:14:54 -07002229 public void onRequestContinued() {
2230 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002231 }
2232
2233 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002234 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002235 IAccountManagerResponse response = getResponseAndClose();
2236 if (response != null) {
2237 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002238 Log.v(TAG, getClass().getSimpleName()
2239 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002240 }
2241 try {
2242 response.onError(errorCode, errorMessage);
2243 } catch (RemoteException e) {
2244 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2245 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2246 }
2247 }
2248 } else {
2249 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2250 Log.v(TAG, "Session.onError: already closed");
2251 }
Fred Quintana60307342009-03-24 22:48:12 -07002252 }
2253 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002254
2255 /**
2256 * find the component name for the authenticator and initiate a bind
2257 * if no authenticator or the bind fails then return false, otherwise return true
2258 */
2259 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002260 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2261 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2262 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002263 if (authenticatorInfo == null) {
2264 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2265 Log.v(TAG, "there is no authenticator for " + authenticatorType
2266 + ", bailing out");
2267 }
2268 return false;
2269 }
2270
2271 Intent intent = new Intent();
2272 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2273 intent.setComponent(authenticatorInfo.componentName);
2274 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2275 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2276 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002277 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2278 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002279 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2280 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2281 }
2282 return false;
2283 }
2284
2285
2286 return true;
2287 }
Fred Quintana60307342009-03-24 22:48:12 -07002288 }
2289
2290 private class MessageHandler extends Handler {
2291 MessageHandler(Looper looper) {
2292 super(looper);
2293 }
Costin Manolache3348f142009-09-29 18:58:36 -07002294
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002295 @Override
Fred Quintana60307342009-03-24 22:48:12 -07002296 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002297 switch (msg.what) {
2298 case MESSAGE_TIMED_OUT:
2299 Session session = (Session)msg.obj;
2300 session.onTimedOut();
2301 break;
2302
Amith Yamasani5be347b2013-03-31 17:44:31 -07002303 case MESSAGE_COPY_SHARED_ACCOUNT:
2304 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2305 break;
2306
Fred Quintana60307342009-03-24 22:48:12 -07002307 default:
2308 throw new IllegalStateException("unhandled message: " + msg.what);
2309 }
2310 }
2311 }
2312
Amith Yamasani04e0d262012-02-14 11:50:53 -08002313 private static String getDatabaseName(int userId) {
2314 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002315 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002316 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002317 // Migrate old file, if it exists, to the new location.
2318 // Make sure the new file doesn't already exist. A dummy file could have been
2319 // accidentally created in the old location, causing the new one to become corrupted
2320 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002321 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002322 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002323 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002324 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002325 if (!userDir.exists()) {
2326 if (!userDir.mkdirs()) {
2327 throw new IllegalStateException("User dir cannot be created: " + userDir);
2328 }
2329 }
2330 if (!oldFile.renameTo(databaseFile)) {
2331 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2332 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002333 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002334 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002335 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002336 }
2337
Amith Yamasani04e0d262012-02-14 11:50:53 -08002338 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002339
Amith Yamasani04e0d262012-02-14 11:50:53 -08002340 public DatabaseHelper(Context context, int userId) {
2341 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002342 }
2343
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002344 /**
2345 * This call needs to be made while the mCacheLock is held. The way to
2346 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2347 * @param db The database.
2348 */
Fred Quintana60307342009-03-24 22:48:12 -07002349 @Override
2350 public void onCreate(SQLiteDatabase db) {
2351 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2352 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2353 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2354 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2355 + ACCOUNTS_PASSWORD + " TEXT, "
2356 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2357
2358 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2359 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2360 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2361 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2362 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2363 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2364
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002365 createGrantsTable(db);
2366
Fred Quintana60307342009-03-24 22:48:12 -07002367 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2368 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2369 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2370 + EXTRAS_KEY + " TEXT NOT NULL, "
2371 + EXTRAS_VALUE + " TEXT, "
2372 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2373
2374 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2375 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2376 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002377
Amith Yamasani67df64b2012-12-14 12:09:36 -08002378 createSharedAccountsTable(db);
2379
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002380 createAccountsDeletionTrigger(db);
2381 }
2382
Amith Yamasani67df64b2012-12-14 12:09:36 -08002383 private void createSharedAccountsTable(SQLiteDatabase db) {
2384 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2385 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2386 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2387 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2388 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2389 }
2390
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002391 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002392 db.execSQL(""
2393 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2394 + " BEGIN"
2395 + " DELETE FROM " + TABLE_AUTHTOKENS
2396 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2397 + " DELETE FROM " + TABLE_EXTRAS
2398 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002399 + " DELETE FROM " + TABLE_GRANTS
2400 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002401 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002402 }
2403
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002404 private void createGrantsTable(SQLiteDatabase db) {
2405 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2406 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2407 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2408 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2409 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2410 + "," + GRANTS_GRANTEE_UID + "))");
2411 }
2412
Fred Quintana60307342009-03-24 22:48:12 -07002413 @Override
2414 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002415 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002416
Fred Quintanaa698f422009-04-08 19:14:54 -07002417 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002418 // no longer need to do anything since the work is done
2419 // when upgrading from version 2
2420 oldVersion++;
2421 }
2422
2423 if (oldVersion == 2) {
2424 createGrantsTable(db);
2425 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2426 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002427 oldVersion++;
2428 }
Costin Manolache3348f142009-09-29 18:58:36 -07002429
2430 if (oldVersion == 3) {
2431 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2432 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2433 oldVersion++;
2434 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002435
2436 if (oldVersion == 4) {
2437 createSharedAccountsTable(db);
2438 oldVersion++;
2439 }
2440
2441 if (oldVersion != newVersion) {
2442 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2443 }
Fred Quintana60307342009-03-24 22:48:12 -07002444 }
2445
2446 @Override
2447 public void onOpen(SQLiteDatabase db) {
2448 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2449 }
2450 }
2451
Fred Quintana60307342009-03-24 22:48:12 -07002452 public IBinder onBind(Intent intent) {
2453 return asBinder();
2454 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002455
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002456 /**
2457 * Searches array of arguments for the specified string
2458 * @param args array of argument strings
2459 * @param value value to search for
2460 * @return true if the value is contained in the array
2461 */
2462 private static boolean scanArgs(String[] args, String value) {
2463 if (args != null) {
2464 for (String arg : args) {
2465 if (value.equals(arg)) {
2466 return true;
2467 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002468 }
2469 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002470 return false;
2471 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002472
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002473 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002474 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002475 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2476 != PackageManager.PERMISSION_GRANTED) {
2477 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2478 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2479 + " without permission " + android.Manifest.permission.DUMP);
2480 return;
2481 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002482 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002483 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002484
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002485 final List<UserInfo> users = getUserManager().getUsers();
2486 for (UserInfo user : users) {
2487 ipw.println("User " + user + ":");
2488 ipw.increaseIndent();
2489 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2490 ipw.println();
2491 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002492 }
2493 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002494
Amith Yamasani04e0d262012-02-14 11:50:53 -08002495 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2496 String[] args, boolean isCheckinRequest) {
2497 synchronized (userAccounts.cacheLock) {
2498 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002499
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002500 if (isCheckinRequest) {
2501 // This is a checkin request. *Only* upload the account types and the count of each.
2502 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2503 null, null, ACCOUNTS_TYPE, null, null);
2504 try {
2505 while (cursor.moveToNext()) {
2506 // print type,count
2507 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2508 }
2509 } finally {
2510 if (cursor != null) {
2511 cursor.close();
2512 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002513 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002514 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002515 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002516 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002517 fout.println("Accounts: " + accounts.length);
2518 for (Account account : accounts) {
2519 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002520 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002521
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002522 fout.println();
2523 synchronized (mSessions) {
2524 final long now = SystemClock.elapsedRealtime();
2525 fout.println("Active Sessions: " + mSessions.size());
2526 for (Session session : mSessions.values()) {
2527 fout.println(" " + session.toDebugString(now));
2528 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002529 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002530
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002531 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002532 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002533 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002534 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002535 }
2536
Amith Yamasani04e0d262012-02-14 11:50:53 -08002537 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002538 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002539 long identityToken = clearCallingIdentity();
2540 try {
2541 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2542 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2543 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002544
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002545 if (intent.getComponent() != null &&
2546 GrantCredentialsPermissionActivity.class.getName().equals(
2547 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002548 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002549 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002550 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002551 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002552 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2553 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002554 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002555 final String notificationTitleFormat =
2556 mContext.getText(R.string.notification_title).toString();
2557 n.setLatestEventInfo(mContext,
2558 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002559 message, PendingIntent.getActivityAsUser(
2560 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002561 null, user));
2562 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002563 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002564 } finally {
2565 restoreCallingIdentity(identityToken);
2566 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002567 }
2568
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002569 protected void installNotification(final int notificationId, final Notification n,
2570 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002571 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002572 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002573 }
2574
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002575 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002576 long identityToken = clearCallingIdentity();
2577 try {
2578 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002579 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002580 } finally {
2581 restoreCallingIdentity(identityToken);
2582 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002583 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002584
Fred Quintanab38eb142010-02-24 13:40:54 -08002585 /** Succeeds if any of the specified permissions are granted. */
2586 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002587 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002588
2589 for (String perm : permissions) {
2590 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2591 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002592 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002593 }
2594 return;
2595 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002596 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002597
2598 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002599 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002600 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002601 }
2602
Amith Yamasani67df64b2012-12-14 12:09:36 -08002603 private int handleIncomingUser(int userId) {
2604 try {
2605 return ActivityManagerNative.getDefault().handleIncomingUser(
2606 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2607 } catch (RemoteException re) {
2608 // Shouldn't happen, local.
2609 }
2610 return userId;
2611 }
2612
Christopher Tateccbf84f2013-05-08 15:25:41 -07002613 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002614 final int callingUserId = UserHandle.getUserId(callingUid);
2615
2616 final PackageManager userPackageManager;
2617 try {
2618 userPackageManager = mContext.createPackageContextAsUser(
2619 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2620 } catch (NameNotFoundException e) {
2621 return false;
2622 }
2623
2624 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002625 for (String name : packages) {
2626 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002627 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002628 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07002629 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002630 return true;
2631 }
2632 } catch (PackageManager.NameNotFoundException e) {
2633 return false;
2634 }
2635 }
2636 return false;
2637 }
2638
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002639 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07002640 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002641 final boolean fromAuthenticator = account != null
2642 && hasAuthenticatorUid(account.type, callerUid);
2643 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002644 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002645 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2646 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002647 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002648 + ": is authenticator? " + fromAuthenticator
2649 + ", has explicit permission? " + hasExplicitGrants);
2650 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07002651 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002652 }
2653
Fred Quintana1a231912009-10-15 11:31:30 -07002654 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002655 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002656 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002657 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002658 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002659 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002660 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002661 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002662 }
2663 }
2664 return false;
2665 }
2666
Amith Yamasani04e0d262012-02-14 11:50:53 -08002667 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2668 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002669 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002670 return true;
2671 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002672 UserAccounts accounts = getUserAccountsForCaller();
2673 synchronized (accounts.cacheLock) {
2674 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2675 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002676 account.name, account.type};
2677 final boolean permissionGranted =
2678 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2679 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2680 // TODO: Skip this check when running automated tests. Replace this
2681 // with a more general solution.
2682 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002683 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002684 + " but ignoring since device is in test harness.");
2685 return true;
2686 }
2687 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002688 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002689 }
2690
2691 private void checkCallingUidAgainstAuthenticator(Account account) {
2692 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002693 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002694 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2695 Log.w(TAG, msg);
2696 throw new SecurityException(msg);
2697 }
2698 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2699 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2700 }
2701 }
2702
2703 private void checkAuthenticateAccountsPermission(Account account) {
2704 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2705 checkCallingUidAgainstAuthenticator(account);
2706 }
2707
2708 private void checkReadAccountsPermission() {
2709 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2710 }
2711
2712 private void checkManageAccountsPermission() {
2713 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2714 }
2715
Fred Quintanab38eb142010-02-24 13:40:54 -08002716 private void checkManageAccountsOrUseCredentialsPermissions() {
2717 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2718 Manifest.permission.USE_CREDENTIALS);
2719 }
2720
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002721 private boolean canUserModifyAccounts(int callingUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002722 if (callingUid != Process.myUid()) {
2723 if (getUserManager().getUserRestrictions(
2724 new UserHandle(UserHandle.getUserId(callingUid)))
2725 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002726 return false;
2727 }
2728 }
2729 return true;
2730 }
2731
Fred Quintanad9640ec2012-05-23 12:37:00 -07002732 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2733 throws RemoteException {
2734 final int callingUid = getCallingUid();
2735
Amith Yamasani27db4682013-03-30 17:07:47 -07002736 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002737 throw new SecurityException();
2738 }
2739
2740 if (value) {
2741 grantAppPermission(account, authTokenType, uid);
2742 } else {
2743 revokeAppPermission(account, authTokenType, uid);
2744 }
2745 }
2746
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002747 /**
2748 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2749 * <p>
2750 * Although this is public it can only be accessed via the AccountManagerService object
2751 * which is in the system. This means we don't need to protect it with permissions.
2752 * @hide
2753 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002754 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002755 if (account == null || authTokenType == null) {
2756 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002757 return;
2758 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002759 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002760 synchronized (accounts.cacheLock) {
2761 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002762 db.beginTransaction();
2763 try {
2764 long accountId = getAccountIdLocked(db, account);
2765 if (accountId >= 0) {
2766 ContentValues values = new ContentValues();
2767 values.put(GRANTS_ACCOUNTS_ID, accountId);
2768 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2769 values.put(GRANTS_GRANTEE_UID, uid);
2770 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2771 db.setTransactionSuccessful();
2772 }
2773 } finally {
2774 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002775 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002776 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2777 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002778 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002779 }
2780
2781 /**
2782 * Don't allow callers with the given uid permission to get credentials for
2783 * account/authTokenType.
2784 * <p>
2785 * Although this is public it can only be accessed via the AccountManagerService object
2786 * which is in the system. This means we don't need to protect it with permissions.
2787 * @hide
2788 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002789 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002790 if (account == null || authTokenType == null) {
2791 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002792 return;
2793 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002794 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002795 synchronized (accounts.cacheLock) {
2796 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002797 db.beginTransaction();
2798 try {
2799 long accountId = getAccountIdLocked(db, account);
2800 if (accountId >= 0) {
2801 db.delete(TABLE_GRANTS,
2802 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2803 + GRANTS_GRANTEE_UID + "=?",
2804 new String[]{String.valueOf(accountId), authTokenType,
2805 String.valueOf(uid)});
2806 db.setTransactionSuccessful();
2807 }
2808 } finally {
2809 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002810 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002811 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2812 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002813 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002814 }
Fred Quintana56285a62010-12-02 14:20:51 -08002815
2816 static final private String stringArrayToString(String[] value) {
2817 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2818 }
2819
Amith Yamasani04e0d262012-02-14 11:50:53 -08002820 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2821 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002822 if (oldAccountsForType != null) {
2823 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2824 for (Account curAccount : oldAccountsForType) {
2825 if (!curAccount.equals(account)) {
2826 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002827 }
2828 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002829 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002830 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002831 } else {
2832 Account[] newAccountsForType = new Account[newAccountsList.size()];
2833 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002834 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002835 }
Fred Quintana56285a62010-12-02 14:20:51 -08002836 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002837 accounts.userDataCache.remove(account);
2838 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002839 }
2840
2841 /**
2842 * This assumes that the caller has already checked that the account is not already present.
2843 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002844 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2845 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002846 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2847 Account[] newAccountsForType = new Account[oldLength + 1];
2848 if (accountsForType != null) {
2849 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002850 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002851 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002852 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002853 }
2854
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002855 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07002856 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002857 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07002858 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002859 return unfiltered;
2860 }
2861 if (mUserManager.getUserInfo(userAccounts.userId).isRestricted()) {
2862 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002863 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002864 // otherwise return non-shared accounts only.
2865 // This might be a temporary way to specify a whitelist
2866 String whiteList = mContext.getResources().getString(
2867 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2868 for (String packageName : packages) {
2869 if (whiteList.contains(";" + packageName + ";")) {
2870 return unfiltered;
2871 }
2872 }
2873 ArrayList<Account> allowed = new ArrayList<Account>();
2874 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2875 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002876 String requiredAccountType = "";
2877 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07002878 // If there's an explicit callingPackage specified, check if that package
2879 // opted in to see restricted accounts.
2880 if (callingPackage != null) {
2881 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002882 if (pi != null && pi.restrictedAccountType != null) {
2883 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07002884 }
2885 } else {
2886 // Otherwise check if the callingUid has a package that has opted in
2887 for (String packageName : packages) {
2888 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
2889 if (pi != null && pi.restrictedAccountType != null) {
2890 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07002891 break;
2892 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002893 }
2894 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002895 } catch (NameNotFoundException nnfe) {
2896 }
2897 for (Account account : unfiltered) {
2898 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002899 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002900 } else {
2901 boolean found = false;
2902 for (Account shared : sharedAccounts) {
2903 if (shared.equals(account)) {
2904 found = true;
2905 break;
2906 }
2907 }
2908 if (!found) {
2909 allowed.add(account);
2910 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002911 }
2912 }
2913 Account[] filtered = new Account[allowed.size()];
2914 allowed.toArray(filtered);
2915 return filtered;
2916 } else {
2917 return unfiltered;
2918 }
2919 }
2920
Amith Yamasani27db4682013-03-30 17:07:47 -07002921 /*
2922 * packageName can be null. If not null, it should be used to filter out restricted accounts
2923 * that the package is not allowed to access.
2924 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002925 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07002926 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002927 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002928 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002929 if (accounts == null) {
2930 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002931 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002932 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07002933 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002934 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002935 } else {
2936 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002937 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002938 totalLength += accounts.length;
2939 }
2940 if (totalLength == 0) {
2941 return EMPTY_ACCOUNT_ARRAY;
2942 }
2943 Account[] accounts = new Account[totalLength];
2944 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002945 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002946 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2947 accountsOfType.length);
2948 totalLength += accountsOfType.length;
2949 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002950 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002951 }
2952 }
2953
Amith Yamasani04e0d262012-02-14 11:50:53 -08002954 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2955 Account account, String key, String value) {
2956 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002957 if (userDataForAccount == null) {
2958 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002959 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002960 }
2961 if (value == null) {
2962 userDataForAccount.remove(key);
2963 } else {
2964 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002965 }
2966 }
2967
Amith Yamasani04e0d262012-02-14 11:50:53 -08002968 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2969 Account account, String key, String value) {
2970 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002971 if (authTokensForAccount == null) {
2972 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002973 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002974 }
2975 if (value == null) {
2976 authTokensForAccount.remove(key);
2977 } else {
2978 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002979 }
2980 }
2981
Amith Yamasani04e0d262012-02-14 11:50:53 -08002982 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2983 String authTokenType) {
2984 synchronized (accounts.cacheLock) {
2985 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002986 if (authTokensForAccount == null) {
2987 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002988 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002989 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002990 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002991 }
2992 return authTokensForAccount.get(authTokenType);
2993 }
2994 }
2995
Amith Yamasani04e0d262012-02-14 11:50:53 -08002996 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2997 synchronized (accounts.cacheLock) {
2998 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002999 if (userDataForAccount == null) {
3000 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003001 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003002 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003003 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003004 }
3005 return userDataForAccount.get(key);
3006 }
3007 }
3008
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003009 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3010 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003011 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003012 Cursor cursor = db.query(TABLE_EXTRAS,
3013 COLUMNS_EXTRAS_KEY_AND_VALUE,
3014 SELECTION_USERDATA_BY_ACCOUNT,
3015 new String[]{account.name, account.type},
3016 null, null, null);
3017 try {
3018 while (cursor.moveToNext()) {
3019 final String tmpkey = cursor.getString(0);
3020 final String value = cursor.getString(1);
3021 userDataForAccount.put(tmpkey, value);
3022 }
3023 } finally {
3024 cursor.close();
3025 }
3026 return userDataForAccount;
3027 }
3028
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003029 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
3030 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003031 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003032 Cursor cursor = db.query(TABLE_AUTHTOKENS,
3033 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
3034 SELECTION_AUTHTOKENS_BY_ACCOUNT,
3035 new String[]{account.name, account.type},
3036 null, null, null);
3037 try {
3038 while (cursor.moveToNext()) {
3039 final String type = cursor.getString(0);
3040 final String authToken = cursor.getString(1);
3041 authTokensForAccount.put(type, authToken);
3042 }
3043 } finally {
3044 cursor.close();
3045 }
3046 return authTokensForAccount;
3047 }
Fred Quintana60307342009-03-24 22:48:12 -07003048}