blob: 2145b76b39e52a570b46434427f57ed8e0518aa6 [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;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070050import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070051import android.database.Cursor;
52import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070053import android.database.sqlite.SQLiteDatabase;
54import android.database.sqlite.SQLiteOpenHelper;
Doug Zongker885cfc232009-10-21 16:52:44 -070055import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070056import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080057import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070058import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070059import android.os.IBinder;
60import android.os.Looper;
61import android.os.Message;
Amith Yamasani27db4682013-03-30 17:07:47 -070062import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070063import android.os.RemoteException;
64import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070065import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070066import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070067import android.text.TextUtils;
68import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070069import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070070import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080071import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070072
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070073import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080074import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080075import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070076import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070077import com.google.android.collect.Lists;
78import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070079
Oscar Montemayora8529f62009-11-18 10:14:20 -080080import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070081import java.io.FileDescriptor;
82import java.io.PrintWriter;
83import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080084import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070085import java.util.Collection;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070086import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070087import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -080088import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070089import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -080090import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070091import java.util.concurrent.atomic.AtomicInteger;
92import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -070093
Fred Quintana60307342009-03-24 22:48:12 -070094/**
95 * A system service that provides account, password, and authtoken management for all
96 * accounts on the device. Some of these calls are implemented with the help of the corresponding
97 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
98 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -070099 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700100 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700101 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700102public class AccountManagerService
103 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800104 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700105 private static final String TAG = "AccountManagerService";
106
107 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
108 private static final String DATABASE_NAME = "accounts.db";
Amith Yamasani67df64b2012-12-14 12:09:36 -0800109 private static final int DATABASE_VERSION = 5;
Fred Quintana60307342009-03-24 22:48:12 -0700110
111 private final Context mContext;
112
Fred Quintana56285a62010-12-02 14:20:51 -0800113 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700114 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800115
Fred Quintana60307342009-03-24 22:48:12 -0700116 private final MessageHandler mMessageHandler;
117
118 // Messages that can be sent on mHandler
119 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700120 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700121
Fred Quintana56285a62010-12-02 14:20:51 -0800122 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700123
124 private static final String TABLE_ACCOUNTS = "accounts";
125 private static final String ACCOUNTS_ID = "_id";
126 private static final String ACCOUNTS_NAME = "name";
127 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700128 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700129 private static final String ACCOUNTS_PASSWORD = "password";
130
131 private static final String TABLE_AUTHTOKENS = "authtokens";
132 private static final String AUTHTOKENS_ID = "_id";
133 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
134 private static final String AUTHTOKENS_TYPE = "type";
135 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
136
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700137 private static final String TABLE_GRANTS = "grants";
138 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
139 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
140 private static final String GRANTS_GRANTEE_UID = "uid";
141
Fred Quintana60307342009-03-24 22:48:12 -0700142 private static final String TABLE_EXTRAS = "extras";
143 private static final String EXTRAS_ID = "_id";
144 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
145 private static final String EXTRAS_KEY = "key";
146 private static final String EXTRAS_VALUE = "value";
147
148 private static final String TABLE_META = "meta";
149 private static final String META_KEY = "key";
150 private static final String META_VALUE = "value";
151
Amith Yamasani67df64b2012-12-14 12:09:36 -0800152 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
153
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700154 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
155 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700156 private static final Intent ACCOUNTS_CHANGED_INTENT;
Fred Quintanaa698f422009-04-08 19:14:54 -0700157
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700158 private static final String COUNT_OF_MATCHING_GRANTS = ""
159 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
160 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
161 + " AND " + GRANTS_GRANTEE_UID + "=?"
162 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
163 + " AND " + ACCOUNTS_NAME + "=?"
164 + " AND " + ACCOUNTS_TYPE + "=?";
165
Fred Quintana56285a62010-12-02 14:20:51 -0800166 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
167 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
168 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
169 AUTHTOKENS_AUTHTOKEN};
170
171 private static final String SELECTION_USERDATA_BY_ACCOUNT =
172 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
173 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
174
Fred Quintanaa698f422009-04-08 19:14:54 -0700175 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700176 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
177
Amith Yamasani04e0d262012-02-14 11:50:53 -0800178 static class UserAccounts {
179 private final int userId;
180 private final DatabaseHelper openHelper;
181 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
182 credentialsPermissionNotificationIds =
183 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
184 private final HashMap<Account, Integer> signinRequiredNotificationIds =
185 new HashMap<Account, Integer>();
186 private final Object cacheLock = new Object();
187 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700188 private final HashMap<String, Account[]> accountCache =
189 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800190 /** protected by the {@link #cacheLock} */
191 private HashMap<Account, HashMap<String, String>> userDataCache =
192 new HashMap<Account, HashMap<String, String>>();
193 /** protected by the {@link #cacheLock} */
194 private HashMap<Account, HashMap<String, String>> authTokenCache =
195 new HashMap<Account, HashMap<String, String>>();
196
197 UserAccounts(Context context, int userId) {
198 this.userId = userId;
199 synchronized (cacheLock) {
200 openHelper = new DatabaseHelper(context, userId);
201 }
202 }
203 }
204
205 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
206
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700207 private static AtomicReference<AccountManagerService> sThis =
208 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700209 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700210
211 static {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700212 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Fred Quintana7be59642009-08-24 18:29:25 -0700213 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
214 }
215
Fred Quintana56285a62010-12-02 14:20:51 -0800216
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700217 /**
218 * This should only be called by system code. One should only call this after the service
219 * has started.
220 * @return a reference to the AccountManagerService instance
221 * @hide
222 */
223 public static AccountManagerService getSingleton() {
224 return sThis.get();
225 }
Fred Quintana60307342009-03-24 22:48:12 -0700226
Fred Quintana56285a62010-12-02 14:20:51 -0800227 public AccountManagerService(Context context) {
228 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700229 }
230
Fred Quintana56285a62010-12-02 14:20:51 -0800231 public AccountManagerService(Context context, PackageManager packageManager,
232 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700233 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800234 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700235
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700236 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700237
Fred Quintana56285a62010-12-02 14:20:51 -0800238 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800239 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700240
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700241 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800242
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800243 IntentFilter intentFilter = new IntentFilter();
244 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
245 intentFilter.addDataScheme("package");
246 mContext.registerReceiver(new BroadcastReceiver() {
247 @Override
248 public void onReceive(Context context1, Intent intent) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800249 purgeOldGrantsAll();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800250 }
251 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800252
Amith Yamasani13593602012-03-22 16:16:17 -0700253 IntentFilter userFilter = new IntentFilter();
254 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800255 userFilter.addAction(Intent.ACTION_USER_STARTED);
256 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700257 @Override
258 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800259 String action = intent.getAction();
260 if (Intent.ACTION_USER_REMOVED.equals(action)) {
261 onUserRemoved(intent);
262 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
263 onUserStarted(intent);
264 }
Amith Yamasani13593602012-03-22 16:16:17 -0700265 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800266 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800267 }
268
Kenny Root26ff6622012-07-30 12:58:03 -0700269 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700270 }
271
Amith Yamasani258848d2012-08-10 17:06:33 -0700272 private UserManager getUserManager() {
273 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700274 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700275 }
276 return mUserManager;
277 }
278
Amith Yamasani04e0d262012-02-14 11:50:53 -0800279 private UserAccounts initUser(int userId) {
280 synchronized (mUsers) {
281 UserAccounts accounts = mUsers.get(userId);
282 if (accounts == null) {
283 accounts = new UserAccounts(mContext, userId);
284 mUsers.append(userId, accounts);
285 purgeOldGrants(accounts);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700286 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800287 }
288 return accounts;
289 }
290 }
291
292 private void purgeOldGrantsAll() {
293 synchronized (mUsers) {
294 for (int i = 0; i < mUsers.size(); i++) {
295 purgeOldGrants(mUsers.valueAt(i));
296 }
297 }
298 }
299
300 private void purgeOldGrants(UserAccounts accounts) {
301 synchronized (accounts.cacheLock) {
302 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800303 final Cursor cursor = db.query(TABLE_GRANTS,
304 new String[]{GRANTS_GRANTEE_UID},
305 null, null, GRANTS_GRANTEE_UID, null, null);
306 try {
307 while (cursor.moveToNext()) {
308 final int uid = cursor.getInt(0);
309 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
310 if (packageExists) {
311 continue;
312 }
313 Log.d(TAG, "deleting grants for UID " + uid
314 + " because its package is no longer installed");
315 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
316 new String[]{Integer.toString(uid)});
317 }
318 } finally {
319 cursor.close();
320 }
321 }
322 }
323
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700324 /**
325 * Validate internal set of accounts against installed authenticators for
326 * given user. Clears cached authenticators before validating.
327 */
328 public void validateAccounts(int userId) {
329 final UserAccounts accounts = getUserAccounts(userId);
330
331 // Invalidate user-specific cache to make sure we catch any
332 // removed authenticators.
333 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
334 }
335
336 /**
337 * Validate internal set of accounts against installed authenticators for
338 * given user. Clear cached authenticators before validating when requested.
339 */
340 private void validateAccountsInternal(
341 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
342 if (invalidateAuthenticatorCache) {
343 mAuthenticatorCache.invalidateCache(accounts.userId);
344 }
345
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700346 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
347 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
348 mAuthenticatorCache.getAllServices(accounts.userId)) {
349 knownAuth.add(service.type);
350 }
351
Amith Yamasani04e0d262012-02-14 11:50:53 -0800352 synchronized (accounts.cacheLock) {
353 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800354 boolean accountDeleted = false;
355 Cursor cursor = db.query(TABLE_ACCOUNTS,
356 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
357 null, null, null, null, null);
358 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800359 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800360 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700361 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800362 while (cursor.moveToNext()) {
363 final long accountId = cursor.getLong(0);
364 final String accountType = cursor.getString(1);
365 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700366
367 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700368 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800369 + accountType + " no longer has a registered authenticator");
370 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
371 accountDeleted = true;
372 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800373 accounts.userDataCache.remove(account);
374 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800375 } else {
376 ArrayList<String> accountNames = accountNamesByType.get(accountType);
377 if (accountNames == null) {
378 accountNames = new ArrayList<String>();
379 accountNamesByType.put(accountType, accountNames);
380 }
381 accountNames.add(accountName);
382 }
383 }
Andy McFadden2f362292012-01-20 14:43:38 -0800384 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800385 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800386 final String accountType = cur.getKey();
387 final ArrayList<String> accountNames = cur.getValue();
388 final Account[] accountsForType = new Account[accountNames.size()];
389 int i = 0;
390 for (String accountName : accountNames) {
391 accountsForType[i] = new Account(accountName, accountType);
392 ++i;
393 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800394 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800395 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800396 } finally {
397 cursor.close();
398 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800399 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800400 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800401 }
402 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700403 }
404
Amith Yamasani04e0d262012-02-14 11:50:53 -0800405 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700406 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800407 }
408
409 protected UserAccounts getUserAccounts(int userId) {
410 synchronized (mUsers) {
411 UserAccounts accounts = mUsers.get(userId);
412 if (accounts == null) {
413 accounts = initUser(userId);
414 mUsers.append(userId, accounts);
415 }
416 return accounts;
417 }
418 }
419
Amith Yamasani13593602012-03-22 16:16:17 -0700420 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700421 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700422 if (userId < 1) return;
423
424 UserAccounts accounts;
425 synchronized (mUsers) {
426 accounts = mUsers.get(userId);
427 mUsers.remove(userId);
428 }
429 if (accounts == null) {
430 File dbFile = new File(getDatabaseName(userId));
431 dbFile.delete();
432 return;
433 }
434
435 synchronized (accounts.cacheLock) {
436 accounts.openHelper.close();
437 File dbFile = new File(getDatabaseName(userId));
438 dbFile.delete();
439 }
440 }
441
Amith Yamasani67df64b2012-12-14 12:09:36 -0800442 private void onUserStarted(Intent intent) {
443 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
444 if (userId < 1) return;
445
446 // Check if there's a shared account that needs to be created as an account
447 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
448 if (sharedAccounts == null || sharedAccounts.length == 0) return;
449 Account[] accounts = getAccountsAsUser(null, userId);
450 for (Account sa : sharedAccounts) {
451 if (ArrayUtils.contains(accounts, sa)) continue;
452 // Account doesn't exist. Copy it now.
453 copyAccountToUser(sa, UserHandle.USER_OWNER, userId);
454 }
455 }
456
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700457 @Override
458 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700459 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700460 }
461
Fred Quintanaa698f422009-04-08 19:14:54 -0700462 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800463 if (Log.isLoggable(TAG, Log.VERBOSE)) {
464 Log.v(TAG, "getPassword: " + account
465 + ", caller's uid " + Binder.getCallingUid()
466 + ", pid " + Binder.getCallingPid());
467 }
Fred Quintana382601f2010-03-25 12:25:10 -0700468 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700469 checkAuthenticateAccountsPermission(account);
470
Amith Yamasani04e0d262012-02-14 11:50:53 -0800471 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700472 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700473 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800474 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700475 } finally {
476 restoreCallingIdentity(identityToken);
477 }
478 }
479
Amith Yamasani04e0d262012-02-14 11:50:53 -0800480 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700481 if (account == null) {
482 return null;
483 }
484
Amith Yamasani04e0d262012-02-14 11:50:53 -0800485 synchronized (accounts.cacheLock) {
486 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800487 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
488 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
489 new String[]{account.name, account.type}, null, null, null);
490 try {
491 if (cursor.moveToNext()) {
492 return cursor.getString(0);
493 }
494 return null;
495 } finally {
496 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700497 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700498 }
499 }
500
501 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800502 if (Log.isLoggable(TAG, Log.VERBOSE)) {
503 Log.v(TAG, "getUserData: " + account
504 + ", key " + key
505 + ", caller's uid " + Binder.getCallingUid()
506 + ", pid " + Binder.getCallingPid());
507 }
Fred Quintana382601f2010-03-25 12:25:10 -0700508 if (account == null) throw new IllegalArgumentException("account is null");
509 if (key == null) throw new IllegalArgumentException("key is null");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700510 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800511 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700512 long identityToken = clearCallingIdentity();
513 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800514 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700515 } finally {
516 restoreCallingIdentity(identityToken);
517 }
518 }
519
Fred Quintana97889762009-06-15 12:29:24 -0700520 public AuthenticatorDescription[] getAuthenticatorTypes() {
Fred Quintana56285a62010-12-02 14:20:51 -0800521 if (Log.isLoggable(TAG, Log.VERBOSE)) {
522 Log.v(TAG, "getAuthenticatorTypes: "
523 + "caller's uid " + Binder.getCallingUid()
524 + ", pid " + Binder.getCallingPid());
525 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700526 final int userId = UserHandle.getCallingUserId();
527 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700528 try {
Fred Quintana97889762009-06-15 12:29:24 -0700529 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700530 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700531 AuthenticatorDescription[] types =
532 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700533 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700534 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700535 : authenticatorCollection) {
536 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700537 i++;
538 }
539 return types;
540 } finally {
541 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700542 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700543 }
544
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700545 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700546 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800547 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700548 Log.v(TAG, "addAccountExplicitly: " + account
Fred Quintana56285a62010-12-02 14:20:51 -0800549 + ", caller's uid " + Binder.getCallingUid()
550 + ", pid " + Binder.getCallingPid());
551 }
Fred Quintana382601f2010-03-25 12:25:10 -0700552 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700553 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700554 /*
555 * Child users are not allowed to add accounts. Only the accounts that are
556 * shared by the parent profile can be added to child profile.
557 *
558 * TODO: Only allow accounts that were shared to be added by
559 * a limited user.
560 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700561
Amith Yamasani04e0d262012-02-14 11:50:53 -0800562 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700563 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700564 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700565 try {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800566 return addAccountInternal(accounts, account, password, extras, false);
Fred Quintana60307342009-03-24 22:48:12 -0700567 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700568 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700569 }
570 }
571
Amith Yamasani67df64b2012-12-14 12:09:36 -0800572 private boolean copyAccountToUser(final Account account, int userFrom, int userTo) {
573 final UserAccounts fromAccounts = getUserAccounts(userFrom);
574 final UserAccounts toAccounts = getUserAccounts(userTo);
575 if (fromAccounts == null || toAccounts == null) {
576 return false;
577 }
578
579 long identityToken = clearCallingIdentity();
580 try {
581 new Session(fromAccounts, null, account.type, false,
582 false /* stripAuthTokenFromResult */) {
583 protected String toDebugString(long now) {
584 return super.toDebugString(now) + ", getAccountCredentialsForClone"
585 + ", " + account.type;
586 }
587
588 public void run() throws RemoteException {
589 mAuthenticator.getAccountCredentialsForCloning(this, account);
590 }
591
592 public void onResult(Bundle result) {
593 if (result != null) {
594 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
595 // Create a Session for the target user and pass in the bundle
Amith Yamasani67df64b2012-12-14 12:09:36 -0800596 completeCloningAccount(result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800597 }
598 return;
599 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800600 super.onResult(result);
601 }
602 }
603 }.bind();
604 } finally {
605 restoreCallingIdentity(identityToken);
606 }
607 return true;
608 }
609
Amith Yamasani67df64b2012-12-14 12:09:36 -0800610 void completeCloningAccount(final Bundle result, final Account account,
611 final UserAccounts targetUser) {
612 long id = clearCallingIdentity();
613 try {
614 new Session(targetUser, null, account.type, false,
615 false /* stripAuthTokenFromResult */) {
616 protected String toDebugString(long now) {
617 return super.toDebugString(now) + ", getAccountCredentialsForClone"
618 + ", " + account.type;
619 }
620
621 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700622 // Confirm that the owner's account still exists before this step.
623 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
624 synchronized (owner.cacheLock) {
625 Account[] ownerAccounts = getAccounts(UserHandle.USER_OWNER);
626 for (Account acc : ownerAccounts) {
627 if (acc.equals(account)) {
628 mAuthenticator.addAccountFromCredentials(this, account, result);
629 break;
630 }
631 }
632 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800633 }
634
635 public void onResult(Bundle result) {
636 if (result != null) {
637 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
638 // TODO: Anything?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800639 } else {
640 // TODO: Show error notification
641 // TODO: Should we remove the shadow account to avoid retries?
Amith Yamasani67df64b2012-12-14 12:09:36 -0800642 }
643 return;
644 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800645 super.onResult(result);
646 }
647 }
648
649 public void onError(int errorCode, String errorMessage) {
650 super.onError(errorCode, errorMessage);
651 // TODO: Show error notification to user
652 // TODO: Should we remove the shadow account so that it doesn't keep trying?
653 }
654
655 }.bind();
656 } finally {
657 restoreCallingIdentity(id);
658 }
659 }
660
Amith Yamasani04e0d262012-02-14 11:50:53 -0800661 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Amith Yamasani67df64b2012-12-14 12:09:36 -0800662 Bundle extras, boolean restricted) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700663 if (account == null) {
664 return false;
665 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800666 synchronized (accounts.cacheLock) {
667 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800668 db.beginTransaction();
669 try {
670 long numMatches = DatabaseUtils.longForQuery(db,
671 "select count(*) from " + TABLE_ACCOUNTS
672 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
673 new String[]{account.name, account.type});
674 if (numMatches > 0) {
675 Log.w(TAG, "insertAccountIntoDatabase: " + account
676 + ", skipping since the account already exists");
677 return false;
678 }
679 ContentValues values = new ContentValues();
680 values.put(ACCOUNTS_NAME, account.name);
681 values.put(ACCOUNTS_TYPE, account.type);
682 values.put(ACCOUNTS_PASSWORD, password);
683 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
684 if (accountId < 0) {
685 Log.w(TAG, "insertAccountIntoDatabase: " + account
686 + ", skipping the DB insert failed");
687 return false;
688 }
689 if (extras != null) {
690 for (String key : extras.keySet()) {
691 final String value = extras.getString(key);
692 if (insertExtraLocked(db, accountId, key, value) < 0) {
693 Log.w(TAG, "insertAccountIntoDatabase: " + account
694 + ", skipping since insertExtra failed for key " + key);
695 return false;
696 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700697 }
698 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800699 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800700 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800701 } finally {
702 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700703 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800704 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700705 }
706 if (accounts.userId == UserHandle.USER_OWNER) {
707 addAccountToLimitedUsers(account);
708 }
709 return true;
710 }
711
712 /**
713 * Adds the account to all limited users as shared accounts. If the user is currently
714 * running, then clone the account too.
715 * @param account the account to share with limited users
716 */
717 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700718 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700719 for (UserInfo user : users) {
720 if (user.isRestricted()) {
721 addSharedAccountAsUser(account, user.id);
722 try {
723 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
724 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
725 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
726 account));
727 }
728 } catch (RemoteException re) {
729 // Shouldn't happen
730 }
731 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700732 }
733 }
734
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800735 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700736 ContentValues values = new ContentValues();
737 values.put(EXTRAS_KEY, key);
738 values.put(EXTRAS_ACCOUNTS_ID, accountId);
739 values.put(EXTRAS_VALUE, value);
740 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
741 }
742
Fred Quintana3084a6f2010-01-14 18:02:03 -0800743 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800744 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800745 if (Log.isLoggable(TAG, Log.VERBOSE)) {
746 Log.v(TAG, "hasFeatures: " + account
747 + ", response " + response
748 + ", features " + stringArrayToString(features)
749 + ", caller's uid " + Binder.getCallingUid()
750 + ", pid " + Binder.getCallingPid());
751 }
Fred Quintana382601f2010-03-25 12:25:10 -0700752 if (response == null) throw new IllegalArgumentException("response is null");
753 if (account == null) throw new IllegalArgumentException("account is null");
754 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800755 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800756 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800757 long identityToken = clearCallingIdentity();
758 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800759 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800760 } finally {
761 restoreCallingIdentity(identityToken);
762 }
763 }
764
765 private class TestFeaturesSession extends Session {
766 private final String[] mFeatures;
767 private final Account mAccount;
768
Amith Yamasani04e0d262012-02-14 11:50:53 -0800769 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800770 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800771 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800772 true /* stripAuthTokenFromResult */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800773 mFeatures = features;
774 mAccount = account;
775 }
776
777 public void run() throws RemoteException {
778 try {
779 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
780 } catch (RemoteException e) {
781 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
782 }
783 }
784
785 public void onResult(Bundle result) {
786 IAccountManagerResponse response = getResponseAndClose();
787 if (response != null) {
788 try {
789 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700790 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800791 return;
792 }
Fred Quintana56285a62010-12-02 14:20:51 -0800793 if (Log.isLoggable(TAG, Log.VERBOSE)) {
794 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
795 + response);
796 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800797 final Bundle newResult = new Bundle();
798 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
799 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
800 response.onResult(newResult);
801 } catch (RemoteException e) {
802 // if the caller is dead then there is no one to care about remote exceptions
803 if (Log.isLoggable(TAG, Log.VERBOSE)) {
804 Log.v(TAG, "failure while notifying response", e);
805 }
806 }
807 }
808 }
809
810 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -0800811 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800812 + ", " + mAccount
813 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
814 }
815 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800816
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700817 public void removeAccount(IAccountManagerResponse response, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800818 if (Log.isLoggable(TAG, Log.VERBOSE)) {
819 Log.v(TAG, "removeAccount: " + account
820 + ", response " + response
821 + ", caller's uid " + Binder.getCallingUid()
822 + ", pid " + Binder.getCallingPid());
823 }
Fred Quintana382601f2010-03-25 12:25:10 -0700824 if (response == null) throw new IllegalArgumentException("response is null");
825 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700826 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700827 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800828 UserAccounts accounts = getUserAccountsForCaller();
Amith Yamasanie4cf7342012-12-17 11:12:09 -0800829 if (!canUserModifyAccounts(Binder.getCallingUid())) {
830 try {
831 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
832 "User cannot modify accounts");
833 } catch (RemoteException re) {
834 }
835 }
836
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700837 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800838
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700839 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800840 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800841 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -0800842 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800843 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800844 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700845 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -0800846 }
847 }
848 }
849
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700850 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800851 new RemoveAccountSession(accounts, response, account).bind();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700852 } finally {
853 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700854 }
Fred Quintana60307342009-03-24 22:48:12 -0700855 }
856
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700857 private class RemoveAccountSession extends Session {
858 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800859 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
860 Account account) {
861 super(accounts, response, account.type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -0800862 true /* stripAuthTokenFromResult */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700863 mAccount = account;
864 }
865
866 protected String toDebugString(long now) {
867 return super.toDebugString(now) + ", removeAccount"
868 + ", account " + mAccount;
869 }
870
871 public void run() throws RemoteException {
872 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
873 }
874
875 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700876 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
877 && !result.containsKey(AccountManager.KEY_INTENT)) {
878 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700879 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800880 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700881 }
882 IAccountManagerResponse response = getResponseAndClose();
883 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -0800884 if (Log.isLoggable(TAG, Log.VERBOSE)) {
885 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
886 + response);
887 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700888 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -0700889 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700890 try {
891 response.onResult(result2);
892 } catch (RemoteException e) {
893 // ignore
894 }
895 }
896 }
897 super.onResult(result);
898 }
899 }
900
Amith Yamasani04e0d262012-02-14 11:50:53 -0800901 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800902 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800903 removeAccountInternal(getUserAccountsForCaller(), account);
904 }
905
906 private void removeAccountInternal(UserAccounts accounts, Account account) {
907 synchronized (accounts.cacheLock) {
908 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800909 db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
910 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -0800911 removeAccountFromCacheLocked(accounts, account);
912 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800913 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800914 if (accounts.userId == UserHandle.USER_OWNER) {
915 // Owner's account was removed, remove from any users that are sharing
916 // this account.
917 long id = Binder.clearCallingIdentity();
918 try {
919 List<UserInfo> users = mUserManager.getUsers(true);
920 for (UserInfo user : users) {
921 if (!user.isPrimary() && user.isRestricted()) {
922 removeSharedAccountAsUser(account, user.id);
923 }
924 }
925 } finally {
926 Binder.restoreCallingIdentity(id);
927 }
928 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700929 }
930
Maggie Benthalla12fccf2013-03-14 18:02:12 -0400931 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700932 public void invalidateAuthToken(String accountType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -0800933 if (Log.isLoggable(TAG, Log.VERBOSE)) {
934 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
935 + ", caller's uid " + Binder.getCallingUid()
936 + ", pid " + Binder.getCallingPid());
937 }
Fred Quintana382601f2010-03-25 12:25:10 -0700938 if (accountType == null) throw new IllegalArgumentException("accountType is null");
939 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Fred Quintanab38eb142010-02-24 13:40:54 -0800940 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800941 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700942 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700943 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800944 synchronized (accounts.cacheLock) {
945 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800946 db.beginTransaction();
947 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800948 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800949 db.setTransactionSuccessful();
950 } finally {
951 db.endTransaction();
952 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700953 }
Fred Quintana60307342009-03-24 22:48:12 -0700954 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700955 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700956 }
957 }
958
Amith Yamasani04e0d262012-02-14 11:50:53 -0800959 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
960 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700961 if (authToken == null || accountType == null) {
962 return;
963 }
Fred Quintana33269202009-04-20 16:05:10 -0700964 Cursor cursor = db.rawQuery(
965 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
966 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
967 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
968 + " FROM " + TABLE_ACCOUNTS
969 + " JOIN " + TABLE_AUTHTOKENS
970 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
971 + " = " + AUTHTOKENS_ACCOUNTS_ID
972 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
973 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
974 new String[]{authToken, accountType});
975 try {
976 while (cursor.moveToNext()) {
977 long authTokenId = cursor.getLong(0);
978 String accountName = cursor.getString(1);
979 String authTokenType = cursor.getString(2);
980 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800981 writeAuthTokenIntoCacheLocked(accounts, db, new Account(accountName, accountType),
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800982 authTokenType, null);
Fred Quintana60307342009-03-24 22:48:12 -0700983 }
Fred Quintana33269202009-04-20 16:05:10 -0700984 } finally {
985 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -0700986 }
987 }
988
Amith Yamasani04e0d262012-02-14 11:50:53 -0800989 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
990 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -0700991 if (account == null || type == null) {
992 return false;
993 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700994 cancelNotification(getSigninRequiredNotificationId(accounts, account),
995 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -0800996 synchronized (accounts.cacheLock) {
997 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800998 db.beginTransaction();
999 try {
1000 long accountId = getAccountIdLocked(db, account);
1001 if (accountId < 0) {
1002 return false;
1003 }
1004 db.delete(TABLE_AUTHTOKENS,
1005 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1006 new String[]{type});
1007 ContentValues values = new ContentValues();
1008 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1009 values.put(AUTHTOKENS_TYPE, type);
1010 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1011 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1012 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001013 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001014 return true;
1015 }
Fred Quintana33269202009-04-20 16:05:10 -07001016 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001017 } finally {
1018 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001019 }
Fred Quintana60307342009-03-24 22:48:12 -07001020 }
1021 }
1022
Fred Quintanaa698f422009-04-08 19:14:54 -07001023 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001024 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1025 Log.v(TAG, "peekAuthToken: " + account
1026 + ", authTokenType " + authTokenType
1027 + ", caller's uid " + Binder.getCallingUid()
1028 + ", pid " + Binder.getCallingPid());
1029 }
Fred Quintana382601f2010-03-25 12:25:10 -07001030 if (account == null) throw new IllegalArgumentException("account is null");
1031 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001032 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001033 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001034 long identityToken = clearCallingIdentity();
1035 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001036 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001037 } finally {
1038 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001039 }
Fred Quintana60307342009-03-24 22:48:12 -07001040 }
1041
Fred Quintanaa698f422009-04-08 19:14:54 -07001042 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001043 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1044 Log.v(TAG, "setAuthToken: " + account
1045 + ", authTokenType " + authTokenType
1046 + ", caller's uid " + Binder.getCallingUid()
1047 + ", pid " + Binder.getCallingPid());
1048 }
Fred Quintana382601f2010-03-25 12:25:10 -07001049 if (account == null) throw new IllegalArgumentException("account is null");
1050 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001051 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001052 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001053 long identityToken = clearCallingIdentity();
1054 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001055 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001056 } finally {
1057 restoreCallingIdentity(identityToken);
1058 }
Fred Quintana60307342009-03-24 22:48:12 -07001059 }
1060
Fred Quintanaa698f422009-04-08 19:14:54 -07001061 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001062 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1063 Log.v(TAG, "setAuthToken: " + account
1064 + ", caller's uid " + Binder.getCallingUid()
1065 + ", pid " + Binder.getCallingPid());
1066 }
Fred Quintana382601f2010-03-25 12:25:10 -07001067 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001068 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001069 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001070 long identityToken = clearCallingIdentity();
1071 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001072 setPasswordInternal(accounts, account, password);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001073 } finally {
1074 restoreCallingIdentity(identityToken);
1075 }
Fred Quintana60307342009-03-24 22:48:12 -07001076 }
1077
Amith Yamasani04e0d262012-02-14 11:50:53 -08001078 private void setPasswordInternal(UserAccounts accounts, Account account, String password) {
Fred Quintana31957f12009-10-21 13:43:10 -07001079 if (account == null) {
1080 return;
1081 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001082 synchronized (accounts.cacheLock) {
1083 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001084 db.beginTransaction();
1085 try {
1086 final ContentValues values = new ContentValues();
1087 values.put(ACCOUNTS_PASSWORD, password);
1088 final long accountId = getAccountIdLocked(db, account);
1089 if (accountId >= 0) {
1090 final String[] argsAccountId = {String.valueOf(accountId)};
1091 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1092 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001093 accounts.authTokenCache.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001094 db.setTransactionSuccessful();
Costin Manolachef5ffe892011-01-19 09:35:32 -08001095 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001096 } finally {
1097 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001098 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001099 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001100 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001101 }
1102
Amith Yamasani04e0d262012-02-14 11:50:53 -08001103 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001104 Log.i(TAG, "the accounts changed, sending broadcast of "
1105 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001106 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001107 }
1108
Fred Quintanaa698f422009-04-08 19:14:54 -07001109 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001110 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1111 Log.v(TAG, "clearPassword: " + account
1112 + ", caller's uid " + Binder.getCallingUid()
1113 + ", pid " + Binder.getCallingPid());
1114 }
Fred Quintana382601f2010-03-25 12:25:10 -07001115 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001116 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001117 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001118 long identityToken = clearCallingIdentity();
1119 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001120 setPasswordInternal(accounts, account, null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001121 } finally {
1122 restoreCallingIdentity(identityToken);
1123 }
Fred Quintana60307342009-03-24 22:48:12 -07001124 }
1125
Fred Quintanaa698f422009-04-08 19:14:54 -07001126 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001127 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1128 Log.v(TAG, "setUserData: " + account
1129 + ", key " + key
1130 + ", caller's uid " + Binder.getCallingUid()
1131 + ", pid " + Binder.getCallingPid());
1132 }
Fred Quintana382601f2010-03-25 12:25:10 -07001133 if (key == null) throw new IllegalArgumentException("key is null");
1134 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001135 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001136 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001137 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001138 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001139 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001140 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001141 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001142 }
1143 }
1144
Amith Yamasani04e0d262012-02-14 11:50:53 -08001145 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1146 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001147 if (account == null || key == null) {
1148 return;
1149 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001150 synchronized (accounts.cacheLock) {
1151 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001152 db.beginTransaction();
1153 try {
1154 long accountId = getAccountIdLocked(db, account);
1155 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001156 return;
1157 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001158 long extrasId = getExtrasIdLocked(db, accountId, key);
1159 if (extrasId < 0 ) {
1160 extrasId = insertExtraLocked(db, accountId, key, value);
1161 if (extrasId < 0) {
1162 return;
1163 }
1164 } else {
1165 ContentValues values = new ContentValues();
1166 values.put(EXTRAS_VALUE, value);
1167 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1168 return;
1169 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001170
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001171 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001172 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001173 db.setTransactionSuccessful();
1174 } finally {
1175 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001176 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001177 }
1178 }
1179
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001180 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001181 if (result == null) {
1182 Log.e(TAG, "the result is unexpectedly null", new Exception());
1183 }
1184 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1185 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1186 + response);
1187 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001188 try {
1189 response.onResult(result);
1190 } catch (RemoteException e) {
1191 // if the caller is dead then there is no one to care about remote
1192 // exceptions
1193 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1194 Log.v(TAG, "failure while notifying response", e);
1195 }
1196 }
1197 }
1198
Fred Quintanad9640ec2012-05-23 12:37:00 -07001199 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1200 final String authTokenType)
1201 throws RemoteException {
1202 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001203 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1204
Fred Quintanad9640ec2012-05-23 12:37:00 -07001205 final int callingUid = getCallingUid();
1206 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001207 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001208 throw new SecurityException("can only call from system");
1209 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001210 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001211 long identityToken = clearCallingIdentity();
1212 try {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001213 new Session(accounts, response, accountType, false,
Costin Manolache5f383ad92010-12-02 16:44:46 -08001214 false /* stripAuthTokenFromResult */) {
1215 protected String toDebugString(long now) {
1216 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001217 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001218 + ", authTokenType " + authTokenType;
1219 }
1220
1221 public void run() throws RemoteException {
1222 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1223 }
1224
1225 public void onResult(Bundle result) {
1226 if (result != null) {
1227 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1228 Bundle bundle = new Bundle();
1229 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1230 super.onResult(bundle);
1231 return;
1232 } else {
1233 super.onResult(result);
1234 }
1235 }
1236 }.bind();
1237 } finally {
1238 restoreCallingIdentity(identityToken);
1239 }
1240 }
1241
Fred Quintanaa698f422009-04-08 19:14:54 -07001242 public void getAuthToken(IAccountManagerResponse response, final Account account,
1243 final String authTokenType, final boolean notifyOnAuthFailure,
Costin Manolachec6684f92011-01-14 11:25:39 -08001244 final boolean expectActivityLaunch, Bundle loginOptionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001245 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1246 Log.v(TAG, "getAuthToken: " + account
1247 + ", response " + response
1248 + ", authTokenType " + authTokenType
1249 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1250 + ", expectActivityLaunch " + expectActivityLaunch
1251 + ", caller's uid " + Binder.getCallingUid()
1252 + ", pid " + Binder.getCallingPid());
1253 }
Fred Quintana382601f2010-03-25 12:25:10 -07001254 if (response == null) throw new IllegalArgumentException("response is null");
1255 if (account == null) throw new IllegalArgumentException("account is null");
1256 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001257 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001258 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001259 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1260 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1261 AuthenticatorDescription.newKey(account.type), accounts.userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001262 final boolean customTokens =
1263 authenticatorInfo != null && authenticatorInfo.type.customTokens;
1264
Amith Yamasanid20ea2f2013-05-08 12:57:01 -07001265 // Check to see that the app is authorized to access the account, in case it's a
1266 // restricted account.
1267 if (!ArrayUtils.contains(getAccounts((String) null), account)) {
1268 throw new IllegalArgumentException("no such account");
1269 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001270 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001271 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001272 final boolean permissionGranted = customTokens ||
1273 permissionIsGranted(account, authTokenType, callerUid);
1274
Costin Manolachec6684f92011-01-14 11:25:39 -08001275 final Bundle loginOptions = (loginOptionsIn == null) ? new Bundle() :
1276 loginOptionsIn;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001277 // let authenticator know the identity of the caller
1278 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1279 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
1280 if (notifyOnAuthFailure) {
1281 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001282 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001283
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001284 long identityToken = clearCallingIdentity();
1285 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001286 // if the caller has permission, do the peek. otherwise go the more expensive
1287 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001288 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001289 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001290 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001291 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001292 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1293 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1294 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001295 onResult(response, result);
1296 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001297 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001298 }
1299
Amith Yamasani04e0d262012-02-14 11:50:53 -08001300 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001301 false /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001302 protected String toDebugString(long now) {
1303 if (loginOptions != null) loginOptions.keySet();
1304 return super.toDebugString(now) + ", getAuthToken"
1305 + ", " + account
1306 + ", authTokenType " + authTokenType
1307 + ", loginOptions " + loginOptions
1308 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1309 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001310
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001311 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001312 // If the caller doesn't have permission then create and return the
1313 // "grant permission" intent instead of the "getAuthToken" intent.
1314 if (!permissionGranted) {
1315 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1316 } else {
1317 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1318 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001319 }
1320
1321 public void onResult(Bundle result) {
1322 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001323 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001324 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1325 new AccountAuthenticatorResponse(this),
1326 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001327 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001328 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001329 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001330 onResult(bundle);
1331 return;
1332 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001333 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001334 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001335 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1336 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001337 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001338 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001339 "the type and name should not be empty");
1340 return;
1341 }
Costin Manolachea40c6302010-12-13 14:50:45 -08001342 if (!customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001343 saveAuthTokenToDatabase(mAccounts, new Account(name, type),
Costin Manolachea40c6302010-12-13 14:50:45 -08001344 authTokenType, authToken);
1345 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001346 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001347
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001348 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001349 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001350 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001351 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001352 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001353 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001354 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001355 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001356 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001357 }.bind();
1358 } finally {
1359 restoreCallingIdentity(identityToken);
1360 }
Fred Quintana60307342009-03-24 22:48:12 -07001361 }
1362
Dianne Hackborn41203752012-08-31 14:05:51 -07001363 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1364 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001365 int uid = intent.getIntExtra(
1366 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1367 String authTokenType = intent.getStringExtra(
1368 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1369 String authTokenLabel = intent.getStringExtra(
1370 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1371
1372 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1373 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001374 final String titleAndSubtitle =
1375 mContext.getString(R.string.permission_request_notification_with_subtitle,
1376 account.name);
1377 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001378 String title = titleAndSubtitle;
1379 String subtitle = "";
1380 if (index > 0) {
1381 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001382 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001383 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001384 UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001385 n.setLatestEventInfo(mContext, title, subtitle,
1386 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001387 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1388 installNotification(getCredentialPermissionNotificationId(
1389 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001390 }
1391
Costin Manolache5f383ad92010-12-02 16:44:46 -08001392 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1393 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001394
1395 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001396 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001397 // Since it was set in Eclair+ we can't change it without breaking apps using
1398 // the intent from a non-Activity context.
1399 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001400 intent.addCategory(
1401 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001402
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001403 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001404 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1405 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001406 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001407
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001408 return intent;
1409 }
1410
1411 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
1412 int uid) {
1413 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001414 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001415 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001416 final Pair<Pair<Account, String>, Integer> key =
1417 new Pair<Pair<Account, String>, Integer>(
1418 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001419 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001420 if (id == null) {
1421 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001422 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001423 }
1424 }
1425 return id;
1426 }
1427
Amith Yamasani04e0d262012-02-14 11:50:53 -08001428 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001429 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001430 synchronized (accounts.signinRequiredNotificationIds) {
1431 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001432 if (id == null) {
1433 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001434 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001435 }
1436 }
1437 return id;
1438 }
1439
Amith Yamasani27db4682013-03-30 17:07:47 -07001440 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07001441 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001442 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08001443 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1444 Log.v(TAG, "addAccount: accountType " + accountType
1445 + ", response " + response
1446 + ", authTokenType " + authTokenType
1447 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
1448 + ", expectActivityLaunch " + expectActivityLaunch
1449 + ", caller's uid " + Binder.getCallingUid()
1450 + ", pid " + Binder.getCallingPid());
1451 }
Fred Quintana382601f2010-03-25 12:25:10 -07001452 if (response == null) throw new IllegalArgumentException("response is null");
1453 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001454 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001455
Amith Yamasani71e6c692013-03-24 17:39:28 -07001456 // Is user disallowed from modifying accounts?
Amith Yamasani27db4682013-03-30 17:07:47 -07001457 if (!canUserModifyAccounts(Binder.getCallingUid())) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001458 try {
1459 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1460 "User is not allowed to add an account!");
1461 } catch (RemoteException re) {
1462 }
Amith Yamasani23c8b962013-04-10 13:37:18 -07001463 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
1464 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1465 long identityToken = clearCallingIdentity();
1466 try {
1467 mContext.startActivityAsUser(cantAddAccount, UserHandle.CURRENT);
1468 } finally {
1469 restoreCallingIdentity(identityToken);
1470 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001471 return;
1472 }
1473
Amith Yamasani04e0d262012-02-14 11:50:53 -08001474 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001475 final int pid = Binder.getCallingPid();
1476 final int uid = Binder.getCallingUid();
1477 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
1478 options.putInt(AccountManager.KEY_CALLER_UID, uid);
1479 options.putInt(AccountManager.KEY_CALLER_PID, pid);
1480
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001481 long identityToken = clearCallingIdentity();
1482 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001483 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001484 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001485 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07001486 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07001487 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001488 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001489
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001490 protected String toDebugString(long now) {
1491 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07001492 + ", accountType " + accountType
1493 + ", requiredFeatures "
1494 + (requiredFeatures != null
1495 ? TextUtils.join(",", requiredFeatures)
1496 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001497 }
1498 }.bind();
1499 } finally {
1500 restoreCallingIdentity(identityToken);
1501 }
Fred Quintana60307342009-03-24 22:48:12 -07001502 }
1503
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001504 @Override
1505 public void confirmCredentialsAsUser(IAccountManagerResponse response,
1506 final Account account, final Bundle options, final boolean expectActivityLaunch,
1507 int userId) {
1508 // Only allow the system process to read accounts of other users
1509 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001510 && Binder.getCallingUid() != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001511 && mContext.checkCallingOrSelfPermission(
1512 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1513 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001514 throw new SecurityException("User " + UserHandle.getCallingUserId()
1515 + " trying to confirm account credentials for " + userId);
1516 }
1517
Fred Quintana56285a62010-12-02 14:20:51 -08001518 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1519 Log.v(TAG, "confirmCredentials: " + account
1520 + ", response " + response
1521 + ", expectActivityLaunch " + expectActivityLaunch
1522 + ", caller's uid " + Binder.getCallingUid()
1523 + ", pid " + Binder.getCallingPid());
1524 }
Fred Quintana382601f2010-03-25 12:25:10 -07001525 if (response == null) throw new IllegalArgumentException("response is null");
1526 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001527 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001528 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001529 long identityToken = clearCallingIdentity();
1530 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001531 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001532 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001533 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001534 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001535 }
1536 protected String toDebugString(long now) {
1537 return super.toDebugString(now) + ", confirmCredentials"
1538 + ", " + account;
1539 }
1540 }.bind();
1541 } finally {
1542 restoreCallingIdentity(identityToken);
1543 }
Fred Quintana60307342009-03-24 22:48:12 -07001544 }
1545
Fred Quintanaa698f422009-04-08 19:14:54 -07001546 public void updateCredentials(IAccountManagerResponse response, final Account account,
1547 final String authTokenType, final boolean expectActivityLaunch,
1548 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001549 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1550 Log.v(TAG, "updateCredentials: " + account
1551 + ", response " + response
1552 + ", authTokenType " + authTokenType
1553 + ", expectActivityLaunch " + expectActivityLaunch
1554 + ", caller's uid " + Binder.getCallingUid()
1555 + ", pid " + Binder.getCallingPid());
1556 }
Fred Quintana382601f2010-03-25 12:25:10 -07001557 if (response == null) throw new IllegalArgumentException("response is null");
1558 if (account == null) throw new IllegalArgumentException("account is null");
1559 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001560 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001561 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001562 long identityToken = clearCallingIdentity();
1563 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001564 new Session(accounts, response, account.type, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001565 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001566 public void run() throws RemoteException {
1567 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
1568 }
1569 protected String toDebugString(long now) {
1570 if (loginOptions != null) loginOptions.keySet();
1571 return super.toDebugString(now) + ", updateCredentials"
1572 + ", " + account
1573 + ", authTokenType " + authTokenType
1574 + ", loginOptions " + loginOptions;
1575 }
1576 }.bind();
1577 } finally {
1578 restoreCallingIdentity(identityToken);
1579 }
Fred Quintana60307342009-03-24 22:48:12 -07001580 }
1581
Fred Quintanaa698f422009-04-08 19:14:54 -07001582 public void editProperties(IAccountManagerResponse response, final String accountType,
1583 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08001584 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1585 Log.v(TAG, "editProperties: accountType " + accountType
1586 + ", response " + response
1587 + ", expectActivityLaunch " + expectActivityLaunch
1588 + ", caller's uid " + Binder.getCallingUid()
1589 + ", pid " + Binder.getCallingPid());
1590 }
Fred Quintana382601f2010-03-25 12:25:10 -07001591 if (response == null) throw new IllegalArgumentException("response is null");
1592 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001593 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001594 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001595 long identityToken = clearCallingIdentity();
1596 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001597 new Session(accounts, response, accountType, expectActivityLaunch,
Fred Quintana8570f742010-02-18 10:32:54 -08001598 true /* stripAuthTokenFromResult */) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001599 public void run() throws RemoteException {
1600 mAuthenticator.editProperties(this, mAccountType);
1601 }
1602 protected String toDebugString(long now) {
1603 return super.toDebugString(now) + ", editProperties"
1604 + ", accountType " + accountType;
1605 }
1606 }.bind();
1607 } finally {
1608 restoreCallingIdentity(identityToken);
1609 }
Fred Quintana60307342009-03-24 22:48:12 -07001610 }
1611
Fred Quintana33269202009-04-20 16:05:10 -07001612 private class GetAccountsByTypeAndFeatureSession extends Session {
1613 private final String[] mFeatures;
1614 private volatile Account[] mAccountsOfType = null;
1615 private volatile ArrayList<Account> mAccountsWithFeatures = null;
1616 private volatile int mCurrentAccount = 0;
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001617 private int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001618
Amith Yamasani04e0d262012-02-14 11:50:53 -08001619 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001620 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001621 super(accounts, response, type, false /* expectActivityLaunch */,
Fred Quintana8570f742010-02-18 10:32:54 -08001622 true /* stripAuthTokenFromResult */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001623 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07001624 mFeatures = features;
1625 }
1626
1627 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001628 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001629 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
1630 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001631 }
Fred Quintana33269202009-04-20 16:05:10 -07001632 // check whether each account matches the requested features
1633 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
1634 mCurrentAccount = 0;
1635
1636 checkAccount();
1637 }
1638
1639 public void checkAccount() {
1640 if (mCurrentAccount >= mAccountsOfType.length) {
1641 sendResult();
1642 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001643 }
Fred Quintana33269202009-04-20 16:05:10 -07001644
Fred Quintana29e94b82010-03-10 12:11:51 -08001645 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
1646 if (accountAuthenticator == null) {
1647 // It is possible that the authenticator has died, which is indicated by
1648 // mAuthenticator being set to null. If this happens then just abort.
1649 // There is no need to send back a result or error in this case since
1650 // that already happened when mAuthenticator was cleared.
1651 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1652 Log.v(TAG, "checkAccount: aborting session since we are no longer"
1653 + " connected to the authenticator, " + toDebugString());
1654 }
1655 return;
1656 }
Fred Quintana33269202009-04-20 16:05:10 -07001657 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08001658 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07001659 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001660 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07001661 }
1662 }
1663
1664 public void onResult(Bundle result) {
1665 mNumResults++;
1666 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001667 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07001668 return;
1669 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001670 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07001671 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
1672 }
1673 mCurrentAccount++;
1674 checkAccount();
1675 }
1676
1677 public void sendResult() {
1678 IAccountManagerResponse response = getResponseAndClose();
1679 if (response != null) {
1680 try {
1681 Account[] accounts = new Account[mAccountsWithFeatures.size()];
1682 for (int i = 0; i < accounts.length; i++) {
1683 accounts[i] = mAccountsWithFeatures.get(i);
1684 }
Fred Quintana56285a62010-12-02 14:20:51 -08001685 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1686 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1687 + response);
1688 }
Fred Quintana33269202009-04-20 16:05:10 -07001689 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001690 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07001691 response.onResult(result);
1692 } catch (RemoteException e) {
1693 // if the caller is dead then there is no one to care about remote exceptions
1694 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1695 Log.v(TAG, "failure while notifying response", e);
1696 }
1697 }
1698 }
1699 }
1700
1701
1702 protected String toDebugString(long now) {
1703 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
1704 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1705 }
1706 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001707
Amith Yamasani04e0d262012-02-14 11:50:53 -08001708 /**
1709 * Returns the accounts for a specific user
1710 * @hide
1711 */
1712 public Account[] getAccounts(int userId) {
1713 checkReadAccountsPermission();
1714 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001715 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001716 long identityToken = clearCallingIdentity();
1717 try {
1718 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001719 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001720 }
1721 } finally {
1722 restoreCallingIdentity(identityToken);
1723 }
1724 }
1725
Amith Yamasanif29f2362012-04-05 18:29:52 -07001726 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001727 * Returns accounts for all running users.
1728 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07001729 * @hide
1730 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001731 public AccountAndUser[] getRunningAccounts() {
1732 final int[] runningUserIds;
1733 try {
1734 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
1735 } catch (RemoteException e) {
1736 // Running in system_server; should never happen
1737 throw new RuntimeException(e);
1738 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001739 return getAccounts(runningUserIds);
1740 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07001741
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001742 /** {@hide} */
1743 public AccountAndUser[] getAllAccounts() {
1744 final List<UserInfo> users = getUserManager().getUsers();
1745 final int[] userIds = new int[users.size()];
1746 for (int i = 0; i < userIds.length; i++) {
1747 userIds[i] = users.get(i).id;
1748 }
1749 return getAccounts(userIds);
1750 }
1751
1752 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001753 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
1754 synchronized (mUsers) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001755 for (int userId : userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001756 UserAccounts userAccounts = getUserAccounts(userId);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001757 if (userAccounts == null) continue;
1758 synchronized (userAccounts.cacheLock) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001759 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
Amith Yamasani27db4682013-03-30 17:07:47 -07001760 Binder.getCallingUid(), null);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001761 for (int a = 0; a < accounts.length; a++) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001762 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07001763 }
1764 }
1765 }
1766 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001767
1768 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
1769 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07001770 }
1771
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001772 @Override
1773 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001774 return getAccountsAsUser(type, userId, null, -1);
1775 }
1776
1777 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
1778 int packageUid) {
1779 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001780 // Only allow the system process to read accounts of other users
1781 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07001782 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08001783 && mContext.checkCallingOrSelfPermission(
1784 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1785 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001786 throw new SecurityException("User " + UserHandle.getCallingUserId()
1787 + " trying to get account for " + userId);
1788 }
1789
Fred Quintana56285a62010-12-02 14:20:51 -08001790 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1791 Log.v(TAG, "getAccounts: accountType " + type
1792 + ", caller's uid " + Binder.getCallingUid()
1793 + ", pid " + Binder.getCallingPid());
1794 }
Amith Yamasani27db4682013-03-30 17:07:47 -07001795 // If the original calling app was using the framework account chooser activity, we'll
1796 // be passed in the original caller's uid here, which is what should be used for filtering.
1797 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
1798 callingUid = packageUid;
1799 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001800 checkReadAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001801 UserAccounts accounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001802 long identityToken = clearCallingIdentity();
1803 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001804 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001805 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001806 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001807 } finally {
1808 restoreCallingIdentity(identityToken);
1809 }
1810 }
1811
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001812 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001813 public boolean addSharedAccountAsUser(Account account, int userId) {
1814 userId = handleIncomingUser(userId);
1815 SQLiteDatabase db = getUserAccounts(userId).openHelper.getWritableDatabase();
1816 ContentValues values = new ContentValues();
1817 values.put(ACCOUNTS_NAME, account.name);
1818 values.put(ACCOUNTS_TYPE, account.type);
1819 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1820 new String[] {account.name, account.type});
1821 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
1822 if (accountId < 0) {
1823 Log.w(TAG, "insertAccountIntoDatabase: " + account
1824 + ", skipping the DB insert failed");
1825 return false;
1826 }
1827 return true;
1828 }
1829
1830 @Override
1831 public boolean removeSharedAccountAsUser(Account account, int userId) {
1832 userId = handleIncomingUser(userId);
1833 UserAccounts accounts = getUserAccounts(userId);
1834 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1835 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1836 new String[] {account.name, account.type});
1837 if (r > 0) {
1838 removeAccountInternal(accounts, account);
1839 }
1840 return r > 0;
1841 }
1842
1843 @Override
1844 public Account[] getSharedAccountsAsUser(int userId) {
1845 userId = handleIncomingUser(userId);
1846 UserAccounts accounts = getUserAccounts(userId);
1847 ArrayList<Account> accountList = new ArrayList<Account>();
1848 Cursor cursor = null;
1849 try {
1850 cursor = accounts.openHelper.getReadableDatabase()
1851 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
1852 null, null, null, null, null);
1853 if (cursor != null && cursor.moveToFirst()) {
1854 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
1855 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
1856 do {
1857 accountList.add(new Account(cursor.getString(nameIndex),
1858 cursor.getString(typeIndex)));
1859 } while (cursor.moveToNext());
1860 }
1861 } finally {
1862 if (cursor != null) {
1863 cursor.close();
1864 }
1865 }
1866 Account[] accountArray = new Account[accountList.size()];
1867 accountList.toArray(accountArray);
1868 return accountArray;
1869 }
1870
1871 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08001872 public Account[] getAccounts(String type) {
1873 return getAccountsAsUser(type, UserHandle.getCallingUserId());
1874 }
1875
Amith Yamasani27db4682013-03-30 17:07:47 -07001876 @Override
1877 public Account[] getAccountsForPackage(String packageName, int uid) {
1878 int callingUid = Binder.getCallingUid();
1879 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
1880 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
1881 + callingUid + " with uid=" + uid);
1882 }
1883 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
1884 }
1885
Amith Yamasani3b458ad2013-04-18 18:40:07 -07001886 @Override
1887 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
1888 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
1889 int packageUid = -1;
1890 try {
1891 packageUid = AppGlobals.getPackageManager().getPackageUid(
1892 packageName, UserHandle.getCallingUserId());
1893 } catch (RemoteException re) {
1894 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
1895 return new Account[0];
1896 }
1897 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
1898 }
1899
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001900 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07001901 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08001902 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1903 Log.v(TAG, "getAccounts: accountType " + type
1904 + ", response " + response
1905 + ", features " + stringArrayToString(features)
1906 + ", caller's uid " + Binder.getCallingUid()
1907 + ", pid " + Binder.getCallingPid());
1908 }
Fred Quintana382601f2010-03-25 12:25:10 -07001909 if (response == null) throw new IllegalArgumentException("response is null");
1910 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001911 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001912 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001913 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07001914 long identityToken = clearCallingIdentity();
1915 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001916 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001917 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001918 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001919 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001920 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001921 Bundle result = new Bundle();
1922 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
1923 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001924 return;
1925 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08001926 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
1927 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07001928 } finally {
1929 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001930 }
1931 }
1932
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001933 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07001934 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001935 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07001936 try {
1937 if (cursor.moveToNext()) {
1938 return cursor.getLong(0);
1939 }
1940 return -1;
1941 } finally {
1942 cursor.close();
1943 }
1944 }
1945
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001946 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07001947 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
1948 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
1949 new String[]{key}, null, null, null);
1950 try {
1951 if (cursor.moveToNext()) {
1952 return cursor.getLong(0);
1953 }
1954 return -1;
1955 } finally {
1956 cursor.close();
1957 }
1958 }
1959
Fred Quintanaa698f422009-04-08 19:14:54 -07001960 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07001961 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07001962 IAccountManagerResponse mResponse;
1963 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001964 final boolean mExpectActivityLaunch;
1965 final long mCreationTime;
1966
Fred Quintana33269202009-04-20 16:05:10 -07001967 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07001968 private int mNumRequestContinued = 0;
1969 private int mNumErrors = 0;
1970
Fred Quintana60307342009-03-24 22:48:12 -07001971 IAccountAuthenticator mAuthenticator = null;
1972
Fred Quintana8570f742010-02-18 10:32:54 -08001973 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001974 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001975
Amith Yamasani04e0d262012-02-14 11:50:53 -08001976 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Fred Quintana8570f742010-02-18 10:32:54 -08001977 boolean expectActivityLaunch, boolean stripAuthTokenFromResult) {
Fred Quintana60307342009-03-24 22:48:12 -07001978 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001979 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07001980 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001981 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08001982 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07001983 mResponse = response;
1984 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07001985 mExpectActivityLaunch = expectActivityLaunch;
1986 mCreationTime = SystemClock.elapsedRealtime();
1987 synchronized (mSessions) {
1988 mSessions.put(toString(), this);
1989 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001990 if (response != null) {
1991 try {
1992 response.asBinder().linkToDeath(this, 0 /* flags */);
1993 } catch (RemoteException e) {
1994 mResponse = null;
1995 binderDied();
1996 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001997 }
Fred Quintana60307342009-03-24 22:48:12 -07001998 }
1999
Fred Quintanaa698f422009-04-08 19:14:54 -07002000 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002001 if (mResponse == null) {
2002 // this session has already been closed
2003 return null;
2004 }
Fred Quintana60307342009-03-24 22:48:12 -07002005 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002006 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002007 return response;
2008 }
2009
Fred Quintanaa698f422009-04-08 19:14:54 -07002010 private void close() {
2011 synchronized (mSessions) {
2012 if (mSessions.remove(toString()) == null) {
2013 // the session was already closed, so bail out now
2014 return;
2015 }
2016 }
2017 if (mResponse != null) {
2018 // stop listening for response deaths
2019 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2020
2021 // clear this so that we don't accidentally send any further results
2022 mResponse = null;
2023 }
2024 cancelTimeout();
2025 unbind();
2026 }
2027
2028 public void binderDied() {
2029 mResponse = null;
2030 close();
2031 }
2032
2033 protected String toDebugString() {
2034 return toDebugString(SystemClock.elapsedRealtime());
2035 }
2036
2037 protected String toDebugString(long now) {
2038 return "Session: expectLaunch " + mExpectActivityLaunch
2039 + ", connected " + (mAuthenticator != null)
2040 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2041 + "/" + mNumErrors + ")"
2042 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2043 }
2044
Fred Quintana60307342009-03-24 22:48:12 -07002045 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002046 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2047 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2048 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002049 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002050 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002051 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002052 }
2053 }
2054
2055 private void unbind() {
2056 if (mAuthenticator != null) {
2057 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002058 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002059 }
2060 }
2061
2062 public void scheduleTimeout() {
2063 mMessageHandler.sendMessageDelayed(
2064 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2065 }
2066
2067 public void cancelTimeout() {
2068 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2069 }
2070
Fred Quintanab839afc2009-10-14 15:57:28 -07002071 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002072 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002073 try {
2074 run();
2075 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002076 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002077 "remote exception");
2078 }
Fred Quintana60307342009-03-24 22:48:12 -07002079 }
2080
Fred Quintanab839afc2009-10-14 15:57:28 -07002081 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002082 mAuthenticator = null;
2083 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002084 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002085 try {
2086 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2087 "disconnected");
2088 } catch (RemoteException e) {
2089 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2090 Log.v(TAG, "Session.onServiceDisconnected: "
2091 + "caught RemoteException while responding", e);
2092 }
2093 }
Fred Quintana60307342009-03-24 22:48:12 -07002094 }
2095 }
2096
Fred Quintanab839afc2009-10-14 15:57:28 -07002097 public abstract void run() throws RemoteException;
2098
Fred Quintana60307342009-03-24 22:48:12 -07002099 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002100 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002101 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002102 try {
2103 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2104 "timeout");
2105 } catch (RemoteException e) {
2106 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2107 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2108 e);
2109 }
2110 }
Fred Quintana60307342009-03-24 22:48:12 -07002111 }
2112 }
2113
Fred Quintanaa698f422009-04-08 19:14:54 -07002114 public void onResult(Bundle result) {
2115 mNumResults++;
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002116 if (result != null && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
2117 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2118 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002119 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2120 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002121 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2122 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002123 }
Fred Quintana60307342009-03-24 22:48:12 -07002124 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002125 IAccountManagerResponse response;
2126 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002127 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002128 response = mResponse;
2129 } else {
2130 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002131 }
Fred Quintana60307342009-03-24 22:48:12 -07002132 if (response != null) {
2133 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002134 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002135 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2136 Log.v(TAG, getClass().getSimpleName()
2137 + " calling onError() on response " + response);
2138 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002139 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002140 "null bundle returned");
2141 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002142 if (mStripAuthTokenFromResult) {
2143 result.remove(AccountManager.KEY_AUTHTOKEN);
2144 }
Fred Quintana56285a62010-12-02 14:20:51 -08002145 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2146 Log.v(TAG, getClass().getSimpleName()
2147 + " calling onResult() on response " + response);
2148 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002149 response.onResult(result);
2150 }
Fred Quintana60307342009-03-24 22:48:12 -07002151 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002152 // if the caller is dead then there is no one to care about remote exceptions
2153 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2154 Log.v(TAG, "failure while notifying response", e);
2155 }
Fred Quintana60307342009-03-24 22:48:12 -07002156 }
2157 }
2158 }
Fred Quintana60307342009-03-24 22:48:12 -07002159
Fred Quintanaa698f422009-04-08 19:14:54 -07002160 public void onRequestContinued() {
2161 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002162 }
2163
2164 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002165 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07002166 IAccountManagerResponse response = getResponseAndClose();
2167 if (response != null) {
2168 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002169 Log.v(TAG, getClass().getSimpleName()
2170 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07002171 }
2172 try {
2173 response.onError(errorCode, errorMessage);
2174 } catch (RemoteException e) {
2175 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2176 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
2177 }
2178 }
2179 } else {
2180 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2181 Log.v(TAG, "Session.onError: already closed");
2182 }
Fred Quintana60307342009-03-24 22:48:12 -07002183 }
2184 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002185
2186 /**
2187 * find the component name for the authenticator and initiate a bind
2188 * if no authenticator or the bind fails then return false, otherwise return true
2189 */
2190 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002191 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
2192 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2193 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07002194 if (authenticatorInfo == null) {
2195 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2196 Log.v(TAG, "there is no authenticator for " + authenticatorType
2197 + ", bailing out");
2198 }
2199 return false;
2200 }
2201
2202 Intent intent = new Intent();
2203 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
2204 intent.setComponent(authenticatorInfo.componentName);
2205 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2206 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
2207 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08002208 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
2209 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07002210 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2211 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
2212 }
2213 return false;
2214 }
2215
2216
2217 return true;
2218 }
Fred Quintana60307342009-03-24 22:48:12 -07002219 }
2220
2221 private class MessageHandler extends Handler {
2222 MessageHandler(Looper looper) {
2223 super(looper);
2224 }
Costin Manolache3348f142009-09-29 18:58:36 -07002225
Fred Quintana60307342009-03-24 22:48:12 -07002226 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07002227 switch (msg.what) {
2228 case MESSAGE_TIMED_OUT:
2229 Session session = (Session)msg.obj;
2230 session.onTimedOut();
2231 break;
2232
Amith Yamasani5be347b2013-03-31 17:44:31 -07002233 case MESSAGE_COPY_SHARED_ACCOUNT:
2234 copyAccountToUser((Account) msg.obj, msg.arg1, msg.arg2);
2235 break;
2236
Fred Quintana60307342009-03-24 22:48:12 -07002237 default:
2238 throw new IllegalStateException("unhandled message: " + msg.what);
2239 }
2240 }
2241 }
2242
Amith Yamasani04e0d262012-02-14 11:50:53 -08002243 private static String getDatabaseName(int userId) {
2244 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07002245 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002246 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07002247 // Migrate old file, if it exists, to the new location.
2248 // Make sure the new file doesn't already exist. A dummy file could have been
2249 // accidentally created in the old location, causing the new one to become corrupted
2250 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08002251 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07002252 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07002253 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07002254 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07002255 if (!userDir.exists()) {
2256 if (!userDir.mkdirs()) {
2257 throw new IllegalStateException("User dir cannot be created: " + userDir);
2258 }
2259 }
2260 if (!oldFile.renameTo(databaseFile)) {
2261 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
2262 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002263 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002264 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002265 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08002266 }
2267
Amith Yamasani04e0d262012-02-14 11:50:53 -08002268 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002269
Amith Yamasani04e0d262012-02-14 11:50:53 -08002270 public DatabaseHelper(Context context, int userId) {
2271 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07002272 }
2273
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002274 /**
2275 * This call needs to be made while the mCacheLock is held. The way to
2276 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
2277 * @param db The database.
2278 */
Fred Quintana60307342009-03-24 22:48:12 -07002279 @Override
2280 public void onCreate(SQLiteDatabase db) {
2281 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
2282 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2283 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2284 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2285 + ACCOUNTS_PASSWORD + " TEXT, "
2286 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2287
2288 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
2289 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2290 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2291 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
2292 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
2293 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
2294
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002295 createGrantsTable(db);
2296
Fred Quintana60307342009-03-24 22:48:12 -07002297 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
2298 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2299 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
2300 + EXTRAS_KEY + " TEXT NOT NULL, "
2301 + EXTRAS_VALUE + " TEXT, "
2302 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
2303
2304 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
2305 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
2306 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07002307
Amith Yamasani67df64b2012-12-14 12:09:36 -08002308 createSharedAccountsTable(db);
2309
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002310 createAccountsDeletionTrigger(db);
2311 }
2312
Amith Yamasani67df64b2012-12-14 12:09:36 -08002313 private void createSharedAccountsTable(SQLiteDatabase db) {
2314 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
2315 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
2316 + ACCOUNTS_NAME + " TEXT NOT NULL, "
2317 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
2318 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
2319 }
2320
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002321 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002322 db.execSQL(""
2323 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
2324 + " BEGIN"
2325 + " DELETE FROM " + TABLE_AUTHTOKENS
2326 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
2327 + " DELETE FROM " + TABLE_EXTRAS
2328 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002329 + " DELETE FROM " + TABLE_GRANTS
2330 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07002331 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07002332 }
2333
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002334 private void createGrantsTable(SQLiteDatabase db) {
2335 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
2336 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
2337 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
2338 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
2339 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
2340 + "," + GRANTS_GRANTEE_UID + "))");
2341 }
2342
Fred Quintana60307342009-03-24 22:48:12 -07002343 @Override
2344 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002345 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07002346
Fred Quintanaa698f422009-04-08 19:14:54 -07002347 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002348 // no longer need to do anything since the work is done
2349 // when upgrading from version 2
2350 oldVersion++;
2351 }
2352
2353 if (oldVersion == 2) {
2354 createGrantsTable(db);
2355 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
2356 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07002357 oldVersion++;
2358 }
Costin Manolache3348f142009-09-29 18:58:36 -07002359
2360 if (oldVersion == 3) {
2361 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
2362 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
2363 oldVersion++;
2364 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002365
2366 if (oldVersion == 4) {
2367 createSharedAccountsTable(db);
2368 oldVersion++;
2369 }
2370
2371 if (oldVersion != newVersion) {
2372 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
2373 }
Fred Quintana60307342009-03-24 22:48:12 -07002374 }
2375
2376 @Override
2377 public void onOpen(SQLiteDatabase db) {
2378 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
2379 }
2380 }
2381
Fred Quintana60307342009-03-24 22:48:12 -07002382 public IBinder onBind(Intent intent) {
2383 return asBinder();
2384 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002385
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002386 /**
2387 * Searches array of arguments for the specified string
2388 * @param args array of argument strings
2389 * @param value value to search for
2390 * @return true if the value is contained in the array
2391 */
2392 private static boolean scanArgs(String[] args, String value) {
2393 if (args != null) {
2394 for (String arg : args) {
2395 if (value.equals(arg)) {
2396 return true;
2397 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002398 }
2399 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002400 return false;
2401 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002402
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002403 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002404 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07002405 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2406 != PackageManager.PERMISSION_GRANTED) {
2407 fout.println("Permission Denial: can't dump AccountsManager from from pid="
2408 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
2409 + " without permission " + android.Manifest.permission.DUMP);
2410 return;
2411 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002412 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002413 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07002414
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002415 final List<UserInfo> users = getUserManager().getUsers();
2416 for (UserInfo user : users) {
2417 ipw.println("User " + user + ":");
2418 ipw.increaseIndent();
2419 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
2420 ipw.println();
2421 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002422 }
2423 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002424
Amith Yamasani04e0d262012-02-14 11:50:53 -08002425 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
2426 String[] args, boolean isCheckinRequest) {
2427 synchronized (userAccounts.cacheLock) {
2428 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002429
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002430 if (isCheckinRequest) {
2431 // This is a checkin request. *Only* upload the account types and the count of each.
2432 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
2433 null, null, ACCOUNTS_TYPE, null, null);
2434 try {
2435 while (cursor.moveToNext()) {
2436 // print type,count
2437 fout.println(cursor.getString(0) + "," + cursor.getString(1));
2438 }
2439 } finally {
2440 if (cursor != null) {
2441 cursor.close();
2442 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002443 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002444 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002445 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07002446 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002447 fout.println("Accounts: " + accounts.length);
2448 for (Account account : accounts) {
2449 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002450 }
Fred Quintana307da1a2010-01-21 14:24:20 -08002451
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002452 fout.println();
2453 synchronized (mSessions) {
2454 final long now = SystemClock.elapsedRealtime();
2455 fout.println("Active Sessions: " + mSessions.size());
2456 for (Session session : mSessions.values()) {
2457 fout.println(" " + session.toDebugString(now));
2458 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002459 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002460
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002461 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002462 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002463 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07002464 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002465 }
2466
Amith Yamasani04e0d262012-02-14 11:50:53 -08002467 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07002468 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002469 long identityToken = clearCallingIdentity();
2470 try {
2471 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2472 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
2473 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002474
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002475 if (intent.getComponent() != null &&
2476 GrantCredentialsPermissionActivity.class.getName().equals(
2477 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002478 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002479 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002480 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07002481 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002482 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
2483 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002484 UserHandle user = new UserHandle(userId);
Fred Quintana33f889a2009-09-14 17:31:26 -07002485 final String notificationTitleFormat =
2486 mContext.getText(R.string.notification_title).toString();
2487 n.setLatestEventInfo(mContext,
2488 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07002489 message, PendingIntent.getActivityAsUser(
2490 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002491 null, user));
2492 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002493 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002494 } finally {
2495 restoreCallingIdentity(identityToken);
2496 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002497 }
2498
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002499 protected void installNotification(final int notificationId, final Notification n,
2500 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08002501 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002502 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08002503 }
2504
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002505 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002506 long identityToken = clearCallingIdentity();
2507 try {
2508 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002509 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002510 } finally {
2511 restoreCallingIdentity(identityToken);
2512 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002513 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002514
Fred Quintanab38eb142010-02-24 13:40:54 -08002515 /** Succeeds if any of the specified permissions are granted. */
2516 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002517 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08002518
2519 for (String perm : permissions) {
2520 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
2521 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08002522 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08002523 }
2524 return;
2525 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002526 }
Fred Quintanab38eb142010-02-24 13:40:54 -08002527
2528 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08002529 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08002530 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002531 }
2532
Amith Yamasani67df64b2012-12-14 12:09:36 -08002533 private int handleIncomingUser(int userId) {
2534 try {
2535 return ActivityManagerNative.getDefault().handleIncomingUser(
2536 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
2537 } catch (RemoteException re) {
2538 // Shouldn't happen, local.
2539 }
2540 return userId;
2541 }
2542
Christopher Tateccbf84f2013-05-08 15:25:41 -07002543 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002544 final int callingUserId = UserHandle.getUserId(callingUid);
2545
2546 final PackageManager userPackageManager;
2547 try {
2548 userPackageManager = mContext.createPackageContextAsUser(
2549 "android", 0, new UserHandle(callingUserId)).getPackageManager();
2550 } catch (NameNotFoundException e) {
2551 return false;
2552 }
2553
2554 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07002555 for (String name : packages) {
2556 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002557 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08002558 if (packageInfo != null
Christopher Tateccbf84f2013-05-08 15:25:41 -07002559 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07002560 return true;
2561 }
2562 } catch (PackageManager.NameNotFoundException e) {
2563 return false;
2564 }
2565 }
2566 return false;
2567 }
2568
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002569 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07002570 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07002571 final boolean fromAuthenticator = account != null
2572 && hasAuthenticatorUid(account.type, callerUid);
2573 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08002574 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002575 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2576 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08002577 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002578 + ": is authenticator? " + fromAuthenticator
2579 + ", has explicit permission? " + hasExplicitGrants);
2580 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07002581 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002582 }
2583
Fred Quintana1a231912009-10-15 11:31:30 -07002584 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002585 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002586 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002587 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002588 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002589 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08002590 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002591 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002592 }
2593 }
2594 return false;
2595 }
2596
Amith Yamasani04e0d262012-02-14 11:50:53 -08002597 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
2598 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002599 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002600 return true;
2601 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002602 UserAccounts accounts = getUserAccountsForCaller();
2603 synchronized (accounts.cacheLock) {
2604 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
2605 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002606 account.name, account.type};
2607 final boolean permissionGranted =
2608 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
2609 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
2610 // TODO: Skip this check when running automated tests. Replace this
2611 // with a more general solution.
2612 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08002613 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002614 + " but ignoring since device is in test harness.");
2615 return true;
2616 }
2617 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002618 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002619 }
2620
2621 private void checkCallingUidAgainstAuthenticator(Account account) {
2622 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07002623 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002624 String msg = "caller uid " + uid + " is different than the authenticator's uid";
2625 Log.w(TAG, msg);
2626 throw new SecurityException(msg);
2627 }
2628 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2629 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
2630 }
2631 }
2632
2633 private void checkAuthenticateAccountsPermission(Account account) {
2634 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
2635 checkCallingUidAgainstAuthenticator(account);
2636 }
2637
2638 private void checkReadAccountsPermission() {
2639 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
2640 }
2641
2642 private void checkManageAccountsPermission() {
2643 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
2644 }
2645
Fred Quintanab38eb142010-02-24 13:40:54 -08002646 private void checkManageAccountsOrUseCredentialsPermissions() {
2647 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
2648 Manifest.permission.USE_CREDENTIALS);
2649 }
2650
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002651 private boolean canUserModifyAccounts(int callingUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002652 if (callingUid != Process.myUid()) {
2653 if (getUserManager().getUserRestrictions(
2654 new UserHandle(UserHandle.getUserId(callingUid)))
2655 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08002656 return false;
2657 }
2658 }
2659 return true;
2660 }
2661
Fred Quintanad9640ec2012-05-23 12:37:00 -07002662 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
2663 throws RemoteException {
2664 final int callingUid = getCallingUid();
2665
Amith Yamasani27db4682013-03-30 17:07:47 -07002666 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002667 throw new SecurityException();
2668 }
2669
2670 if (value) {
2671 grantAppPermission(account, authTokenType, uid);
2672 } else {
2673 revokeAppPermission(account, authTokenType, uid);
2674 }
2675 }
2676
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002677 /**
2678 * Allow callers with the given uid permission to get credentials for account/authTokenType.
2679 * <p>
2680 * Although this is public it can only be accessed via the AccountManagerService object
2681 * which is in the system. This means we don't need to protect it with permissions.
2682 * @hide
2683 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002684 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002685 if (account == null || authTokenType == null) {
2686 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002687 return;
2688 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002689 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002690 synchronized (accounts.cacheLock) {
2691 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002692 db.beginTransaction();
2693 try {
2694 long accountId = getAccountIdLocked(db, account);
2695 if (accountId >= 0) {
2696 ContentValues values = new ContentValues();
2697 values.put(GRANTS_ACCOUNTS_ID, accountId);
2698 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
2699 values.put(GRANTS_GRANTEE_UID, uid);
2700 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
2701 db.setTransactionSuccessful();
2702 }
2703 } finally {
2704 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002705 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002706 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2707 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002708 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002709 }
2710
2711 /**
2712 * Don't allow callers with the given uid permission to get credentials for
2713 * account/authTokenType.
2714 * <p>
2715 * Although this is public it can only be accessed via the AccountManagerService object
2716 * which is in the system. This means we don't need to protect it with permissions.
2717 * @hide
2718 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07002719 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07002720 if (account == null || authTokenType == null) {
2721 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07002722 return;
2723 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002724 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002725 synchronized (accounts.cacheLock) {
2726 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002727 db.beginTransaction();
2728 try {
2729 long accountId = getAccountIdLocked(db, account);
2730 if (accountId >= 0) {
2731 db.delete(TABLE_GRANTS,
2732 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
2733 + GRANTS_GRANTEE_UID + "=?",
2734 new String[]{String.valueOf(accountId), authTokenType,
2735 String.valueOf(uid)});
2736 db.setTransactionSuccessful();
2737 }
2738 } finally {
2739 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002740 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002741 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
2742 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002743 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002744 }
Fred Quintana56285a62010-12-02 14:20:51 -08002745
2746 static final private String stringArrayToString(String[] value) {
2747 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
2748 }
2749
Amith Yamasani04e0d262012-02-14 11:50:53 -08002750 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
2751 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002752 if (oldAccountsForType != null) {
2753 ArrayList<Account> newAccountsList = new ArrayList<Account>();
2754 for (Account curAccount : oldAccountsForType) {
2755 if (!curAccount.equals(account)) {
2756 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002757 }
2758 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002759 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002760 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002761 } else {
2762 Account[] newAccountsForType = new Account[newAccountsList.size()];
2763 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002764 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002765 }
Fred Quintana56285a62010-12-02 14:20:51 -08002766 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002767 accounts.userDataCache.remove(account);
2768 accounts.authTokenCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002769 }
2770
2771 /**
2772 * This assumes that the caller has already checked that the account is not already present.
2773 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08002774 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
2775 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002776 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
2777 Account[] newAccountsForType = new Account[oldLength + 1];
2778 if (accountsForType != null) {
2779 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08002780 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002781 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002782 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08002783 }
2784
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002785 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07002786 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002787 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07002788 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002789 return unfiltered;
2790 }
2791 if (mUserManager.getUserInfo(userAccounts.userId).isRestricted()) {
2792 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002793 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002794 // otherwise return non-shared accounts only.
2795 // This might be a temporary way to specify a whitelist
2796 String whiteList = mContext.getResources().getString(
2797 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
2798 for (String packageName : packages) {
2799 if (whiteList.contains(";" + packageName + ";")) {
2800 return unfiltered;
2801 }
2802 }
2803 ArrayList<Account> allowed = new ArrayList<Account>();
2804 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
2805 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002806 String requiredAccountType = "";
2807 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07002808 // If there's an explicit callingPackage specified, check if that package
2809 // opted in to see restricted accounts.
2810 if (callingPackage != null) {
2811 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002812 if (pi != null && pi.restrictedAccountType != null) {
2813 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07002814 }
2815 } else {
2816 // Otherwise check if the callingUid has a package that has opted in
2817 for (String packageName : packages) {
2818 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
2819 if (pi != null && pi.restrictedAccountType != null) {
2820 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07002821 break;
2822 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002823 }
2824 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002825 } catch (NameNotFoundException nnfe) {
2826 }
2827 for (Account account : unfiltered) {
2828 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002829 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07002830 } else {
2831 boolean found = false;
2832 for (Account shared : sharedAccounts) {
2833 if (shared.equals(account)) {
2834 found = true;
2835 break;
2836 }
2837 }
2838 if (!found) {
2839 allowed.add(account);
2840 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002841 }
2842 }
2843 Account[] filtered = new Account[allowed.size()];
2844 allowed.toArray(filtered);
2845 return filtered;
2846 } else {
2847 return unfiltered;
2848 }
2849 }
2850
Amith Yamasani27db4682013-03-30 17:07:47 -07002851 /*
2852 * packageName can be null. If not null, it should be used to filter out restricted accounts
2853 * that the package is not allowed to access.
2854 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002855 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07002856 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002857 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002858 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002859 if (accounts == null) {
2860 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08002861 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002862 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07002863 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002864 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002865 } else {
2866 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002867 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002868 totalLength += accounts.length;
2869 }
2870 if (totalLength == 0) {
2871 return EMPTY_ACCOUNT_ARRAY;
2872 }
2873 Account[] accounts = new Account[totalLength];
2874 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002875 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002876 System.arraycopy(accountsOfType, 0, accounts, totalLength,
2877 accountsOfType.length);
2878 totalLength += accountsOfType.length;
2879 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002880 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08002881 }
2882 }
2883
Amith Yamasani04e0d262012-02-14 11:50:53 -08002884 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2885 Account account, String key, String value) {
2886 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002887 if (userDataForAccount == null) {
2888 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002889 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002890 }
2891 if (value == null) {
2892 userDataForAccount.remove(key);
2893 } else {
2894 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002895 }
2896 }
2897
Amith Yamasani04e0d262012-02-14 11:50:53 -08002898 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
2899 Account account, String key, String value) {
2900 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002901 if (authTokensForAccount == null) {
2902 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002903 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002904 }
2905 if (value == null) {
2906 authTokensForAccount.remove(key);
2907 } else {
2908 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08002909 }
2910 }
2911
Amith Yamasani04e0d262012-02-14 11:50:53 -08002912 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
2913 String authTokenType) {
2914 synchronized (accounts.cacheLock) {
2915 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002916 if (authTokensForAccount == null) {
2917 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002918 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002919 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002920 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002921 }
2922 return authTokensForAccount.get(authTokenType);
2923 }
2924 }
2925
Amith Yamasani04e0d262012-02-14 11:50:53 -08002926 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
2927 synchronized (accounts.cacheLock) {
2928 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08002929 if (userDataForAccount == null) {
2930 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08002931 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002932 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002933 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08002934 }
2935 return userDataForAccount.get(key);
2936 }
2937 }
2938
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002939 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
2940 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002941 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002942 Cursor cursor = db.query(TABLE_EXTRAS,
2943 COLUMNS_EXTRAS_KEY_AND_VALUE,
2944 SELECTION_USERDATA_BY_ACCOUNT,
2945 new String[]{account.name, account.type},
2946 null, null, null);
2947 try {
2948 while (cursor.moveToNext()) {
2949 final String tmpkey = cursor.getString(0);
2950 final String value = cursor.getString(1);
2951 userDataForAccount.put(tmpkey, value);
2952 }
2953 } finally {
2954 cursor.close();
2955 }
2956 return userDataForAccount;
2957 }
2958
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002959 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
2960 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08002961 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08002962 Cursor cursor = db.query(TABLE_AUTHTOKENS,
2963 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
2964 SELECTION_AUTHTOKENS_BY_ACCOUNT,
2965 new String[]{account.name, account.type},
2966 null, null, null);
2967 try {
2968 while (cursor.moveToNext()) {
2969 final String type = cursor.getString(0);
2970 final String authToken = cursor.getString(1);
2971 authTokensForAccount.put(type, authToken);
2972 }
2973 } finally {
2974 cursor.close();
2975 }
2976 return authTokensForAccount;
2977 }
Fred Quintana60307342009-03-24 22:48:12 -07002978}