blob: 21f96c9dbdbdb9457abb817a7fdfb563a2a89815 [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;
Carlos Valdivia91979be2015-05-22 14:11:35 -070020import android.accounts.AbstractAccountAuthenticator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
25import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070026import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.accounts.GrantCredentialsPermissionActivity;
28import android.accounts.IAccountAuthenticator;
29import android.accounts.IAccountAuthenticatorResponse;
30import android.accounts.IAccountManager;
31import android.accounts.IAccountManagerResponse;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080032import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070033import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070034import android.app.AppGlobals;
Doug Zongker885cfc232009-10-21 16:52:44 -070035import android.app.Notification;
36import android.app.NotificationManager;
37import android.app.PendingIntent;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010038import android.app.admin.DevicePolicyManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070039import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070040import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070041import android.content.ContentValues;
42import android.content.Context;
43import android.content.Intent;
44import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070045import android.content.ServiceConnection;
Doug Zongker885cfc232009-10-21 16:52:44 -070046import android.content.pm.ApplicationInfo;
47import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070048import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070049import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070050import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070051import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070052import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070053import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070054import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070055import android.database.Cursor;
56import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070057import android.database.sqlite.SQLiteDatabase;
58import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070059import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070060import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070061import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080062import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070063import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070064import android.os.IBinder;
65import android.os.Looper;
66import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070067import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070068import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.os.RemoteException;
70import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070071import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070072import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070073import android.text.TextUtils;
74import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070075import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070076import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080077import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070078
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070079import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080080import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080081import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070082import com.android.server.FgThread;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070083import com.google.android.collect.Lists;
84import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070085
Oscar Montemayora8529f62009-11-18 10:14:20 -080086import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070087import java.io.FileDescriptor;
88import java.io.PrintWriter;
Carlos Valdivia91979be2015-05-22 14:11:35 -070089import java.lang.ref.WeakReference;
Carlos Valdiviadcddc472015-06-11 20:04:04 +000090import java.nio.ByteBuffer;
91import java.nio.charset.Charset;
Carlos Valdivia91979be2015-05-22 14:11:35 -070092import java.security.MessageDigest;
93import java.security.NoSuchAlgorithmException;
Carlos Valdiviadcddc472015-06-11 20:04:04 +000094import java.sql.Timestamp;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070095import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -070096import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080097import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -070098import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070099import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700100import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700101import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800102import java.util.LinkedHashMap;
Carlos Valdiviadcddc472015-06-11 20:04:04 +0000103import java.util.LinkedList;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700104import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800105import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700106import java.util.concurrent.atomic.AtomicInteger;
107import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700108
Fred Quintana60307342009-03-24 22:48:12 -0700109/**
110 * A system service that provides account, password, and authtoken management for all
111 * accounts on the device. Some of these calls are implemented with the help of the corresponding
112 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
113 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700114 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700115 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700116 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700117public class AccountManagerService
118 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800119 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700120 private static final String TAG = "AccountManagerService";
121
122 private static final int TIMEOUT_DELAY_MS = 1000 * 60;
123 private static final String DATABASE_NAME = "accounts.db";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700124 private static final int DATABASE_VERSION = 8;
125
126 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700127
128 private final Context mContext;
129
Fred Quintana56285a62010-12-02 14:20:51 -0800130 private final PackageManager mPackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700131 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800132
Fred Quintana60307342009-03-24 22:48:12 -0700133 private final MessageHandler mMessageHandler;
134
135 // Messages that can be sent on mHandler
136 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700137 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700138
Fred Quintana56285a62010-12-02 14:20:51 -0800139 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700140
141 private static final String TABLE_ACCOUNTS = "accounts";
142 private static final String ACCOUNTS_ID = "_id";
143 private static final String ACCOUNTS_NAME = "name";
144 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700145 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700146 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700147 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800148 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
149 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700150
151 private static final String TABLE_AUTHTOKENS = "authtokens";
152 private static final String AUTHTOKENS_ID = "_id";
153 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
154 private static final String AUTHTOKENS_TYPE = "type";
155 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
156
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700157 private static final String TABLE_GRANTS = "grants";
158 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
159 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
160 private static final String GRANTS_GRANTEE_UID = "uid";
161
Fred Quintana60307342009-03-24 22:48:12 -0700162 private static final String TABLE_EXTRAS = "extras";
163 private static final String EXTRAS_ID = "_id";
164 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
165 private static final String EXTRAS_KEY = "key";
166 private static final String EXTRAS_VALUE = "value";
167
168 private static final String TABLE_META = "meta";
169 private static final String META_KEY = "key";
170 private static final String META_VALUE = "value";
171
Amith Yamasani67df64b2012-12-14 12:09:36 -0800172 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
173
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700174 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
175 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700176 private static final Intent ACCOUNTS_CHANGED_INTENT;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700177 static {
178 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
179 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
180 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700181
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700182 private static final String COUNT_OF_MATCHING_GRANTS = ""
183 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
184 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
185 + " AND " + GRANTS_GRANTEE_UID + "=?"
186 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
187 + " AND " + ACCOUNTS_NAME + "=?"
188 + " AND " + ACCOUNTS_TYPE + "=?";
189
Fred Quintana56285a62010-12-02 14:20:51 -0800190 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
191 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700192
Fred Quintana56285a62010-12-02 14:20:51 -0800193 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
194 AUTHTOKENS_AUTHTOKEN};
195
196 private static final String SELECTION_USERDATA_BY_ACCOUNT =
197 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
198 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
199
Fred Quintanaa698f422009-04-08 19:14:54 -0700200 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700201 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
202
Amith Yamasani04e0d262012-02-14 11:50:53 -0800203 static class UserAccounts {
204 private final int userId;
205 private final DatabaseHelper openHelper;
206 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
207 credentialsPermissionNotificationIds =
208 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
209 private final HashMap<Account, Integer> signinRequiredNotificationIds =
210 new HashMap<Account, Integer>();
211 private final Object cacheLock = new Object();
212 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700213 private final HashMap<String, Account[]> accountCache =
214 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800215 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800216 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800217 new HashMap<Account, HashMap<String, String>>();
218 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800219 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800220 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700221
222 /** protected by the {@link #cacheLock} */
223 private final HashMap<Account, WeakReference<TokenCache>> accountTokenCaches = new HashMap<>();
224
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700225 /**
226 * protected by the {@link #cacheLock}
227 *
228 * Caches the previous names associated with an account. Previous names
229 * should be cached because we expect that when an Account is renamed,
230 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
231 * want to know if the accounts they care about have been renamed.
232 *
233 * The previous names are wrapped in an {@link AtomicReference} so that
234 * we can distinguish between those accounts with no previous names and
235 * those whose previous names haven't been cached (yet).
236 */
237 private final HashMap<Account, AtomicReference<String>> previousNameCache =
238 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800239
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700240 private int debugDbInsertionPoint = -1;
241 private SQLiteStatement statementForLogging;
242
Amith Yamasani04e0d262012-02-14 11:50:53 -0800243 UserAccounts(Context context, int userId) {
244 this.userId = userId;
245 synchronized (cacheLock) {
246 openHelper = new DatabaseHelper(context, userId);
247 }
248 }
249 }
250
251 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
252
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700253 private static AtomicReference<AccountManagerService> sThis =
254 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700255 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700256
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700257 /**
258 * This should only be called by system code. One should only call this after the service
259 * has started.
260 * @return a reference to the AccountManagerService instance
261 * @hide
262 */
263 public static AccountManagerService getSingleton() {
264 return sThis.get();
265 }
Fred Quintana60307342009-03-24 22:48:12 -0700266
Fred Quintana56285a62010-12-02 14:20:51 -0800267 public AccountManagerService(Context context) {
268 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700269 }
270
Fred Quintana56285a62010-12-02 14:20:51 -0800271 public AccountManagerService(Context context, PackageManager packageManager,
272 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700273 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800274 mPackageManager = packageManager;
Fred Quintana60307342009-03-24 22:48:12 -0700275
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700276 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700277
Fred Quintana56285a62010-12-02 14:20:51 -0800278 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800279 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700280
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700281 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800282
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800283 IntentFilter intentFilter = new IntentFilter();
284 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
285 intentFilter.addDataScheme("package");
286 mContext.registerReceiver(new BroadcastReceiver() {
287 @Override
288 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700289 // Don't delete accounts when updating a authenticator's
290 // package.
291 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
292 purgeOldGrantsAll();
293 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800294 }
295 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800296
Amith Yamasani13593602012-03-22 16:16:17 -0700297 IntentFilter userFilter = new IntentFilter();
298 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800299 userFilter.addAction(Intent.ACTION_USER_STARTED);
300 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700301 @Override
302 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800303 String action = intent.getAction();
304 if (Intent.ACTION_USER_REMOVED.equals(action)) {
305 onUserRemoved(intent);
306 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
307 onUserStarted(intent);
308 }
Amith Yamasani13593602012-03-22 16:16:17 -0700309 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800310 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800311 }
312
Dianne Hackborn164371f2013-10-01 19:10:13 -0700313 @Override
314 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
315 throws RemoteException {
316 try {
317 return super.onTransact(code, data, reply, flags);
318 } catch (RuntimeException e) {
319 // The account manager only throws security exceptions, so let's
320 // log all others.
321 if (!(e instanceof SecurityException)) {
322 Slog.wtf(TAG, "Account Manager Crash", e);
323 }
324 throw e;
325 }
326 }
327
Kenny Root26ff6622012-07-30 12:58:03 -0700328 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700329 }
330
Amith Yamasani258848d2012-08-10 17:06:33 -0700331 private UserManager getUserManager() {
332 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700333 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700334 }
335 return mUserManager;
336 }
337
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700338 /* Caller should lock mUsers */
339 private UserAccounts initUserLocked(int userId) {
340 UserAccounts accounts = mUsers.get(userId);
341 if (accounts == null) {
342 accounts = new UserAccounts(mContext, userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700343 initializeDebugDbSizeAndCompileSqlStatementForLogging(
344 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700345 mUsers.append(userId, accounts);
346 purgeOldGrants(accounts);
347 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800348 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700349 return accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800350 }
351
352 private void purgeOldGrantsAll() {
353 synchronized (mUsers) {
354 for (int i = 0; i < mUsers.size(); i++) {
355 purgeOldGrants(mUsers.valueAt(i));
356 }
357 }
358 }
359
360 private void purgeOldGrants(UserAccounts accounts) {
361 synchronized (accounts.cacheLock) {
362 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800363 final Cursor cursor = db.query(TABLE_GRANTS,
364 new String[]{GRANTS_GRANTEE_UID},
365 null, null, GRANTS_GRANTEE_UID, null, null);
366 try {
367 while (cursor.moveToNext()) {
368 final int uid = cursor.getInt(0);
369 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
370 if (packageExists) {
371 continue;
372 }
373 Log.d(TAG, "deleting grants for UID " + uid
374 + " because its package is no longer installed");
375 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
376 new String[]{Integer.toString(uid)});
377 }
378 } finally {
379 cursor.close();
380 }
381 }
382 }
383
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700384 /**
385 * Validate internal set of accounts against installed authenticators for
386 * given user. Clears cached authenticators before validating.
387 */
388 public void validateAccounts(int userId) {
389 final UserAccounts accounts = getUserAccounts(userId);
390
391 // Invalidate user-specific cache to make sure we catch any
392 // removed authenticators.
393 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
394 }
395
396 /**
397 * Validate internal set of accounts against installed authenticators for
398 * given user. Clear cached authenticators before validating when requested.
399 */
400 private void validateAccountsInternal(
401 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
402 if (invalidateAuthenticatorCache) {
403 mAuthenticatorCache.invalidateCache(accounts.userId);
404 }
405
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700406 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
407 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
408 mAuthenticatorCache.getAllServices(accounts.userId)) {
409 knownAuth.add(service.type);
410 }
411
Amith Yamasani04e0d262012-02-14 11:50:53 -0800412 synchronized (accounts.cacheLock) {
413 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800414 boolean accountDeleted = false;
415 Cursor cursor = db.query(TABLE_ACCOUNTS,
416 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800417 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800418 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800419 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800420 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700421 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800422 while (cursor.moveToNext()) {
423 final long accountId = cursor.getLong(0);
424 final String accountType = cursor.getString(1);
425 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700426
427 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700428 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800429 + accountType + " no longer has a registered authenticator");
430 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
431 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700432
433 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
434 accountId, accounts);
435
Fred Quintana56285a62010-12-02 14:20:51 -0800436 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800437 accounts.userDataCache.remove(account);
438 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700439 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800440 } else {
441 ArrayList<String> accountNames = accountNamesByType.get(accountType);
442 if (accountNames == null) {
443 accountNames = new ArrayList<String>();
444 accountNamesByType.put(accountType, accountNames);
445 }
446 accountNames.add(accountName);
447 }
448 }
Andy McFadden2f362292012-01-20 14:43:38 -0800449 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800450 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800451 final String accountType = cur.getKey();
452 final ArrayList<String> accountNames = cur.getValue();
453 final Account[] accountsForType = new Account[accountNames.size()];
454 int i = 0;
455 for (String accountName : accountNames) {
456 accountsForType[i] = new Account(accountName, accountType);
457 ++i;
458 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800459 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800460 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800461 } finally {
462 cursor.close();
463 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800464 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800465 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800466 }
467 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700468 }
469
Amith Yamasani04e0d262012-02-14 11:50:53 -0800470 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700471 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800472 }
473
474 protected UserAccounts getUserAccounts(int userId) {
475 synchronized (mUsers) {
476 UserAccounts accounts = mUsers.get(userId);
477 if (accounts == null) {
Amith Yamasani0c19bf52013-10-03 10:34:58 -0700478 accounts = initUserLocked(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800479 mUsers.append(userId, accounts);
480 }
481 return accounts;
482 }
483 }
484
Amith Yamasani13593602012-03-22 16:16:17 -0700485 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700486 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700487 if (userId < 1) return;
488
489 UserAccounts accounts;
490 synchronized (mUsers) {
491 accounts = mUsers.get(userId);
492 mUsers.remove(userId);
493 }
494 if (accounts == null) {
495 File dbFile = new File(getDatabaseName(userId));
496 dbFile.delete();
497 return;
498 }
499
500 synchronized (accounts.cacheLock) {
501 accounts.openHelper.close();
502 File dbFile = new File(getDatabaseName(userId));
503 dbFile.delete();
504 }
505 }
506
Amith Yamasani67df64b2012-12-14 12:09:36 -0800507 private void onUserStarted(Intent intent) {
508 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
509 if (userId < 1) return;
510
511 // Check if there's a shared account that needs to be created as an account
512 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
513 if (sharedAccounts == null || sharedAccounts.length == 0) return;
514 Account[] accounts = getAccountsAsUser(null, userId);
515 for (Account sa : sharedAccounts) {
516 if (ArrayUtils.contains(accounts, sa)) continue;
517 // Account doesn't exist. Copy it now.
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000518 copyAccountToUser(null /*no response*/, sa, UserHandle.USER_OWNER, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800519 }
520 }
521
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700522 @Override
523 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700524 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700525 }
526
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800527 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700528 public String getPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -0800529 if (Log.isLoggable(TAG, Log.VERBOSE)) {
530 Log.v(TAG, "getPassword: " + account
531 + ", caller's uid " + Binder.getCallingUid()
532 + ", pid " + Binder.getCallingPid());
533 }
Fred Quintana382601f2010-03-25 12:25:10 -0700534 if (account == null) throw new IllegalArgumentException("account is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +0000535 checkAuthenticateAccountsPermission(account);
536
Amith Yamasani04e0d262012-02-14 11:50:53 -0800537 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700538 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700539 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800540 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700541 } finally {
542 restoreCallingIdentity(identityToken);
543 }
544 }
545
Amith Yamasani04e0d262012-02-14 11:50:53 -0800546 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700547 if (account == null) {
548 return null;
549 }
550
Amith Yamasani04e0d262012-02-14 11:50:53 -0800551 synchronized (accounts.cacheLock) {
552 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800553 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
554 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
555 new String[]{account.name, account.type}, null, null, null);
556 try {
557 if (cursor.moveToNext()) {
558 return cursor.getString(0);
559 }
560 return null;
561 } finally {
562 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700563 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700564 }
565 }
566
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800567 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700568 public String getPreviousName(Account account) {
569 if (Log.isLoggable(TAG, Log.VERBOSE)) {
570 Log.v(TAG, "getPreviousName: " + account
571 + ", caller's uid " + Binder.getCallingUid()
572 + ", pid " + Binder.getCallingPid());
573 }
574 if (account == null) throw new IllegalArgumentException("account is null");
575 UserAccounts accounts = getUserAccountsForCaller();
576 long identityToken = clearCallingIdentity();
577 try {
578 return readPreviousNameInternal(accounts, account);
579 } finally {
580 restoreCallingIdentity(identityToken);
581 }
582 }
583
584 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
585 if (account == null) {
586 return null;
587 }
588 synchronized (accounts.cacheLock) {
589 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
590 if (previousNameRef == null) {
591 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
592 Cursor cursor = db.query(
593 TABLE_ACCOUNTS,
594 new String[]{ ACCOUNTS_PREVIOUS_NAME },
595 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
596 new String[] { account.name, account.type },
597 null,
598 null,
599 null);
600 try {
601 if (cursor.moveToNext()) {
602 String previousName = cursor.getString(0);
603 previousNameRef = new AtomicReference<String>(previousName);
604 accounts.previousNameCache.put(account, previousNameRef);
605 return previousName;
606 } else {
607 return null;
608 }
609 } finally {
610 cursor.close();
611 }
612 } else {
613 return previousNameRef.get();
614 }
615 }
616 }
617
618 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700619 public String getUserData(Account account, String key) {
Fred Quintana56285a62010-12-02 14:20:51 -0800620 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdiviadcddc472015-06-11 20:04:04 +0000621 Log.v(TAG, "getUserData: " + account
622 + ", key " + key
623 + ", caller's uid " + Binder.getCallingUid()
624 + ", pid " + Binder.getCallingPid());
Fred Quintana56285a62010-12-02 14:20:51 -0800625 }
Fred Quintana382601f2010-03-25 12:25:10 -0700626 if (account == null) throw new IllegalArgumentException("account is null");
627 if (key == null) throw new IllegalArgumentException("key is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +0000628 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800629 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700630 long identityToken = clearCallingIdentity();
631 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800632 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700633 } finally {
634 restoreCallingIdentity(identityToken);
635 }
636 }
637
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800638 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100639 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -0800640 if (Log.isLoggable(TAG, Log.VERBOSE)) {
641 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100642 + "for user id " + userId
Fred Quintana56285a62010-12-02 14:20:51 -0800643 + "caller's uid " + Binder.getCallingUid()
644 + ", pid " + Binder.getCallingPid());
645 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100646 // Only allow the system process to read accounts of other users
647 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
648 + " trying get authenticator types for " + userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700649 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700650 try {
Fred Quintana97889762009-06-15 12:29:24 -0700651 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700652 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
Fred Quintana97889762009-06-15 12:29:24 -0700653 AuthenticatorDescription[] types =
654 new AuthenticatorDescription[authenticatorCollection.size()];
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700655 int i = 0;
Fred Quintana97889762009-06-15 12:29:24 -0700656 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
Fred Quintana718d8a22009-04-29 17:53:20 -0700657 : authenticatorCollection) {
658 types[i] = authenticator.type;
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700659 i++;
660 }
661 return types;
662 } finally {
663 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700664 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700665 }
666
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100667 private void enforceCrossUserPermission(int userId, String errorMessage) {
668 if (userId != UserHandle.getCallingUserId()
669 && Binder.getCallingUid() != Process.myUid()
670 && mContext.checkCallingOrSelfPermission(
671 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
672 != PackageManager.PERMISSION_GRANTED) {
673 throw new SecurityException(errorMessage);
674 }
675 }
676
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700677 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700678 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Fred Quintana56285a62010-12-02 14:20:51 -0800679 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700680 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdiviadcddc472015-06-11 20:04:04 +0000681 + ", caller's uid " + Binder.getCallingUid()
Fred Quintana56285a62010-12-02 14:20:51 -0800682 + ", pid " + Binder.getCallingPid());
683 }
Fred Quintana382601f2010-03-25 12:25:10 -0700684 if (account == null) throw new IllegalArgumentException("account is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +0000685 checkAuthenticateAccountsPermission(account);
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700686 /*
687 * Child users are not allowed to add accounts. Only the accounts that are
688 * shared by the parent profile can be added to child profile.
689 *
690 * TODO: Only allow accounts that were shared to be added by
691 * a limited user.
692 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700693
Amith Yamasani04e0d262012-02-14 11:50:53 -0800694 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana60307342009-03-24 22:48:12 -0700695 // fails if the account already exists
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700696 int uid = getCallingUid();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700697 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700698 try {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700699 return addAccountInternal(accounts, account, password, extras, false, uid);
Fred Quintana60307342009-03-24 22:48:12 -0700700 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700701 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700702 }
703 }
704
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000705 @Override
706 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
707 int userFrom, int userTo) {
708 enforceCrossUserPermission(UserHandle.USER_ALL, "Calling copyAccountToUser requires "
709 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800710 final UserAccounts fromAccounts = getUserAccounts(userFrom);
711 final UserAccounts toAccounts = getUserAccounts(userTo);
712 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000713 if (response != null) {
714 Bundle result = new Bundle();
715 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
716 try {
717 response.onResult(result);
718 } catch (RemoteException e) {
719 Slog.w(TAG, "Failed to report error back to the client." + e);
720 }
721 }
722 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800723 }
724
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000725 Slog.d(TAG, "Copying account " + account.name
726 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800727 long identityToken = clearCallingIdentity();
728 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000729 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800730 false /* stripAuthTokenFromResult */, account.name,
731 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700732 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800733 protected String toDebugString(long now) {
734 return super.toDebugString(now) + ", getAccountCredentialsForClone"
735 + ", " + account.type;
736 }
737
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700738 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800739 public void run() throws RemoteException {
740 mAuthenticator.getAccountCredentialsForCloning(this, account);
741 }
742
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700743 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800744 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000745 if (result != null
746 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
747 // Create a Session for the target user and pass in the bundle
748 completeCloningAccount(response, result, account, toAccounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800749 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800750 super.onResult(result);
751 }
752 }
753 }.bind();
754 } finally {
755 restoreCallingIdentity(identityToken);
756 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800757 }
758
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800759 @Override
760 public boolean accountAuthenticated(final Account account) {
761 if (account == null) {
762 throw new IllegalArgumentException("account is null");
763 }
Carlos Valdiviadcddc472015-06-11 20:04:04 +0000764 checkAuthenticateAccountsPermission(account);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800765 int userId = Binder.getCallingUserHandle().getIdentifier();
766 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
767 return false;
768 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -0700769 return updateLastAuthenticatedTime(account);
770 }
771
772 private boolean updateLastAuthenticatedTime(Account account) {
773 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800774 synchronized (accounts.cacheLock) {
775 final ContentValues values = new ContentValues();
776 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
777 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
778 int i = db.update(
779 TABLE_ACCOUNTS,
780 values,
781 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
782 new String[] {
783 account.name, account.type
784 });
785 if (i > 0) {
786 return true;
787 }
788 }
789 return false;
790 }
791
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000792 private void completeCloningAccount(IAccountManagerResponse response,
793 final Bundle accountCredentials, final Account account, final UserAccounts targetUser) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800794 long id = clearCallingIdentity();
795 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000796 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800797 false /* stripAuthTokenFromResult */, account.name,
798 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700799 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800800 protected String toDebugString(long now) {
801 return super.toDebugString(now) + ", getAccountCredentialsForClone"
802 + ", " + account.type;
803 }
804
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700805 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800806 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700807 // Confirm that the owner's account still exists before this step.
808 UserAccounts owner = getUserAccounts(UserHandle.USER_OWNER);
809 synchronized (owner.cacheLock) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000810 for (Account acc : getAccounts(UserHandle.USER_OWNER)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700811 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000812 mAuthenticator.addAccountFromCredentials(
813 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700814 break;
815 }
816 }
817 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800818 }
819
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700820 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800821 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000822 // TODO: Anything to do if if succedded?
823 // TODO: If it failed: Show error notification? Should we remove the shadow
824 // account to avoid retries?
825 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800826 }
827
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700828 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800829 public void onError(int errorCode, String errorMessage) {
830 super.onError(errorCode, errorMessage);
831 // TODO: Show error notification to user
832 // TODO: Should we remove the shadow account so that it doesn't keep trying?
833 }
834
835 }.bind();
836 } finally {
837 restoreCallingIdentity(id);
838 }
839 }
840
Amith Yamasani04e0d262012-02-14 11:50:53 -0800841 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700842 Bundle extras, boolean restricted, int callingUid) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700843 if (account == null) {
844 return false;
845 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800846 synchronized (accounts.cacheLock) {
847 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800848 db.beginTransaction();
849 try {
850 long numMatches = DatabaseUtils.longForQuery(db,
851 "select count(*) from " + TABLE_ACCOUNTS
852 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
853 new String[]{account.name, account.type});
854 if (numMatches > 0) {
855 Log.w(TAG, "insertAccountIntoDatabase: " + account
856 + ", skipping since the account already exists");
857 return false;
858 }
859 ContentValues values = new ContentValues();
860 values.put(ACCOUNTS_NAME, account.name);
861 values.put(ACCOUNTS_TYPE, account.type);
862 values.put(ACCOUNTS_PASSWORD, password);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800863 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800864 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
865 if (accountId < 0) {
866 Log.w(TAG, "insertAccountIntoDatabase: " + account
867 + ", skipping the DB insert failed");
868 return false;
869 }
870 if (extras != null) {
871 for (String key : extras.keySet()) {
872 final String value = extras.getString(key);
873 if (insertExtraLocked(db, accountId, key, value) < 0) {
874 Log.w(TAG, "insertAccountIntoDatabase: " + account
875 + ", skipping since insertExtra failed for key " + key);
876 return false;
877 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700878 }
879 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800880 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700881
882 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
883 accounts, callingUid);
884
Amith Yamasani04e0d262012-02-14 11:50:53 -0800885 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800886 } finally {
887 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700888 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800889 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700890 }
891 if (accounts.userId == UserHandle.USER_OWNER) {
892 addAccountToLimitedUsers(account);
893 }
894 return true;
895 }
896
897 /**
898 * Adds the account to all limited users as shared accounts. If the user is currently
899 * running, then clone the account too.
900 * @param account the account to share with limited users
901 */
902 private void addAccountToLimitedUsers(Account account) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700903 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700904 for (UserInfo user : users) {
905 if (user.isRestricted()) {
906 addSharedAccountAsUser(account, user.id);
907 try {
908 if (ActivityManagerNative.getDefault().isUserRunning(user.id, false)) {
909 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
910 MESSAGE_COPY_SHARED_ACCOUNT, UserHandle.USER_OWNER, user.id,
911 account));
912 }
913 } catch (RemoteException re) {
914 // Shouldn't happen
915 }
916 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700917 }
918 }
919
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800920 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -0700921 ContentValues values = new ContentValues();
922 values.put(EXTRAS_KEY, key);
923 values.put(EXTRAS_ACCOUNTS_ID, accountId);
924 values.put(EXTRAS_VALUE, value);
925 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
926 }
927
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800928 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -0800929 public void hasFeatures(IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800930 Account account, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -0800931 if (Log.isLoggable(TAG, Log.VERBOSE)) {
932 Log.v(TAG, "hasFeatures: " + account
933 + ", response " + response
934 + ", features " + stringArrayToString(features)
935 + ", caller's uid " + Binder.getCallingUid()
936 + ", pid " + Binder.getCallingPid());
937 }
Fred Quintana382601f2010-03-25 12:25:10 -0700938 if (response == null) throw new IllegalArgumentException("response is null");
939 if (account == null) throw new IllegalArgumentException("account is null");
940 if (features == null) throw new IllegalArgumentException("features is null");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800941 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800942 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800943 long identityToken = clearCallingIdentity();
944 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800945 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800946 } finally {
947 restoreCallingIdentity(identityToken);
948 }
949 }
950
951 private class TestFeaturesSession extends Session {
952 private final String[] mFeatures;
953 private final Account mAccount;
954
Amith Yamasani04e0d262012-02-14 11:50:53 -0800955 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800956 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800957 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800958 true /* stripAuthTokenFromResult */, account.name,
959 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800960 mFeatures = features;
961 mAccount = account;
962 }
963
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700964 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800965 public void run() throws RemoteException {
966 try {
967 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
968 } catch (RemoteException e) {
969 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
970 }
971 }
972
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700973 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800974 public void onResult(Bundle result) {
975 IAccountManagerResponse response = getResponseAndClose();
976 if (response != null) {
977 try {
978 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -0700979 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800980 return;
981 }
Fred Quintana56285a62010-12-02 14:20:51 -0800982 if (Log.isLoggable(TAG, Log.VERBOSE)) {
983 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
984 + response);
985 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -0800986 final Bundle newResult = new Bundle();
987 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
988 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
989 response.onResult(newResult);
990 } catch (RemoteException e) {
991 // if the caller is dead then there is no one to care about remote exceptions
992 if (Log.isLoggable(TAG, Log.VERBOSE)) {
993 Log.v(TAG, "failure while notifying response", e);
994 }
995 }
996 }
997 }
998
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700999 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001000 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001001 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001002 + ", " + mAccount
1003 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1004 }
1005 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001006
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001007 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001008 public void renameAccount(
1009 IAccountManagerResponse response, Account accountToRename, String newName) {
1010 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1011 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001012 + ", caller's uid " + Binder.getCallingUid()
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001013 + ", pid " + Binder.getCallingPid());
1014 }
1015 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001016 checkAuthenticateAccountsPermission(accountToRename);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001017 UserAccounts accounts = getUserAccountsForCaller();
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001018
1019 int callingUid = getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001020 long identityToken = clearCallingIdentity();
1021 try {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001022 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName,
1023 callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001024 Bundle result = new Bundle();
1025 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1026 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1027 try {
1028 response.onResult(result);
1029 } catch (RemoteException e) {
1030 Log.w(TAG, e.getMessage());
1031 }
1032 } finally {
1033 restoreCallingIdentity(identityToken);
1034 }
1035 }
1036
1037 private Account renameAccountInternal(
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001038 UserAccounts accounts, Account accountToRename, String newName, int callingUid) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001039 Account resultAccount = null;
1040 /*
1041 * Cancel existing notifications. Let authenticators
1042 * re-post notifications as required. But we don't know if
1043 * the authenticators have bound their notifications to
1044 * now stale account name data.
1045 *
1046 * With a rename api, we might not need to do this anymore but it
1047 * shouldn't hurt.
1048 */
1049 cancelNotification(
1050 getSigninRequiredNotificationId(accounts, accountToRename),
1051 new UserHandle(accounts.userId));
1052 synchronized(accounts.credentialsPermissionNotificationIds) {
1053 for (Pair<Pair<Account, String>, Integer> pair:
1054 accounts.credentialsPermissionNotificationIds.keySet()) {
1055 if (accountToRename.equals(pair.first.first)) {
1056 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1057 cancelNotification(id, new UserHandle(accounts.userId));
1058 }
1059 }
1060 }
1061 synchronized (accounts.cacheLock) {
1062 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1063 db.beginTransaction();
1064 boolean isSuccessful = false;
1065 Account renamedAccount = new Account(newName, accountToRename.type);
1066 try {
1067 final ContentValues values = new ContentValues();
1068 values.put(ACCOUNTS_NAME, newName);
1069 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
1070 final long accountId = getAccountIdLocked(db, accountToRename);
1071 if (accountId >= 0) {
1072 final String[] argsAccountId = { String.valueOf(accountId) };
1073 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1074 db.setTransactionSuccessful();
1075 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001076 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1077 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001078 }
1079 } finally {
1080 db.endTransaction();
1081 if (isSuccessful) {
1082 /*
1083 * Database transaction was successful. Clean up cached
1084 * data associated with the account in the user profile.
1085 */
1086 insertAccountIntoCacheLocked(accounts, renamedAccount);
1087 /*
1088 * Extract the data and token caches before removing the
1089 * old account to preserve the user data associated with
1090 * the account.
1091 */
1092 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1093 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1094 removeAccountFromCacheLocked(accounts, accountToRename);
1095 /*
1096 * Update the cached data associated with the renamed
1097 * account.
1098 */
1099 accounts.userDataCache.put(renamedAccount, tmpData);
1100 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1101 accounts.previousNameCache.put(
1102 renamedAccount,
1103 new AtomicReference<String>(accountToRename.name));
1104 resultAccount = renamedAccount;
1105
1106 if (accounts.userId == UserHandle.USER_OWNER) {
1107 /*
1108 * Owner's account was renamed, rename the account for
1109 * those users with which the account was shared.
1110 */
1111 List<UserInfo> users = mUserManager.getUsers(true);
1112 for (UserInfo user : users) {
1113 if (!user.isPrimary() && user.isRestricted()) {
1114 renameSharedAccountAsUser(accountToRename, newName, user.id);
1115 }
1116 }
1117 }
1118 sendAccountsChangedBroadcast(accounts.userId);
1119 }
1120 }
1121 }
1122 return resultAccount;
1123 }
1124
1125 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001126 public void removeAccount(IAccountManagerResponse response, Account account,
1127 boolean expectActivityLaunch) {
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001128 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1129 Log.v(TAG, "removeAccount: " + account
1130 + ", response " + response
1131 + ", caller's uid " + Binder.getCallingUid()
1132 + ", pid " + Binder.getCallingPid());
1133 }
1134 if (response == null) throw new IllegalArgumentException("response is null");
1135 if (account == null) throw new IllegalArgumentException("account is null");
1136 checkManageAccountsPermission();
1137 UserHandle user = Binder.getCallingUserHandle();
1138 UserAccounts accounts = getUserAccountsForCaller();
1139 int userId = Binder.getCallingUserHandle().getIdentifier();
1140 if (!canUserModifyAccounts(userId)) {
1141 try {
1142 // TODO: This should be ERROR_CODE_USER_RESTRICTED instead. See http://b/16322768
1143 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
1144 "User cannot modify accounts");
1145 } catch (RemoteException re) {
1146 }
1147 return;
1148 }
1149 if (!canUserModifyAccountsForType(userId, account.type)) {
1150 try {
1151 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1152 "User cannot modify accounts of this type (policy).");
1153 } catch (RemoteException re) {
1154 }
1155 return;
1156 }
1157
1158 long identityToken = clearCallingIdentity();
1159
1160 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
1161 synchronized (accounts.credentialsPermissionNotificationIds) {
1162 for (Pair<Pair<Account, String>, Integer> pair:
1163 accounts.credentialsPermissionNotificationIds.keySet()) {
1164 if (account.equals(pair.first.first)) {
1165 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1166 cancelNotification(id, user);
1167 }
1168 }
1169 }
1170
1171 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1172
1173 try {
1174 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1175 } finally {
1176 restoreCallingIdentity(identityToken);
1177 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001178 }
1179
1180 @Override
1181 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001182 boolean expectActivityLaunch, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001183 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1184 Log.v(TAG, "removeAccount: " + account
1185 + ", response " + response
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001186 + ", caller's uid " + Binder.getCallingUid()
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001187 + ", pid " + Binder.getCallingPid()
1188 + ", for user id " + userId);
1189 }
1190 if (response == null) throw new IllegalArgumentException("response is null");
1191 if (account == null) throw new IllegalArgumentException("account is null");
1192
1193 // Only allow the system process to modify accounts of other users
1194 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
1195 + " trying to remove account for " + userId);
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001196 checkManageAccountsPermission();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001197
1198 UserAccounts accounts = getUserAccounts(userId);
1199 if (!canUserModifyAccounts(userId)) {
1200 try {
1201 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1202 "User cannot modify accounts");
1203 } catch (RemoteException re) {
1204 }
1205 return;
1206 }
1207 if (!canUserModifyAccountsForType(userId, account.type)) {
1208 try {
1209 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1210 "User cannot modify accounts of this type (policy).");
1211 } catch (RemoteException re) {
1212 }
1213 return;
1214 }
1215
1216 UserHandle user = new UserHandle(userId);
1217 long identityToken = clearCallingIdentity();
1218
1219 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001220 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001221 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001222 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001223 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001224 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001225 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001226 }
1227 }
1228 }
1229
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001230 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1231
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001232 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001233 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1234 } finally {
1235 restoreCallingIdentity(identityToken);
1236 }
1237 }
1238
1239 @Override
1240 public boolean removeAccountExplicitly(Account account) {
1241 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1242 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001243 + ", caller's uid " + Binder.getCallingUid()
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001244 + ", pid " + Binder.getCallingPid());
1245 }
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001246 if (account == null) throw new IllegalArgumentException("account is null");
1247 checkAuthenticateAccountsPermission(account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001248
1249 UserAccounts accounts = getUserAccountsForCaller();
1250 int userId = Binder.getCallingUserHandle().getIdentifier();
1251 if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
1252 return false;
1253 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001254
1255 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1256
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001257 long identityToken = clearCallingIdentity();
1258 try {
1259 return removeAccountInternal(accounts, account);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001260 } finally {
1261 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001262 }
Fred Quintana60307342009-03-24 22:48:12 -07001263 }
1264
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001265 private class RemoveAccountSession extends Session {
1266 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001267 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001268 Account account, boolean expectActivityLaunch) {
1269 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001270 true /* stripAuthTokenFromResult */, account.name,
1271 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001272 mAccount = account;
1273 }
1274
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001275 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001276 protected String toDebugString(long now) {
1277 return super.toDebugString(now) + ", removeAccount"
1278 + ", account " + mAccount;
1279 }
1280
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001281 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001282 public void run() throws RemoteException {
1283 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1284 }
1285
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001286 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001287 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001288 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1289 && !result.containsKey(AccountManager.KEY_INTENT)) {
1290 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001291 if (removalAllowed) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001292 removeAccountInternal(mAccounts, mAccount);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001293 }
1294 IAccountManagerResponse response = getResponseAndClose();
1295 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001296 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1297 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1298 + response);
1299 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001300 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001301 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001302 try {
1303 response.onResult(result2);
1304 } catch (RemoteException e) {
1305 // ignore
1306 }
1307 }
1308 }
1309 super.onResult(result);
1310 }
1311 }
1312
Amith Yamasani04e0d262012-02-14 11:50:53 -08001313 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001314 protected void removeAccountInternal(Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001315 removeAccountInternal(getUserAccountsForCaller(), account);
1316 }
1317
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001318 private boolean removeAccountInternal(UserAccounts accounts, Account account) {
1319 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001320 synchronized (accounts.cacheLock) {
1321 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001322 final long accountId = getAccountIdLocked(db, account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001323 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1324 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001325 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001326 removeAccountFromCacheLocked(accounts, account);
1327 sendAccountsChangedBroadcast(accounts.userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001328
1329 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001330 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001331 if (accounts.userId == UserHandle.USER_OWNER) {
1332 // Owner's account was removed, remove from any users that are sharing
1333 // this account.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001334 int callingUid = getCallingUid();
Amith Yamasani67df64b2012-12-14 12:09:36 -08001335 long id = Binder.clearCallingIdentity();
1336 try {
1337 List<UserInfo> users = mUserManager.getUsers(true);
1338 for (UserInfo user : users) {
1339 if (!user.isPrimary() && user.isRestricted()) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001340 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001341 }
1342 }
1343 } finally {
1344 Binder.restoreCallingIdentity(id);
1345 }
1346 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001347 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001348 }
1349
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001350 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001351 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001352 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001353 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1354 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001355 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001356 + ", pid " + Binder.getCallingPid());
1357 }
Fred Quintana382601f2010-03-25 12:25:10 -07001358 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1359 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001360 checkManageAccountsOrUseCredentialsPermissions();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001361 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001362 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001363 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001364 synchronized (accounts.cacheLock) {
1365 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001366 db.beginTransaction();
1367 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001368 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001369 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001370 db.setTransactionSuccessful();
1371 } finally {
1372 db.endTransaction();
1373 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001374 }
Fred Quintana60307342009-03-24 22:48:12 -07001375 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001376 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001377 }
1378 }
1379
Carlos Valdivia91979be2015-05-22 14:11:35 -07001380 private void invalidateCustomTokenLocked(
1381 UserAccounts accounts,
1382 String accountType,
1383 String authToken) {
1384 if (authToken == null || accountType == null) {
1385 return;
1386 }
1387 // Also wipe out cached token in memory.
1388 for (Account a : accounts.accountTokenCaches.keySet()) {
1389 if (a.type.equals(accountType)) {
1390 WeakReference<TokenCache> tokenCacheRef =
1391 accounts.accountTokenCaches.get(a);
1392 TokenCache cache = null;
1393 if (tokenCacheRef != null && (cache = tokenCacheRef.get()) != null) {
1394 cache.remove(authToken);
1395 }
1396 }
1397 }
1398 }
1399
Amith Yamasani04e0d262012-02-14 11:50:53 -08001400 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1401 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001402 if (authToken == null || accountType == null) {
1403 return;
1404 }
Fred Quintana33269202009-04-20 16:05:10 -07001405 Cursor cursor = db.rawQuery(
1406 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1407 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1408 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1409 + " FROM " + TABLE_ACCOUNTS
1410 + " JOIN " + TABLE_AUTHTOKENS
1411 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1412 + " = " + AUTHTOKENS_ACCOUNTS_ID
1413 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1414 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1415 new String[]{authToken, accountType});
1416 try {
1417 while (cursor.moveToNext()) {
1418 long authTokenId = cursor.getLong(0);
1419 String accountName = cursor.getString(1);
1420 String authTokenType = cursor.getString(2);
1421 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001422 writeAuthTokenIntoCacheLocked(
1423 accounts,
1424 db,
1425 new Account(accountName, accountType),
1426 authTokenType,
1427 null);
Fred Quintana60307342009-03-24 22:48:12 -07001428 }
Fred Quintana33269202009-04-20 16:05:10 -07001429 } finally {
1430 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001431 }
1432 }
1433
Carlos Valdivia91979be2015-05-22 14:11:35 -07001434 private void saveCachedToken(
1435 UserAccounts accounts,
1436 Account account,
1437 String callerPkg,
1438 byte[] callerSigDigest,
1439 String tokenType,
1440 String token,
1441 long expiryMillis) {
1442
1443 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1444 return;
1445 }
1446 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1447 new UserHandle(accounts.userId));
1448 synchronized (accounts.cacheLock) {
1449 TokenCache cache = getTokenCacheForAccountLocked(accounts, account);
1450 if (cache != null) {
1451 cache.put(token, tokenType, callerPkg, callerSigDigest, expiryMillis);
1452 }
1453 return;
1454 }
1455 }
1456
Amith Yamasani04e0d262012-02-14 11:50:53 -08001457 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1458 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001459 if (account == null || type == null) {
1460 return false;
1461 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001462 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1463 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001464 synchronized (accounts.cacheLock) {
1465 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001466 db.beginTransaction();
1467 try {
1468 long accountId = getAccountIdLocked(db, account);
1469 if (accountId < 0) {
1470 return false;
1471 }
1472 db.delete(TABLE_AUTHTOKENS,
1473 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1474 new String[]{type});
1475 ContentValues values = new ContentValues();
1476 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1477 values.put(AUTHTOKENS_TYPE, type);
1478 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1479 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1480 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001481 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001482 return true;
1483 }
Fred Quintana33269202009-04-20 16:05:10 -07001484 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001485 } finally {
1486 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001487 }
Fred Quintana60307342009-03-24 22:48:12 -07001488 }
1489 }
1490
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001491 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001492 public String peekAuthToken(Account account, String authTokenType) {
Fred Quintana56285a62010-12-02 14:20:51 -08001493 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1494 Log.v(TAG, "peekAuthToken: " + account
1495 + ", authTokenType " + authTokenType
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001496 + ", caller's uid " + Binder.getCallingUid()
Fred Quintana56285a62010-12-02 14:20:51 -08001497 + ", pid " + Binder.getCallingPid());
1498 }
Fred Quintana382601f2010-03-25 12:25:10 -07001499 if (account == null) throw new IllegalArgumentException("account is null");
1500 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001501 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001502 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001503 long identityToken = clearCallingIdentity();
1504 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001505 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001506 } finally {
1507 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001508 }
Fred Quintana60307342009-03-24 22:48:12 -07001509 }
1510
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001511 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001512 public void setAuthToken(Account account, String authTokenType, String authToken) {
Fred Quintana56285a62010-12-02 14:20:51 -08001513 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1514 Log.v(TAG, "setAuthToken: " + account
1515 + ", authTokenType " + authTokenType
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001516 + ", caller's uid " + Binder.getCallingUid()
Fred Quintana56285a62010-12-02 14:20:51 -08001517 + ", pid " + Binder.getCallingPid());
1518 }
Fred Quintana382601f2010-03-25 12:25:10 -07001519 if (account == null) throw new IllegalArgumentException("account is null");
1520 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001521 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001522 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001523 long identityToken = clearCallingIdentity();
1524 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001525 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001526 } finally {
1527 restoreCallingIdentity(identityToken);
1528 }
Fred Quintana60307342009-03-24 22:48:12 -07001529 }
1530
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001531 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001532 public void setPassword(Account account, String password) {
Fred Quintana56285a62010-12-02 14:20:51 -08001533 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1534 Log.v(TAG, "setAuthToken: " + account
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001535 + ", caller's uid " + Binder.getCallingUid()
Fred Quintana56285a62010-12-02 14:20:51 -08001536 + ", pid " + Binder.getCallingPid());
1537 }
Fred Quintana382601f2010-03-25 12:25:10 -07001538 if (account == null) throw new IllegalArgumentException("account is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001539 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001540 UserAccounts accounts = getUserAccountsForCaller();
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001541 int callingUid = getCallingUid();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001542 long identityToken = clearCallingIdentity();
1543 try {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001544 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001545 } finally {
1546 restoreCallingIdentity(identityToken);
1547 }
Fred Quintana60307342009-03-24 22:48:12 -07001548 }
1549
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001550 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1551 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001552 if (account == null) {
1553 return;
1554 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001555 synchronized (accounts.cacheLock) {
1556 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001557 db.beginTransaction();
1558 try {
1559 final ContentValues values = new ContentValues();
1560 values.put(ACCOUNTS_PASSWORD, password);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001561 long time = 0;
1562 // Only set current time, if it is a valid password. For clear password case, it
1563 // should not be set.
1564 if (password != null) {
1565 time = System.currentTimeMillis();
1566 }
1567 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, time);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001568 final long accountId = getAccountIdLocked(db, account);
1569 if (accountId >= 0) {
1570 final String[] argsAccountId = {String.valueOf(accountId)};
1571 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1572 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001573 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001574 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001575 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001576
1577 String action = (password == null || password.length() == 0) ?
1578 DebugDbHelper.ACTION_CLEAR_PASSWORD
1579 : DebugDbHelper.ACTION_SET_PASSWORD;
1580 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001581 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001582 } finally {
1583 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001584 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001585 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001586 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001587 }
1588
Amith Yamasani04e0d262012-02-14 11:50:53 -08001589 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001590 Log.i(TAG, "the accounts changed, sending broadcast of "
1591 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001592 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001593 }
1594
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001595 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001596 public void clearPassword(Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08001597 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1598 Log.v(TAG, "clearPassword: " + account
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001599 + ", caller's uid " + Binder.getCallingUid()
Fred Quintana56285a62010-12-02 14:20:51 -08001600 + ", pid " + Binder.getCallingPid());
1601 }
Fred Quintana382601f2010-03-25 12:25:10 -07001602 if (account == null) throw new IllegalArgumentException("account is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001603 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001604 UserAccounts accounts = getUserAccountsForCaller();
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001605
1606 int callingUid = getCallingUid();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001607 long identityToken = clearCallingIdentity();
1608 try {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001609 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001610 } finally {
1611 restoreCallingIdentity(identityToken);
1612 }
Fred Quintana60307342009-03-24 22:48:12 -07001613 }
1614
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001615 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001616 public void setUserData(Account account, String key, String value) {
Fred Quintana56285a62010-12-02 14:20:51 -08001617 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1618 Log.v(TAG, "setUserData: " + account
1619 + ", key " + key
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001620 + ", caller's uid " + Binder.getCallingUid()
Fred Quintana56285a62010-12-02 14:20:51 -08001621 + ", pid " + Binder.getCallingPid());
1622 }
Fred Quintana382601f2010-03-25 12:25:10 -07001623 if (key == null) throw new IllegalArgumentException("key is null");
1624 if (account == null) throw new IllegalArgumentException("account is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001625 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001626 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001627 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001628 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001629 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001630 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001631 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001632 }
1633 }
1634
Amith Yamasani04e0d262012-02-14 11:50:53 -08001635 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1636 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001637 if (account == null || key == null) {
1638 return;
1639 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001640 synchronized (accounts.cacheLock) {
1641 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001642 db.beginTransaction();
1643 try {
1644 long accountId = getAccountIdLocked(db, account);
1645 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001646 return;
1647 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001648 long extrasId = getExtrasIdLocked(db, accountId, key);
1649 if (extrasId < 0 ) {
1650 extrasId = insertExtraLocked(db, accountId, key, value);
1651 if (extrasId < 0) {
1652 return;
1653 }
1654 } else {
1655 ContentValues values = new ContentValues();
1656 values.put(EXTRAS_VALUE, value);
1657 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1658 return;
1659 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001660
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001661 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001662 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001663 db.setTransactionSuccessful();
1664 } finally {
1665 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001666 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001667 }
1668 }
1669
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001670 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001671 if (result == null) {
1672 Log.e(TAG, "the result is unexpectedly null", new Exception());
1673 }
1674 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1675 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1676 + response);
1677 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001678 try {
1679 response.onResult(result);
1680 } catch (RemoteException e) {
1681 // if the caller is dead then there is no one to care about remote
1682 // exceptions
1683 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1684 Log.v(TAG, "failure while notifying response", e);
1685 }
1686 }
1687 }
1688
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001689 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001690 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1691 final String authTokenType)
1692 throws RemoteException {
1693 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001694 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1695
Fred Quintanad9640ec2012-05-23 12:37:00 -07001696 final int callingUid = getCallingUid();
1697 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001698 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001699 throw new SecurityException("can only call from system");
1700 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001701 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001702 long identityToken = clearCallingIdentity();
1703 try {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001704 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1705 false /* stripAuthTokenFromResult */, null /* accountName */,
1706 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001707 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001708 protected String toDebugString(long now) {
1709 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001710 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001711 + ", authTokenType " + authTokenType;
1712 }
1713
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001714 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001715 public void run() throws RemoteException {
1716 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1717 }
1718
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001719 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001720 public void onResult(Bundle result) {
1721 if (result != null) {
1722 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1723 Bundle bundle = new Bundle();
1724 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1725 super.onResult(bundle);
1726 return;
1727 } else {
1728 super.onResult(result);
1729 }
1730 }
1731 }.bind();
1732 } finally {
1733 restoreCallingIdentity(identityToken);
1734 }
1735 }
1736
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001737 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07001738 public void getAuthToken(
1739 IAccountManagerResponse response,
1740 final Account account,
1741 final String authTokenType,
1742 final boolean notifyOnAuthFailure,
1743 final boolean expectActivityLaunch,
1744 final Bundle loginOptions) {
1745
Fred Quintana56285a62010-12-02 14:20:51 -08001746 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1747 Log.v(TAG, "getAuthToken: " + account
1748 + ", response " + response
1749 + ", authTokenType " + authTokenType
1750 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1751 + ", expectActivityLaunch " + expectActivityLaunch
1752 + ", caller's uid " + Binder.getCallingUid()
1753 + ", pid " + Binder.getCallingPid());
1754 }
Fred Quintana382601f2010-03-25 12:25:10 -07001755 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001756 try {
1757 if (account == null) {
1758 Slog.w(TAG, "getAuthToken called with null account");
1759 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1760 return;
1761 }
1762 if (authTokenType == null) {
1763 Slog.w(TAG, "getAuthToken called with null authTokenType");
1764 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1765 return;
1766 }
1767 } catch (RemoteException e) {
1768 Slog.w(TAG, "Failed to report error back to the client." + e);
1769 return;
1770 }
1771
Carlos Valdiviadcddc472015-06-11 20:04:04 +00001772 checkBinderPermission(Manifest.permission.USE_CREDENTIALS);
Dianne Hackborn41203752012-08-31 14:05:51 -07001773 final UserAccounts accounts = getUserAccountsForCaller();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001774 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
1775 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1776 AuthenticatorDescription.newKey(account.type), accounts.userId);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001777
Costin Manolachea40c6302010-12-13 14:50:45 -08001778 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07001779 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08001780
1781 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001782 final int callerUid = Binder.getCallingUid();
Costin Manolachea40c6302010-12-13 14:50:45 -08001783 final boolean permissionGranted = customTokens ||
1784 permissionIsGranted(account, authTokenType, callerUid);
1785
Carlos Valdivia91979be2015-05-22 14:11:35 -07001786 // Get the calling package. We will use it for the purpose of caching.
1787 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07001788 List<String> callerOwnedPackageNames;
1789 long ident = Binder.clearCallingIdentity();
1790 try {
1791 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
1792 } finally {
1793 Binder.restoreCallingIdentity(ident);
1794 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001795 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
1796 String msg = String.format(
1797 "Uid %s is attempting to illegally masquerade as package %s!",
1798 callerUid,
1799 callerPkg);
1800 throw new SecurityException(msg);
1801 }
1802
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001803 // let authenticator know the identity of the caller
1804 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1805 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07001806
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001807 if (notifyOnAuthFailure) {
1808 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001809 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001810
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001811 long identityToken = clearCallingIdentity();
1812 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07001813 // Distill the caller's package signatures into a single digest.
1814 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
1815
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001816 // if the caller has permission, do the peek. otherwise go the more expensive
1817 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001818 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001819 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001820 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001821 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001822 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1823 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1824 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001825 onResult(response, result);
1826 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001827 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001828 }
1829
Carlos Valdivia91979be2015-05-22 14:11:35 -07001830 if (customTokens) {
1831 /*
1832 * Look up tokens in the new cache only if the loginOptions don't have parameters
1833 * outside of those expected to be injected by the AccountManager, e.g.
1834 * ANDORID_PACKAGE_NAME.
1835 */
1836 String token = readCachedTokenInternal(
1837 accounts,
1838 account,
1839 authTokenType,
1840 callerPkg,
1841 callerPkgSigDigest);
1842 if (token != null) {
1843 Bundle result = new Bundle();
1844 result.putString(AccountManager.KEY_AUTHTOKEN, token);
1845 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1846 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
1847 onResult(response, result);
1848 return;
1849 }
1850 }
1851
Amith Yamasani04e0d262012-02-14 11:50:53 -08001852 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001853 false /* stripAuthTokenFromResult */, account.name,
1854 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001855 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001856 protected String toDebugString(long now) {
1857 if (loginOptions != null) loginOptions.keySet();
1858 return super.toDebugString(now) + ", getAuthToken"
1859 + ", " + account
1860 + ", authTokenType " + authTokenType
1861 + ", loginOptions " + loginOptions
1862 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1863 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001864
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001865 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001866 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001867 // If the caller doesn't have permission then create and return the
1868 // "grant permission" intent instead of the "getAuthToken" intent.
1869 if (!permissionGranted) {
1870 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1871 } else {
1872 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1873 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001874 }
1875
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001876 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001877 public void onResult(Bundle result) {
1878 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001879 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001880 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1881 new AccountAuthenticatorResponse(this),
1882 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001883 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001884 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001885 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001886 onResult(bundle);
1887 return;
1888 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001889 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001890 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001891 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1892 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001893 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001894 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001895 "the type and name should not be empty");
1896 return;
1897 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001898 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08001899 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001900 saveAuthTokenToDatabase(
1901 mAccounts,
1902 resultAccount,
1903 authTokenType,
1904 authToken);
1905 }
1906 long expiryMillis = result.getLong(
1907 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
1908 if (customTokens
1909 && expiryMillis > System.currentTimeMillis()) {
1910 saveCachedToken(
1911 mAccounts,
1912 account,
1913 callerPkg,
1914 callerPkgSigDigest,
1915 authTokenType,
1916 authToken,
1917 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08001918 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001919 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001920
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001921 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001922 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001923 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001924 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001925 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001926 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001927 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001928 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001929 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001930 }.bind();
1931 } finally {
1932 restoreCallingIdentity(identityToken);
1933 }
Fred Quintana60307342009-03-24 22:48:12 -07001934 }
1935
Carlos Valdivia91979be2015-05-22 14:11:35 -07001936 private byte[] calculatePackageSignatureDigest(String callerPkg) {
1937 MessageDigest digester;
1938 try {
1939 digester = MessageDigest.getInstance("SHA-256");
1940 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
1941 callerPkg, PackageManager.GET_SIGNATURES);
1942 for (Signature sig : pkgInfo.signatures) {
1943 digester.update(sig.toByteArray());
1944 }
1945 } catch (NoSuchAlgorithmException x) {
1946 Log.wtf(TAG, "SHA-256 should be available", x);
1947 digester = null;
1948 } catch (NameNotFoundException e) {
1949 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
1950 digester = null;
1951 }
1952 return (digester == null) ? null : digester.digest();
1953 }
1954
Dianne Hackborn41203752012-08-31 14:05:51 -07001955 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1956 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001957 int uid = intent.getIntExtra(
1958 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1959 String authTokenType = intent.getStringExtra(
1960 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1961 String authTokenLabel = intent.getStringExtra(
1962 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1963
1964 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1965 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001966 final String titleAndSubtitle =
1967 mContext.getString(R.string.permission_request_notification_with_subtitle,
1968 account.name);
1969 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001970 String title = titleAndSubtitle;
1971 String subtitle = "";
1972 if (index > 0) {
1973 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001974 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001975 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001976 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01001977 Context contextForUser = getContextForUser(user);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001978 n.color = contextForUser.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001979 com.android.internal.R.color.system_notification_accent_color);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01001980 n.setLatestEventInfo(contextForUser, title, subtitle,
Dianne Hackborn41203752012-08-31 14:05:51 -07001981 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001982 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1983 installNotification(getCredentialPermissionNotificationId(
1984 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001985 }
1986
Costin Manolache5f383ad92010-12-02 16:44:46 -08001987 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1988 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001989
1990 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001991 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001992 // Since it was set in Eclair+ we can't change it without breaking apps using
1993 // the intent from a non-Activity context.
1994 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001995 intent.addCategory(
1996 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001997
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001998 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001999 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2000 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002001 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002002
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002003 return intent;
2004 }
2005
2006 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2007 int uid) {
2008 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002009 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002010 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002011 final Pair<Pair<Account, String>, Integer> key =
2012 new Pair<Pair<Account, String>, Integer>(
2013 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002014 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002015 if (id == null) {
2016 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002017 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002018 }
2019 }
2020 return id;
2021 }
2022
Amith Yamasani04e0d262012-02-14 11:50:53 -08002023 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002024 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002025 synchronized (accounts.signinRequiredNotificationIds) {
2026 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002027 if (id == null) {
2028 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002029 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002030 }
2031 }
2032 return id;
2033 }
2034
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002035 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002036 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002037 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002038 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08002039 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2040 Log.v(TAG, "addAccount: accountType " + accountType
2041 + ", response " + response
2042 + ", authTokenType " + authTokenType
2043 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2044 + ", expectActivityLaunch " + expectActivityLaunch
2045 + ", caller's uid " + Binder.getCallingUid()
2046 + ", pid " + Binder.getCallingPid());
2047 }
Fred Quintana382601f2010-03-25 12:25:10 -07002048 if (response == null) throw new IllegalArgumentException("response is null");
2049 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00002050 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002051
Amith Yamasani71e6c692013-03-24 17:39:28 -07002052 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002053 int userId = Binder.getCallingUserHandle().getIdentifier();
2054 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002055 try {
2056 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2057 "User is not allowed to add an account!");
2058 } catch (RemoteException re) {
2059 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002060 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002061 return;
2062 }
2063 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002064 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002065 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2066 "User cannot modify accounts of this type (policy).");
2067 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002068 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002069 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2070 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002071 return;
2072 }
2073
Amith Yamasani04e0d262012-02-14 11:50:53 -08002074 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002075 final int pid = Binder.getCallingPid();
2076 final int uid = Binder.getCallingUid();
2077 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2078 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2079 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2080
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002081 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS);
2082
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002083 long identityToken = clearCallingIdentity();
2084 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002085 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002086 true /* stripAuthTokenFromResult */, null /* accountName */,
2087 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002088 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002089 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002090 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002091 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002092 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002093
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002094 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002095 protected String toDebugString(long now) {
2096 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002097 + ", accountType " + accountType
2098 + ", requiredFeatures "
2099 + (requiredFeatures != null
2100 ? TextUtils.join(",", requiredFeatures)
2101 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002102 }
2103 }.bind();
2104 } finally {
2105 restoreCallingIdentity(identityToken);
2106 }
Fred Quintana60307342009-03-24 22:48:12 -07002107 }
2108
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002109 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002110 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2111 final String authTokenType, final String[] requiredFeatures,
2112 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
2113 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2114 Log.v(TAG, "addAccount: accountType " + accountType
2115 + ", response " + response
2116 + ", authTokenType " + authTokenType
2117 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2118 + ", expectActivityLaunch " + expectActivityLaunch
2119 + ", caller's uid " + Binder.getCallingUid()
2120 + ", pid " + Binder.getCallingPid()
2121 + ", for user id " + userId);
2122 }
2123 if (response == null) throw new IllegalArgumentException("response is null");
2124 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00002125 checkManageAccountsPermission();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002126
2127 // Only allow the system process to add accounts of other users
2128 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
2129 + " trying to add account for " + userId);
2130
2131 // Is user disallowed from modifying accounts?
2132 if (!canUserModifyAccounts(userId)) {
2133 try {
2134 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2135 "User is not allowed to add an account!");
2136 } catch (RemoteException re) {
2137 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002138 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002139 return;
2140 }
2141 if (!canUserModifyAccountsForType(userId, accountType)) {
2142 try {
2143 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2144 "User cannot modify accounts of this type (policy).");
2145 } catch (RemoteException re) {
2146 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002147 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2148 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002149 return;
2150 }
2151
2152 UserAccounts accounts = getUserAccounts(userId);
2153 final int pid = Binder.getCallingPid();
2154 final int uid = Binder.getCallingUid();
2155 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2156 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2157 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2158
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002159 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS);
2160
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002161 long identityToken = clearCallingIdentity();
2162 try {
2163 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002164 true /* stripAuthTokenFromResult */, null /* accountName */,
2165 false /* authDetailsRequired */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002166 @Override
2167 public void run() throws RemoteException {
2168 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2169 options);
2170 }
2171
2172 @Override
2173 protected String toDebugString(long now) {
2174 return super.toDebugString(now) + ", addAccount"
2175 + ", accountType " + accountType
2176 + ", requiredFeatures "
2177 + (requiredFeatures != null
2178 ? TextUtils.join(",", requiredFeatures)
2179 : null);
2180 }
2181 }.bind();
2182 } finally {
2183 restoreCallingIdentity(identityToken);
2184 }
2185 }
2186
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002187 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002188 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2189 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2190 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2191 long identityToken = clearCallingIdentity();
2192 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002193 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002194 } finally {
2195 restoreCallingIdentity(identityToken);
2196 }
2197 }
2198
2199 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002200 public void confirmCredentialsAsUser(IAccountManagerResponse response,
2201 final Account account, final Bundle options, final boolean expectActivityLaunch,
2202 int userId) {
2203 // Only allow the system process to read accounts of other users
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01002204 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002205 + " trying to confirm account credentials for " + userId);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002206
Fred Quintana56285a62010-12-02 14:20:51 -08002207 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2208 Log.v(TAG, "confirmCredentials: " + account
2209 + ", response " + response
2210 + ", expectActivityLaunch " + expectActivityLaunch
2211 + ", caller's uid " + Binder.getCallingUid()
2212 + ", pid " + Binder.getCallingPid());
2213 }
Fred Quintana382601f2010-03-25 12:25:10 -07002214 if (response == null) throw new IllegalArgumentException("response is null");
2215 if (account == null) throw new IllegalArgumentException("account is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00002216 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002217 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002218 long identityToken = clearCallingIdentity();
2219 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002220 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002221 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002222 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002223 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002224 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002225 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002226 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002227 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002228 protected String toDebugString(long now) {
2229 return super.toDebugString(now) + ", confirmCredentials"
2230 + ", " + account;
2231 }
2232 }.bind();
2233 } finally {
2234 restoreCallingIdentity(identityToken);
2235 }
Fred Quintana60307342009-03-24 22:48:12 -07002236 }
2237
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002238 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002239 public void updateCredentials(IAccountManagerResponse response, final Account account,
2240 final String authTokenType, final boolean expectActivityLaunch,
2241 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08002242 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2243 Log.v(TAG, "updateCredentials: " + account
2244 + ", response " + response
2245 + ", authTokenType " + authTokenType
2246 + ", expectActivityLaunch " + expectActivityLaunch
2247 + ", caller's uid " + Binder.getCallingUid()
2248 + ", pid " + Binder.getCallingPid());
2249 }
Fred Quintana382601f2010-03-25 12:25:10 -07002250 if (response == null) throw new IllegalArgumentException("response is null");
2251 if (account == null) throw new IllegalArgumentException("account is null");
2252 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00002253 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002254 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002255 long identityToken = clearCallingIdentity();
2256 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002257 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002258 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002259 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002260 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002261 public void run() throws RemoteException {
2262 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2263 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002264 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002265 protected String toDebugString(long now) {
2266 if (loginOptions != null) loginOptions.keySet();
2267 return super.toDebugString(now) + ", updateCredentials"
2268 + ", " + account
2269 + ", authTokenType " + authTokenType
2270 + ", loginOptions " + loginOptions;
2271 }
2272 }.bind();
2273 } finally {
2274 restoreCallingIdentity(identityToken);
2275 }
Fred Quintana60307342009-03-24 22:48:12 -07002276 }
2277
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002278 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002279 public void editProperties(IAccountManagerResponse response, final String accountType,
2280 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08002281 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2282 Log.v(TAG, "editProperties: accountType " + accountType
2283 + ", response " + response
2284 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviadcddc472015-06-11 20:04:04 +00002285 + ", caller's uid " + Binder.getCallingUid()
Fred Quintana56285a62010-12-02 14:20:51 -08002286 + ", pid " + Binder.getCallingPid());
2287 }
Fred Quintana382601f2010-03-25 12:25:10 -07002288 if (response == null) throw new IllegalArgumentException("response is null");
2289 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Carlos Valdiviadcddc472015-06-11 20:04:04 +00002290 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002291 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002292 long identityToken = clearCallingIdentity();
2293 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002294 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002295 true /* stripAuthTokenFromResult */, null /* accountName */,
2296 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002297 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002298 public void run() throws RemoteException {
2299 mAuthenticator.editProperties(this, mAccountType);
2300 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002301 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002302 protected String toDebugString(long now) {
2303 return super.toDebugString(now) + ", editProperties"
2304 + ", accountType " + accountType;
2305 }
2306 }.bind();
2307 } finally {
2308 restoreCallingIdentity(identityToken);
2309 }
Fred Quintana60307342009-03-24 22:48:12 -07002310 }
2311
Fred Quintana33269202009-04-20 16:05:10 -07002312 private class GetAccountsByTypeAndFeatureSession extends Session {
2313 private final String[] mFeatures;
2314 private volatile Account[] mAccountsOfType = null;
2315 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2316 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002317 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002318
Amith Yamasani04e0d262012-02-14 11:50:53 -08002319 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002320 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002321 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002322 true /* stripAuthTokenFromResult */, null /* accountName */,
2323 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002324 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002325 mFeatures = features;
2326 }
2327
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002328 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002329 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002330 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002331 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2332 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002333 }
Fred Quintana33269202009-04-20 16:05:10 -07002334 // check whether each account matches the requested features
2335 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2336 mCurrentAccount = 0;
2337
2338 checkAccount();
2339 }
2340
2341 public void checkAccount() {
2342 if (mCurrentAccount >= mAccountsOfType.length) {
2343 sendResult();
2344 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002345 }
Fred Quintana33269202009-04-20 16:05:10 -07002346
Fred Quintana29e94b82010-03-10 12:11:51 -08002347 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2348 if (accountAuthenticator == null) {
2349 // It is possible that the authenticator has died, which is indicated by
2350 // mAuthenticator being set to null. If this happens then just abort.
2351 // There is no need to send back a result or error in this case since
2352 // that already happened when mAuthenticator was cleared.
2353 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2354 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2355 + " connected to the authenticator, " + toDebugString());
2356 }
2357 return;
2358 }
Fred Quintana33269202009-04-20 16:05:10 -07002359 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002360 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002361 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002362 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002363 }
2364 }
2365
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002366 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002367 public void onResult(Bundle result) {
2368 mNumResults++;
2369 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002370 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002371 return;
2372 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002373 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002374 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2375 }
2376 mCurrentAccount++;
2377 checkAccount();
2378 }
2379
2380 public void sendResult() {
2381 IAccountManagerResponse response = getResponseAndClose();
2382 if (response != null) {
2383 try {
2384 Account[] accounts = new Account[mAccountsWithFeatures.size()];
2385 for (int i = 0; i < accounts.length; i++) {
2386 accounts[i] = mAccountsWithFeatures.get(i);
2387 }
Fred Quintana56285a62010-12-02 14:20:51 -08002388 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2389 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2390 + response);
2391 }
Fred Quintana33269202009-04-20 16:05:10 -07002392 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002393 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07002394 response.onResult(result);
2395 } catch (RemoteException e) {
2396 // if the caller is dead then there is no one to care about remote exceptions
2397 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2398 Log.v(TAG, "failure while notifying response", e);
2399 }
2400 }
2401 }
2402 }
2403
2404
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002405 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002406 protected String toDebugString(long now) {
2407 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2408 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2409 }
2410 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002411
Amith Yamasani04e0d262012-02-14 11:50:53 -08002412 /**
2413 * Returns the accounts for a specific user
2414 * @hide
2415 */
2416 public Account[] getAccounts(int userId) {
2417 checkReadAccountsPermission();
2418 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002419 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002420 long identityToken = clearCallingIdentity();
2421 try {
2422 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002423 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002424 }
2425 } finally {
2426 restoreCallingIdentity(identityToken);
2427 }
2428 }
2429
Amith Yamasanif29f2362012-04-05 18:29:52 -07002430 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002431 * Returns accounts for all running users.
2432 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07002433 * @hide
2434 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002435 public AccountAndUser[] getRunningAccounts() {
2436 final int[] runningUserIds;
2437 try {
2438 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2439 } catch (RemoteException e) {
2440 // Running in system_server; should never happen
2441 throw new RuntimeException(e);
2442 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002443 return getAccounts(runningUserIds);
2444 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07002445
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002446 /** {@hide} */
2447 public AccountAndUser[] getAllAccounts() {
2448 final List<UserInfo> users = getUserManager().getUsers();
2449 final int[] userIds = new int[users.size()];
2450 for (int i = 0; i < userIds.length; i++) {
2451 userIds[i] = users.get(i).id;
2452 }
2453 return getAccounts(userIds);
2454 }
2455
2456 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002457 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002458 for (int userId : userIds) {
2459 UserAccounts userAccounts = getUserAccounts(userId);
2460 if (userAccounts == null) continue;
2461 synchronized (userAccounts.cacheLock) {
2462 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2463 Binder.getCallingUid(), null);
2464 for (int a = 0; a < accounts.length; a++) {
2465 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07002466 }
2467 }
2468 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002469
2470 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2471 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002472 }
2473
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002474 @Override
2475 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002476 return getAccountsAsUser(type, userId, null, -1);
2477 }
2478
2479 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
2480 int packageUid) {
2481 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002482 // Only allow the system process to read accounts of other users
2483 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002484 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002485 && mContext.checkCallingOrSelfPermission(
2486 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2487 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002488 throw new SecurityException("User " + UserHandle.getCallingUserId()
2489 + " trying to get account for " + userId);
2490 }
2491
Fred Quintana56285a62010-12-02 14:20:51 -08002492 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2493 Log.v(TAG, "getAccounts: accountType " + type
2494 + ", caller's uid " + Binder.getCallingUid()
2495 + ", pid " + Binder.getCallingPid());
2496 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002497 // If the original calling app was using the framework account chooser activity, we'll
2498 // be passed in the original caller's uid here, which is what should be used for filtering.
2499 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2500 callingUid = packageUid;
2501 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002502 checkReadAccountsPermission();
2503 long identityToken = clearCallingIdentity();
2504 try {
Simranjit Singh Kohli6a184872015-05-19 10:58:01 -07002505 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002506 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002507 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002508 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002509 } finally {
2510 restoreCallingIdentity(identityToken);
2511 }
2512 }
2513
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002514 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002515 public boolean addSharedAccountAsUser(Account account, int userId) {
2516 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002517 UserAccounts accounts = getUserAccounts(userId);
2518 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002519 ContentValues values = new ContentValues();
2520 values.put(ACCOUNTS_NAME, account.name);
2521 values.put(ACCOUNTS_TYPE, account.type);
2522 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2523 new String[] {account.name, account.type});
2524 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2525 if (accountId < 0) {
2526 Log.w(TAG, "insertAccountIntoDatabase: " + account
2527 + ", skipping the DB insert failed");
2528 return false;
2529 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002530 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002531 return true;
2532 }
2533
2534 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002535 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
2536 userId = handleIncomingUser(userId);
2537 UserAccounts accounts = getUserAccounts(userId);
2538 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002539 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002540 final ContentValues values = new ContentValues();
2541 values.put(ACCOUNTS_NAME, newName);
2542 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
2543 int r = db.update(
2544 TABLE_SHARED_ACCOUNTS,
2545 values,
2546 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2547 new String[] { account.name, account.type });
2548 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002549 int callingUid = getCallingUid();
2550 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
2551 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002552 // Recursively rename the account.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002553 renameAccountInternal(accounts, account, newName, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002554 }
2555 return r > 0;
2556 }
2557
2558 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002559 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002560 return removeSharedAccountAsUser(account, userId, getCallingUid());
2561 }
2562
2563 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08002564 userId = handleIncomingUser(userId);
2565 UserAccounts accounts = getUserAccounts(userId);
2566 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002567 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002568 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2569 new String[] {account.name, account.type});
2570 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002571 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
2572 sharedTableAccountId, accounts, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002573 removeAccountInternal(accounts, account);
2574 }
2575 return r > 0;
2576 }
2577
2578 @Override
2579 public Account[] getSharedAccountsAsUser(int userId) {
2580 userId = handleIncomingUser(userId);
2581 UserAccounts accounts = getUserAccounts(userId);
2582 ArrayList<Account> accountList = new ArrayList<Account>();
2583 Cursor cursor = null;
2584 try {
2585 cursor = accounts.openHelper.getReadableDatabase()
2586 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2587 null, null, null, null, null);
2588 if (cursor != null && cursor.moveToFirst()) {
2589 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2590 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2591 do {
2592 accountList.add(new Account(cursor.getString(nameIndex),
2593 cursor.getString(typeIndex)));
2594 } while (cursor.moveToNext());
2595 }
2596 } finally {
2597 if (cursor != null) {
2598 cursor.close();
2599 }
2600 }
2601 Account[] accountArray = new Account[accountList.size()];
2602 accountList.toArray(accountArray);
2603 return accountArray;
2604 }
2605
2606 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002607 public Account[] getAccounts(String type) {
2608 return getAccountsAsUser(type, UserHandle.getCallingUserId());
2609 }
2610
Amith Yamasani27db4682013-03-30 17:07:47 -07002611 @Override
2612 public Account[] getAccountsForPackage(String packageName, int uid) {
2613 int callingUid = Binder.getCallingUid();
2614 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2615 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2616 + callingUid + " with uid=" + uid);
2617 }
2618 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
2619 }
2620
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002621 @Override
2622 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
2623 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
2624 int packageUid = -1;
2625 try {
2626 packageUid = AppGlobals.getPackageManager().getPackageUid(
2627 packageName, UserHandle.getCallingUserId());
2628 } catch (RemoteException re) {
2629 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2630 return new Account[0];
2631 }
2632 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
2633 }
2634
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002635 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002636 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07002637 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08002638 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2639 Log.v(TAG, "getAccounts: accountType " + type
2640 + ", response " + response
2641 + ", features " + stringArrayToString(features)
2642 + ", caller's uid " + Binder.getCallingUid()
2643 + ", pid " + Binder.getCallingPid());
2644 }
Fred Quintana382601f2010-03-25 12:25:10 -07002645 if (response == null) throw new IllegalArgumentException("response is null");
2646 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002647 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002648 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002649 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07002650 long identityToken = clearCallingIdentity();
2651 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002652 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002653 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002654 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002655 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002656 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002657 Bundle result = new Bundle();
2658 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2659 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002660 return;
2661 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002662 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
2663 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002664 } finally {
2665 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002666 }
2667 }
2668
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002669 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
2670 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
2671 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
2672 try {
2673 if (cursor.moveToNext()) {
2674 return cursor.getLong(0);
2675 }
2676 return -1;
2677 } finally {
2678 cursor.close();
2679 }
2680 }
2681
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002682 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002683 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002684 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002685 try {
2686 if (cursor.moveToNext()) {
2687 return cursor.getLong(0);
2688 }
2689 return -1;
2690 } finally {
2691 cursor.close();
2692 }
2693 }
2694
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002695 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002696 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2697 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2698 new String[]{key}, null, null, null);
2699 try {
2700 if (cursor.moveToNext()) {
2701 return cursor.getLong(0);
2702 }
2703 return -1;
2704 } finally {
2705 cursor.close();
2706 }
2707 }
2708
Fred Quintanaa698f422009-04-08 19:14:54 -07002709 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002710 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002711 IAccountManagerResponse mResponse;
2712 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002713 final boolean mExpectActivityLaunch;
2714 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002715 final String mAccountName;
2716 // Indicates if we need to add auth details(like last credential time)
2717 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002718 // If set, we need to update the last authenticated time. This is
2719 // currently
2720 // used on
2721 // successful confirming credentials.
2722 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07002723
Fred Quintana33269202009-04-20 16:05:10 -07002724 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002725 private int mNumRequestContinued = 0;
2726 private int mNumErrors = 0;
2727
Fred Quintana60307342009-03-24 22:48:12 -07002728 IAccountAuthenticator mAuthenticator = null;
2729
Fred Quintana8570f742010-02-18 10:32:54 -08002730 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002731 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002732
Amith Yamasani04e0d262012-02-14 11:50:53 -08002733 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002734 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2735 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002736 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
2737 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
2738 }
2739
2740 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
2741 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2742 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07002743 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002744 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002745 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002746 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002747 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002748 mResponse = response;
2749 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002750 mExpectActivityLaunch = expectActivityLaunch;
2751 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002752 mAccountName = accountName;
2753 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002754 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002755
Fred Quintanaa698f422009-04-08 19:14:54 -07002756 synchronized (mSessions) {
2757 mSessions.put(toString(), this);
2758 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002759 if (response != null) {
2760 try {
2761 response.asBinder().linkToDeath(this, 0 /* flags */);
2762 } catch (RemoteException e) {
2763 mResponse = null;
2764 binderDied();
2765 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002766 }
Fred Quintana60307342009-03-24 22:48:12 -07002767 }
2768
Fred Quintanaa698f422009-04-08 19:14:54 -07002769 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002770 if (mResponse == null) {
2771 // this session has already been closed
2772 return null;
2773 }
Fred Quintana60307342009-03-24 22:48:12 -07002774 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002775 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002776 return response;
2777 }
2778
Fred Quintanaa698f422009-04-08 19:14:54 -07002779 private void close() {
2780 synchronized (mSessions) {
2781 if (mSessions.remove(toString()) == null) {
2782 // the session was already closed, so bail out now
2783 return;
2784 }
2785 }
2786 if (mResponse != null) {
2787 // stop listening for response deaths
2788 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2789
2790 // clear this so that we don't accidentally send any further results
2791 mResponse = null;
2792 }
2793 cancelTimeout();
2794 unbind();
2795 }
2796
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002797 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002798 public void binderDied() {
2799 mResponse = null;
2800 close();
2801 }
2802
2803 protected String toDebugString() {
2804 return toDebugString(SystemClock.elapsedRealtime());
2805 }
2806
2807 protected String toDebugString(long now) {
2808 return "Session: expectLaunch " + mExpectActivityLaunch
2809 + ", connected " + (mAuthenticator != null)
2810 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2811 + "/" + mNumErrors + ")"
2812 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2813 }
2814
Fred Quintana60307342009-03-24 22:48:12 -07002815 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002816 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2817 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2818 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002819 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002820 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002821 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002822 }
2823 }
2824
2825 private void unbind() {
2826 if (mAuthenticator != null) {
2827 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002828 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002829 }
2830 }
2831
2832 public void scheduleTimeout() {
2833 mMessageHandler.sendMessageDelayed(
2834 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2835 }
2836
2837 public void cancelTimeout() {
2838 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2839 }
2840
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002841 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002842 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002843 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002844 try {
2845 run();
2846 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002847 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002848 "remote exception");
2849 }
Fred Quintana60307342009-03-24 22:48:12 -07002850 }
2851
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002852 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002853 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002854 mAuthenticator = null;
2855 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002856 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002857 try {
2858 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2859 "disconnected");
2860 } catch (RemoteException e) {
2861 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2862 Log.v(TAG, "Session.onServiceDisconnected: "
2863 + "caught RemoteException while responding", e);
2864 }
2865 }
Fred Quintana60307342009-03-24 22:48:12 -07002866 }
2867 }
2868
Fred Quintanab839afc2009-10-14 15:57:28 -07002869 public abstract void run() throws RemoteException;
2870
Fred Quintana60307342009-03-24 22:48:12 -07002871 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002872 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002873 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002874 try {
2875 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2876 "timeout");
2877 } catch (RemoteException e) {
2878 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2879 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2880 e);
2881 }
2882 }
Fred Quintana60307342009-03-24 22:48:12 -07002883 }
2884 }
2885
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002886 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002887 public void onResult(Bundle result) {
2888 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002889 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002890 if (result != null) {
2891 boolean isSuccessfulConfirmCreds = result.getBoolean(
2892 AccountManager.KEY_BOOLEAN_RESULT, false);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002893 boolean isSuccessfulUpdateCreds =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002894 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
2895 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002896 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002897 // mUpdateLastAuthenticatedTime is true and the confirmRequest
2898 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07002899 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002900 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCreds);
2901 if (needUpdate || mAuthDetailsRequired) {
2902 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
2903 if (needUpdate && accountPresent) {
2904 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
2905 }
2906 if (mAuthDetailsRequired) {
2907 long lastAuthenticatedTime = -1;
2908 if (accountPresent) {
2909 lastAuthenticatedTime = DatabaseUtils.longForQuery(
2910 mAccounts.openHelper.getReadableDatabase(),
2911 "select " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
2912 + " from " +
2913 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
2914 + ACCOUNTS_TYPE + "=?",
2915 new String[] {
2916 mAccountName, mAccountType
2917 });
2918 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07002919 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002920 lastAuthenticatedTime);
2921 }
2922 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002923 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002924 if (result != null
2925 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2926 /*
2927 * The Authenticator API allows third party authenticators to
2928 * supply arbitrary intents to other apps that they can run,
2929 * this can be very bad when those apps are in the system like
2930 * the System Settings.
2931 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002932 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07002933 long bid = Binder.clearCallingIdentity();
2934 try {
2935 PackageManager pm = mContext.getPackageManager();
2936 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2937 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2938 if (PackageManager.SIGNATURE_MATCH !=
2939 pm.checkSignatures(authenticatorUid, targetUid)) {
2940 throw new SecurityException(
2941 "Activity to be started with KEY_INTENT must " +
2942 "share Authenticator's signatures");
2943 }
2944 } finally {
2945 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002946 }
2947 }
2948 if (result != null
2949 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002950 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2951 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002952 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2953 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002954 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2955 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002956 }
Fred Quintana60307342009-03-24 22:48:12 -07002957 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002958 IAccountManagerResponse response;
2959 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002960 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002961 response = mResponse;
2962 } else {
2963 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002964 }
Fred Quintana60307342009-03-24 22:48:12 -07002965 if (response != null) {
2966 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002967 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002968 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2969 Log.v(TAG, getClass().getSimpleName()
2970 + " calling onError() on response " + response);
2971 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002972 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002973 "null bundle returned");
2974 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002975 if (mStripAuthTokenFromResult) {
2976 result.remove(AccountManager.KEY_AUTHTOKEN);
2977 }
Fred Quintana56285a62010-12-02 14:20:51 -08002978 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2979 Log.v(TAG, getClass().getSimpleName()
2980 + " calling onResult() on response " + response);
2981 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002982 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
2983 (intent == null)) {
2984 // All AccountManager error codes are greater than 0
2985 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
2986 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2987 } else {
2988 response.onResult(result);
2989 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002990 }
Fred Quintana60307342009-03-24 22:48:12 -07002991 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002992 // if the caller is dead then there is no one to care about remote exceptions
2993 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2994 Log.v(TAG, "failure while notifying response", e);
2995 }
Fred Quintana60307342009-03-24 22:48:12 -07002996 }
2997 }
2998 }
Fred Quintana60307342009-03-24 22:48:12 -07002999
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003000 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003001 public void onRequestContinued() {
3002 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003003 }
3004
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003005 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003006 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003007 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003008 IAccountManagerResponse response = getResponseAndClose();
3009 if (response != null) {
3010 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003011 Log.v(TAG, getClass().getSimpleName()
3012 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003013 }
3014 try {
3015 response.onError(errorCode, errorMessage);
3016 } catch (RemoteException e) {
3017 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3018 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3019 }
3020 }
3021 } else {
3022 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3023 Log.v(TAG, "Session.onError: already closed");
3024 }
Fred Quintana60307342009-03-24 22:48:12 -07003025 }
3026 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003027
3028 /**
3029 * find the component name for the authenticator and initiate a bind
3030 * if no authenticator or the bind fails then return false, otherwise return true
3031 */
3032 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003033 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3034 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3035 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003036 if (authenticatorInfo == null) {
3037 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3038 Log.v(TAG, "there is no authenticator for " + authenticatorType
3039 + ", bailing out");
3040 }
3041 return false;
3042 }
3043
3044 Intent intent = new Intent();
3045 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3046 intent.setComponent(authenticatorInfo.componentName);
3047 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3048 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3049 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003050 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
3051 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003052 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3053 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3054 }
3055 return false;
3056 }
3057
3058
3059 return true;
3060 }
Fred Quintana60307342009-03-24 22:48:12 -07003061 }
3062
3063 private class MessageHandler extends Handler {
3064 MessageHandler(Looper looper) {
3065 super(looper);
3066 }
Costin Manolache3348f142009-09-29 18:58:36 -07003067
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003068 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003069 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07003070 switch (msg.what) {
3071 case MESSAGE_TIMED_OUT:
3072 Session session = (Session)msg.obj;
3073 session.onTimedOut();
3074 break;
3075
Amith Yamasani5be347b2013-03-31 17:44:31 -07003076 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00003077 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07003078 break;
3079
Fred Quintana60307342009-03-24 22:48:12 -07003080 default:
3081 throw new IllegalStateException("unhandled message: " + msg.what);
3082 }
3083 }
3084 }
3085
Amith Yamasani04e0d262012-02-14 11:50:53 -08003086 private static String getDatabaseName(int userId) {
3087 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07003088 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003089 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07003090 // Migrate old file, if it exists, to the new location.
3091 // Make sure the new file doesn't already exist. A dummy file could have been
3092 // accidentally created in the old location, causing the new one to become corrupted
3093 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08003094 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07003095 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07003096 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07003097 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07003098 if (!userDir.exists()) {
3099 if (!userDir.mkdirs()) {
3100 throw new IllegalStateException("User dir cannot be created: " + userDir);
3101 }
3102 }
3103 if (!oldFile.renameTo(databaseFile)) {
3104 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
3105 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003106 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003107 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003108 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08003109 }
3110
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003111 private static class DebugDbHelper{
3112 private DebugDbHelper() {
3113 }
3114
3115 private static String TABLE_DEBUG = "debug_table";
3116
3117 // Columns for the table
3118 private static String ACTION_TYPE = "action_type";
3119 private static String TIMESTAMP = "time";
3120 private static String CALLER_UID = "caller_uid";
3121 private static String TABLE_NAME = "table_name";
3122 private static String KEY = "primary_key";
3123
3124 // These actions correspond to the occurrence of real actions. Since
3125 // these are called by the authenticators, the uid associated will be
3126 // of the authenticator.
3127 private static String ACTION_SET_PASSWORD = "action_set_password";
3128 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
3129 private static String ACTION_ACCOUNT_ADD = "action_account_add";
3130 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
3131 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
3132 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
3133
3134 // These actions don't necessarily correspond to any action on
3135 // accountDb taking place. As an example, there might be a request for
3136 // addingAccount, which might not lead to addition of account on grounds
3137 // of bad authentication. We will still be logging it to keep track of
3138 // who called.
3139 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
3140 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
3141 private static String ACTION_CALLED_ACCOUNT_RENAME = "action_called_account_rename";
3142
3143 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3144
3145 private static String UPDATE_WHERE_CLAUSE = KEY + "=?";
3146
3147 private static void createDebugTable(SQLiteDatabase db) {
3148 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
3149 + ACCOUNTS_ID + " INTEGER,"
3150 + ACTION_TYPE + " TEXT NOT NULL, "
3151 + TIMESTAMP + " DATETIME,"
3152 + CALLER_UID + " INTEGER NOT NULL,"
3153 + TABLE_NAME + " TEXT NOT NULL,"
3154 + KEY + " INTEGER PRIMARY KEY)");
3155 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
3156 }
3157 }
3158
3159 private void logRecord(UserAccounts accounts, String action, String tableName) {
3160 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3161 logRecord(db, action, tableName, -1, accounts);
3162 }
3163
3164 /*
3165 * This function receives an opened writable database.
3166 */
3167 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3168 UserAccounts userAccount) {
3169 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
3170 }
3171
3172 /*
3173 * This function receives an opened writable database.
3174 */
3175 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3176 UserAccounts userAccount, int callingUid) {
3177 SQLiteStatement logStatement = userAccount.statementForLogging;
3178 logStatement.bindLong(1, accountId);
3179 logStatement.bindString(2, action);
3180 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
3181 logStatement.bindLong(4, callingUid);
3182 logStatement.bindString(5, tableName);
3183 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
3184 logStatement.execute();
3185 logStatement.clearBindings();
3186 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
3187 % MAX_DEBUG_DB_SIZE;
3188 }
3189
3190 /*
3191 * This should only be called once to compile the sql statement for logging
3192 * and to find the insertion point.
3193 */
3194 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
3195 UserAccounts userAccount) {
3196 // Initialize the count if not done earlier.
3197 int size = (int) getDebugTableRowCount(db);
3198 if (size >= MAX_DEBUG_DB_SIZE) {
3199 // Table is full, and we need to find the point where to insert.
3200 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
3201 } else {
3202 userAccount.debugDbInsertionPoint = size;
3203 }
3204 compileSqlStatementForLogging(db, userAccount);
3205 }
3206
3207 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
3208 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
3209 + " VALUES (?,?,?,?,?,?)";
3210 userAccount.statementForLogging = db.compileStatement(sql);
3211 }
3212
3213 private long getDebugTableRowCount(SQLiteDatabase db) {
3214 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
3215 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3216 }
3217
3218 /*
3219 * Finds the row key where the next insertion should take place. This should
3220 * be invoked only if the table has reached its full capacity.
3221 */
3222 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
3223 // This query finds the smallest timestamp value (and if 2 records have
3224 // same timestamp, the choose the lower id).
3225 String queryCountDebugDbRows = new StringBuilder()
3226 .append("SELECT ").append(DebugDbHelper.KEY)
3227 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
3228 .append(" ORDER BY ")
3229 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
3230 .append(" LIMIT 1")
3231 .toString();
3232 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3233 }
3234
Amith Yamasani04e0d262012-02-14 11:50:53 -08003235 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003236
Amith Yamasani04e0d262012-02-14 11:50:53 -08003237 public DatabaseHelper(Context context, int userId) {
3238 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07003239 }
3240
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003241 /**
3242 * This call needs to be made while the mCacheLock is held. The way to
3243 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
3244 * @param db The database.
3245 */
Fred Quintana60307342009-03-24 22:48:12 -07003246 @Override
3247 public void onCreate(SQLiteDatabase db) {
3248 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
3249 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3250 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3251 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3252 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003253 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003254 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
Fred Quintana60307342009-03-24 22:48:12 -07003255 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3256
3257 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
3258 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3259 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3260 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
3261 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
3262 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
3263
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003264 createGrantsTable(db);
3265
Fred Quintana60307342009-03-24 22:48:12 -07003266 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
3267 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3268 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
3269 + EXTRAS_KEY + " TEXT NOT NULL, "
3270 + EXTRAS_VALUE + " TEXT, "
3271 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
3272
3273 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
3274 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
3275 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07003276
Amith Yamasani67df64b2012-12-14 12:09:36 -08003277 createSharedAccountsTable(db);
3278
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003279 createAccountsDeletionTrigger(db);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003280
3281 DebugDbHelper.createDebugTable(db);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003282 }
3283
Amith Yamasani67df64b2012-12-14 12:09:36 -08003284 private void createSharedAccountsTable(SQLiteDatabase db) {
3285 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
3286 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3287 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3288 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3289 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3290 }
3291
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003292 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
3293 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
3294 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
3295 }
3296
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003297 private void addOldAccountNameColumn(SQLiteDatabase db) {
3298 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
3299 }
3300
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003301 private void addDebugTable(SQLiteDatabase db) {
3302 DebugDbHelper.createDebugTable(db);
3303 }
3304
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003305 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003306 db.execSQL(""
3307 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
3308 + " BEGIN"
3309 + " DELETE FROM " + TABLE_AUTHTOKENS
3310 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
3311 + " DELETE FROM " + TABLE_EXTRAS
3312 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003313 + " DELETE FROM " + TABLE_GRANTS
3314 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07003315 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07003316 }
3317
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003318 private void createGrantsTable(SQLiteDatabase db) {
3319 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
3320 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3321 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
3322 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
3323 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
3324 + "," + GRANTS_GRANTEE_UID + "))");
3325 }
3326
Fred Quintana60307342009-03-24 22:48:12 -07003327 @Override
3328 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003329 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07003330
Fred Quintanaa698f422009-04-08 19:14:54 -07003331 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003332 // no longer need to do anything since the work is done
3333 // when upgrading from version 2
3334 oldVersion++;
3335 }
3336
3337 if (oldVersion == 2) {
3338 createGrantsTable(db);
3339 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
3340 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07003341 oldVersion++;
3342 }
Costin Manolache3348f142009-09-29 18:58:36 -07003343
3344 if (oldVersion == 3) {
3345 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
3346 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
3347 oldVersion++;
3348 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003349
3350 if (oldVersion == 4) {
3351 createSharedAccountsTable(db);
3352 oldVersion++;
3353 }
3354
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003355 if (oldVersion == 5) {
3356 addOldAccountNameColumn(db);
3357 oldVersion++;
3358 }
3359
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003360 if (oldVersion == 6) {
3361 addLastSuccessfullAuthenticatedTimeColumn(db);
3362 oldVersion++;
3363 }
3364
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003365 if (oldVersion == 7) {
3366 addDebugTable(db);
3367 oldVersion++;
3368 }
3369
Amith Yamasani67df64b2012-12-14 12:09:36 -08003370 if (oldVersion != newVersion) {
3371 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
3372 }
Fred Quintana60307342009-03-24 22:48:12 -07003373 }
3374
3375 @Override
3376 public void onOpen(SQLiteDatabase db) {
3377 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
3378 }
3379 }
3380
Fred Quintana60307342009-03-24 22:48:12 -07003381 public IBinder onBind(Intent intent) {
3382 return asBinder();
3383 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003384
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003385 /**
3386 * Searches array of arguments for the specified string
3387 * @param args array of argument strings
3388 * @param value value to search for
3389 * @return true if the value is contained in the array
3390 */
3391 private static boolean scanArgs(String[] args, String value) {
3392 if (args != null) {
3393 for (String arg : args) {
3394 if (value.equals(arg)) {
3395 return true;
3396 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003397 }
3398 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003399 return false;
3400 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003401
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003402 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003403 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07003404 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3405 != PackageManager.PERMISSION_GRANTED) {
3406 fout.println("Permission Denial: can't dump AccountsManager from from pid="
3407 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3408 + " without permission " + android.Manifest.permission.DUMP);
3409 return;
3410 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003411 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003412 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07003413
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003414 final List<UserInfo> users = getUserManager().getUsers();
3415 for (UserInfo user : users) {
3416 ipw.println("User " + user + ":");
3417 ipw.increaseIndent();
3418 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
3419 ipw.println();
3420 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08003421 }
3422 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003423
Amith Yamasani04e0d262012-02-14 11:50:53 -08003424 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
3425 String[] args, boolean isCheckinRequest) {
3426 synchronized (userAccounts.cacheLock) {
3427 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003428
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003429 if (isCheckinRequest) {
3430 // This is a checkin request. *Only* upload the account types and the count of each.
3431 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
3432 null, null, ACCOUNTS_TYPE, null, null);
3433 try {
3434 while (cursor.moveToNext()) {
3435 // print type,count
3436 fout.println(cursor.getString(0) + "," + cursor.getString(1));
3437 }
3438 } finally {
3439 if (cursor != null) {
3440 cursor.close();
3441 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003442 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003443 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003444 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07003445 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003446 fout.println("Accounts: " + accounts.length);
3447 for (Account account : accounts) {
3448 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003449 }
Fred Quintana307da1a2010-01-21 14:24:20 -08003450
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003451 // Add debug information.
3452 fout.println();
3453 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
3454 null, null, null, null, DebugDbHelper.TIMESTAMP);
3455 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
3456 fout.println("Accounts History");
3457 try {
3458 while (cursor.moveToNext()) {
3459 // print type,count
3460 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
3461 cursor.getString(2) + "," + cursor.getString(3) + ","
3462 + cursor.getString(4) + "," + cursor.getString(5));
3463 }
3464 } finally {
3465 cursor.close();
3466 }
3467
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003468 fout.println();
3469 synchronized (mSessions) {
3470 final long now = SystemClock.elapsedRealtime();
3471 fout.println("Active Sessions: " + mSessions.size());
3472 for (Session session : mSessions.values()) {
3473 fout.println(" " + session.toDebugString(now));
3474 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003475 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003476
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003477 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003478 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003479 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003480 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003481 }
3482
Amith Yamasani04e0d262012-02-14 11:50:53 -08003483 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07003484 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003485 long identityToken = clearCallingIdentity();
3486 try {
3487 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3488 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
3489 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003490
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003491 if (intent.getComponent() != null &&
3492 GrantCredentialsPermissionActivity.class.getName().equals(
3493 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003494 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003495 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003496 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07003497 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003498 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
3499 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003500 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003501 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07003502 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003503 contextForUser.getText(R.string.notification_title).toString();
Alan Viverette4a357cd2015-03-18 18:37:18 -07003504 n.color = contextForUser.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003505 com.android.internal.R.color.system_notification_accent_color);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003506 n.setLatestEventInfo(contextForUser,
Fred Quintana33f889a2009-09-14 17:31:26 -07003507 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07003508 message, PendingIntent.getActivityAsUser(
3509 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003510 null, user));
3511 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003512 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003513 } finally {
3514 restoreCallingIdentity(identityToken);
3515 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003516 }
3517
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003518 protected void installNotification(final int notificationId, final Notification n,
3519 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08003520 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003521 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08003522 }
3523
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003524 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003525 long identityToken = clearCallingIdentity();
3526 try {
3527 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003528 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003529 } finally {
3530 restoreCallingIdentity(identityToken);
3531 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003532 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003533
Fred Quintanab38eb142010-02-24 13:40:54 -08003534 /** Succeeds if any of the specified permissions are granted. */
3535 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003536 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08003537
3538 for (String perm : permissions) {
3539 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
3540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003541 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08003542 }
3543 return;
3544 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003545 }
Fred Quintanab38eb142010-02-24 13:40:54 -08003546 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08003547 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08003548 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003549 }
3550
Amith Yamasani67df64b2012-12-14 12:09:36 -08003551 private int handleIncomingUser(int userId) {
3552 try {
3553 return ActivityManagerNative.getDefault().handleIncomingUser(
3554 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
3555 } catch (RemoteException re) {
3556 // Shouldn't happen, local.
3557 }
3558 return userId;
3559 }
3560
Christopher Tateccbf84f2013-05-08 15:25:41 -07003561 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003562 final int callingUserId = UserHandle.getUserId(callingUid);
3563
3564 final PackageManager userPackageManager;
3565 try {
3566 userPackageManager = mContext.createPackageContextAsUser(
3567 "android", 0, new UserHandle(callingUserId)).getPackageManager();
3568 } catch (NameNotFoundException e) {
3569 return false;
3570 }
3571
3572 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07003573 for (String name : packages) {
3574 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003575 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08003576 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003577 && (packageInfo.applicationInfo.privateFlags
3578 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07003579 return true;
3580 }
3581 } catch (PackageManager.NameNotFoundException e) {
3582 return false;
3583 }
3584 }
3585 return false;
3586 }
3587
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003588 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07003589 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07003590 final boolean fromAuthenticator = account != null
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003591 && hasAuthenticatorUid(account.type, callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07003592 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08003593 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003594 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3595 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08003596 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003597 + ": is authenticator? " + fromAuthenticator
3598 + ", has explicit permission? " + hasExplicitGrants);
3599 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07003600 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003601 }
3602
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003603 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003604 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003605 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003606 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003607 if (serviceInfo.type.type.equals(accountType)) {
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003608 return (serviceInfo.uid == callingUid) ||
3609 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
3610 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003611 }
3612 }
3613 return false;
3614 }
3615
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003616 private boolean isAccountPresentForCaller(String accountName, String accountType) {
3617 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
3618 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
3619 if (account.name.equals(accountName)) {
3620 return true;
3621 }
3622 }
3623 }
3624 return false;
3625 }
3626
Amith Yamasani04e0d262012-02-14 11:50:53 -08003627 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
3628 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003629 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003630 return true;
3631 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003632 UserAccounts accounts = getUserAccountsForCaller();
3633 synchronized (accounts.cacheLock) {
3634 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3635 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003636 account.name, account.type};
3637 final boolean permissionGranted =
3638 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
3639 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
3640 // TODO: Skip this check when running automated tests. Replace this
3641 // with a more general solution.
3642 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08003643 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003644 + " but ignoring since device is in test harness.");
3645 return true;
3646 }
3647 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003648 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003649 }
3650
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003651 private void checkCallingUidAgainstAuthenticator(Account account) {
3652 final int uid = Binder.getCallingUid();
3653 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
3654 String msg = "caller uid " + uid + " is different than the authenticator's uid";
Carlos Valdiviaffb46022015-06-08 19:07:54 -07003655 Log.w(TAG, msg);
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003656 throw new SecurityException(msg);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07003657 }
3658 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003659 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
Carlos Valdiviaffb46022015-06-08 19:07:54 -07003660 }
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003661 }
3662
3663 private void checkAuthenticateAccountsPermission(Account account) {
3664 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
3665 checkCallingUidAgainstAuthenticator(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003666 }
3667
3668 private void checkReadAccountsPermission() {
3669 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
3670 }
3671
Carlos Valdiviadcddc472015-06-11 20:04:04 +00003672 private void checkManageAccountsPermission() {
3673 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
3674 }
3675
3676 private void checkManageAccountsOrUseCredentialsPermissions() {
3677 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
3678 Manifest.permission.USE_CREDENTIALS);
3679 }
3680
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003681 private boolean canUserModifyAccounts(int userId) {
3682 if (getUserManager().getUserRestrictions(new UserHandle(userId))
3683 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
3684 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003685 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003686 return true;
3687 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003688
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003689 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003690 DevicePolicyManager dpm = (DevicePolicyManager) mContext
3691 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003692 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02003693 if (typesArray == null) {
3694 return true;
3695 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003696 for (String forbiddenType : typesArray) {
3697 if (forbiddenType.equals(accountType)) {
3698 return false;
3699 }
3700 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003701 return true;
3702 }
3703
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003704 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07003705 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
3706 throws RemoteException {
3707 final int callingUid = getCallingUid();
3708
Amith Yamasani27db4682013-03-30 17:07:47 -07003709 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07003710 throw new SecurityException();
3711 }
3712
3713 if (value) {
3714 grantAppPermission(account, authTokenType, uid);
3715 } else {
3716 revokeAppPermission(account, authTokenType, uid);
3717 }
3718 }
3719
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003720 /**
3721 * Allow callers with the given uid permission to get credentials for account/authTokenType.
3722 * <p>
3723 * Although this is public it can only be accessed via the AccountManagerService object
3724 * which is in the system. This means we don't need to protect it with permissions.
3725 * @hide
3726 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003727 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003728 if (account == null || authTokenType == null) {
3729 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003730 return;
3731 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003732 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003733 synchronized (accounts.cacheLock) {
3734 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003735 db.beginTransaction();
3736 try {
3737 long accountId = getAccountIdLocked(db, account);
3738 if (accountId >= 0) {
3739 ContentValues values = new ContentValues();
3740 values.put(GRANTS_ACCOUNTS_ID, accountId);
3741 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
3742 values.put(GRANTS_GRANTEE_UID, uid);
3743 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
3744 db.setTransactionSuccessful();
3745 }
3746 } finally {
3747 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003748 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003749 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3750 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003751 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003752 }
3753
3754 /**
3755 * Don't allow callers with the given uid permission to get credentials for
3756 * account/authTokenType.
3757 * <p>
3758 * Although this is public it can only be accessed via the AccountManagerService object
3759 * which is in the system. This means we don't need to protect it with permissions.
3760 * @hide
3761 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003762 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003763 if (account == null || authTokenType == null) {
3764 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003765 return;
3766 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003767 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003768 synchronized (accounts.cacheLock) {
3769 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003770 db.beginTransaction();
3771 try {
3772 long accountId = getAccountIdLocked(db, account);
3773 if (accountId >= 0) {
3774 db.delete(TABLE_GRANTS,
3775 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
3776 + GRANTS_GRANTEE_UID + "=?",
3777 new String[]{String.valueOf(accountId), authTokenType,
3778 String.valueOf(uid)});
3779 db.setTransactionSuccessful();
3780 }
3781 } finally {
3782 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003783 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003784 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3785 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003786 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003787 }
Fred Quintana56285a62010-12-02 14:20:51 -08003788
3789 static final private String stringArrayToString(String[] value) {
3790 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
3791 }
3792
Amith Yamasani04e0d262012-02-14 11:50:53 -08003793 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
3794 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003795 if (oldAccountsForType != null) {
3796 ArrayList<Account> newAccountsList = new ArrayList<Account>();
3797 for (Account curAccount : oldAccountsForType) {
3798 if (!curAccount.equals(account)) {
3799 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003800 }
3801 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003802 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003803 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003804 } else {
3805 Account[] newAccountsForType = new Account[newAccountsList.size()];
3806 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003807 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003808 }
Fred Quintana56285a62010-12-02 14:20:51 -08003809 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003810 accounts.userDataCache.remove(account);
3811 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003812 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003813 }
3814
3815 /**
3816 * This assumes that the caller has already checked that the account is not already present.
3817 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08003818 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
3819 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003820 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
3821 Account[] newAccountsForType = new Account[oldLength + 1];
3822 if (accountsForType != null) {
3823 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08003824 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003825 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003826 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08003827 }
3828
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003829 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07003830 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003831 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07003832 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003833 return unfiltered;
3834 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003835 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
3836 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003837 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003838 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003839 // otherwise return non-shared accounts only.
3840 // This might be a temporary way to specify a whitelist
3841 String whiteList = mContext.getResources().getString(
3842 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
3843 for (String packageName : packages) {
3844 if (whiteList.contains(";" + packageName + ";")) {
3845 return unfiltered;
3846 }
3847 }
3848 ArrayList<Account> allowed = new ArrayList<Account>();
3849 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
3850 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003851 String requiredAccountType = "";
3852 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07003853 // If there's an explicit callingPackage specified, check if that package
3854 // opted in to see restricted accounts.
3855 if (callingPackage != null) {
3856 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003857 if (pi != null && pi.restrictedAccountType != null) {
3858 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07003859 }
3860 } else {
3861 // Otherwise check if the callingUid has a package that has opted in
3862 for (String packageName : packages) {
3863 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
3864 if (pi != null && pi.restrictedAccountType != null) {
3865 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07003866 break;
3867 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003868 }
3869 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003870 } catch (NameNotFoundException nnfe) {
3871 }
3872 for (Account account : unfiltered) {
3873 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003874 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003875 } else {
3876 boolean found = false;
3877 for (Account shared : sharedAccounts) {
3878 if (shared.equals(account)) {
3879 found = true;
3880 break;
3881 }
3882 }
3883 if (!found) {
3884 allowed.add(account);
3885 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003886 }
3887 }
3888 Account[] filtered = new Account[allowed.size()];
3889 allowed.toArray(filtered);
3890 return filtered;
3891 } else {
3892 return unfiltered;
3893 }
3894 }
3895
Amith Yamasani27db4682013-03-30 17:07:47 -07003896 /*
3897 * packageName can be null. If not null, it should be used to filter out restricted accounts
3898 * that the package is not allowed to access.
3899 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003900 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07003901 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003902 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003903 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003904 if (accounts == null) {
3905 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08003906 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003907 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07003908 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003909 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003910 } else {
3911 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003912 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003913 totalLength += accounts.length;
3914 }
3915 if (totalLength == 0) {
3916 return EMPTY_ACCOUNT_ARRAY;
3917 }
3918 Account[] accounts = new Account[totalLength];
3919 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003920 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003921 System.arraycopy(accountsOfType, 0, accounts, totalLength,
3922 accountsOfType.length);
3923 totalLength += accountsOfType.length;
3924 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003925 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003926 }
3927 }
3928
Amith Yamasani04e0d262012-02-14 11:50:53 -08003929 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3930 Account account, String key, String value) {
3931 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003932 if (userDataForAccount == null) {
3933 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003934 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003935 }
3936 if (value == null) {
3937 userDataForAccount.remove(key);
3938 } else {
3939 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003940 }
3941 }
3942
Carlos Valdivia91979be2015-05-22 14:11:35 -07003943 protected String readCachedTokenInternal(
3944 UserAccounts accounts,
3945 Account account,
3946 String tokenType,
3947 String callingPackage,
3948 byte[] pkgSigDigest) {
3949 synchronized (accounts.cacheLock) {
3950 TokenCache cache = getTokenCacheForAccountLocked(accounts, account);
3951 return cache.get(tokenType, callingPackage, pkgSigDigest);
3952 }
3953 }
3954
Amith Yamasani04e0d262012-02-14 11:50:53 -08003955 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3956 Account account, String key, String value) {
3957 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003958 if (authTokensForAccount == null) {
3959 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003960 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003961 }
3962 if (value == null) {
3963 authTokensForAccount.remove(key);
3964 } else {
3965 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003966 }
3967 }
3968
Amith Yamasani04e0d262012-02-14 11:50:53 -08003969 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
3970 String authTokenType) {
3971 synchronized (accounts.cacheLock) {
3972 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003973 if (authTokensForAccount == null) {
3974 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003975 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003976 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003977 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003978 }
3979 return authTokensForAccount.get(authTokenType);
3980 }
3981 }
3982
Amith Yamasani04e0d262012-02-14 11:50:53 -08003983 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
3984 synchronized (accounts.cacheLock) {
3985 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003986 if (userDataForAccount == null) {
3987 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003988 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003989 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003990 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003991 }
3992 return userDataForAccount.get(key);
3993 }
3994 }
3995
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003996 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3997 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003998 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003999 Cursor cursor = db.query(TABLE_EXTRAS,
4000 COLUMNS_EXTRAS_KEY_AND_VALUE,
4001 SELECTION_USERDATA_BY_ACCOUNT,
4002 new String[]{account.name, account.type},
4003 null, null, null);
4004 try {
4005 while (cursor.moveToNext()) {
4006 final String tmpkey = cursor.getString(0);
4007 final String value = cursor.getString(1);
4008 userDataForAccount.put(tmpkey, value);
4009 }
4010 } finally {
4011 cursor.close();
4012 }
4013 return userDataForAccount;
4014 }
4015
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004016 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
4017 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004018 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004019 Cursor cursor = db.query(TABLE_AUTHTOKENS,
4020 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
4021 SELECTION_AUTHTOKENS_BY_ACCOUNT,
4022 new String[]{account.name, account.type},
4023 null, null, null);
4024 try {
4025 while (cursor.moveToNext()) {
4026 final String type = cursor.getString(0);
4027 final String authToken = cursor.getString(1);
4028 authTokensForAccount.put(type, authToken);
4029 }
4030 } finally {
4031 cursor.close();
4032 }
4033 return authTokensForAccount;
4034 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004035
Carlos Valdivia91979be2015-05-22 14:11:35 -07004036 protected TokenCache getTokenCacheForAccountLocked(UserAccounts accounts, Account account) {
4037 WeakReference<TokenCache> cacheRef = accounts.accountTokenCaches.get(account);
4038 TokenCache cache;
4039 if (cacheRef == null || (cache = cacheRef.get()) == null) {
4040 cache = new TokenCache();
4041 cacheRef = new WeakReference<>(cache);
4042 accounts.accountTokenCaches.put(account, cacheRef);
4043 }
4044 return cache;
4045 }
4046
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004047 private Context getContextForUser(UserHandle user) {
4048 try {
4049 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
4050 } catch (NameNotFoundException e) {
4051 // Default to mContext, not finding the package system is running as is unlikely.
4052 return mContext;
4053 }
4054 }
Fred Quintana60307342009-03-24 22:48:12 -07004055}