blob: 3315c89daa28bc8bc397e45edbfcac25f983e8fe [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;
90import java.nio.ByteBuffer;
91import java.nio.charset.Charset;
92import java.security.MessageDigest;
93import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070094import java.sql.Timestamp;
95import 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 Valdivia91979be2015-05-22 14:11:35 -0700103import 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");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700535 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)) {
621 Log.v(TAG, "getUserData: " + account
622 + ", key " + key
623 + ", caller's uid " + Binder.getCallingUid()
624 + ", pid " + Binder.getCallingPid());
625 }
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");
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700628 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
Fred Quintana56285a62010-12-02 14:20:51 -0800681 + ", caller's uid " + Binder.getCallingUid()
682 + ", pid " + Binder.getCallingPid());
683 }
Fred Quintana382601f2010-03-25 12:25:10 -0700684 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700685 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 }
764 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
1012 + ", caller's uid " + Binder.getCallingUid()
1013 + ", pid " + Binder.getCallingPid());
1014 }
1015 if (accountToRename == null) throw new IllegalArgumentException("account is null");
1016 checkAuthenticateAccountsPermission(accountToRename);
1017 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001018
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) {
Fred Quintana56285a62010-12-02 14:20:51 -08001128 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 }
Fred Quintana382601f2010-03-25 12:25:10 -07001134 if (response == null) throw new IllegalArgumentException("response is null");
1135 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001136 checkManageAccountsPermission();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001137 UserHandle user = Binder.getCallingUserHandle();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001138 UserAccounts accounts = getUserAccountsForCaller();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001139 int userId = Binder.getCallingUserHandle().getIdentifier();
1140 if (!canUserModifyAccounts(userId)) {
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001141 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001142 // TODO: This should be ERROR_CODE_USER_RESTRICTED instead. See http://b/16322768
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001143 response.onError(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
1144 "User cannot modify accounts");
1145 } catch (RemoteException re) {
1146 }
Amith Yamasani5934dbc2014-02-20 15:23:36 -08001147 return;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001148 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001149 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 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08001157
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001158 long identityToken = clearCallingIdentity();
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001159
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001160 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001161 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
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001171 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1172
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001173 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001174 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001175 } finally {
1176 restoreCallingIdentity(identityToken);
1177 }
1178 }
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
1186 + ", caller's uid " + Binder.getCallingUid()
1187 + ", 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);
1196 checkManageAccountsPermission();
1197
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
1243 + ", caller's uid " + Binder.getCallingUid()
1244 + ", pid " + Binder.getCallingPid());
1245 }
1246 if (account == null) throw new IllegalArgumentException("account is null");
1247 checkAuthenticateAccountsPermission(account);
1248
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");
Fred Quintanab38eb142010-02-24 13:40:54 -08001360 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
1496 + ", caller's uid " + Binder.getCallingUid()
1497 + ", 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");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001501 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
1516 + ", caller's uid " + Binder.getCallingUid()
1517 + ", 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");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001521 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
1535 + ", caller's uid " + Binder.getCallingUid()
1536 + ", pid " + Binder.getCallingPid());
1537 }
Fred Quintana382601f2010-03-25 12:25:10 -07001538 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001539 checkAuthenticateAccountsPermission(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001540 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001541 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
1599 + ", caller's uid " + Binder.getCallingUid()
1600 + ", pid " + Binder.getCallingPid());
1601 }
Fred Quintana382601f2010-03-25 12:25:10 -07001602 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001603 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001604 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001605
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
1620 + ", caller's uid " + Binder.getCallingUid()
1621 + ", 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");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001625 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
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001772 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);
1788 List<String> callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
1789 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
1790 String msg = String.format(
1791 "Uid %s is attempting to illegally masquerade as package %s!",
1792 callerUid,
1793 callerPkg);
1794 throw new SecurityException(msg);
1795 }
1796
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001797 // let authenticator know the identity of the caller
1798 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1799 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07001800
1801 // Distill the caller's package signatures into a single digest.
1802 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
1803
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001804 if (notifyOnAuthFailure) {
1805 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001806 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001807
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001808 long identityToken = clearCallingIdentity();
1809 try {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001810 // if the caller has permission, do the peek. otherwise go the more expensive
1811 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001812 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001813 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001814 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001815 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001816 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1817 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1818 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001819 onResult(response, result);
1820 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001821 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001822 }
1823
Carlos Valdivia91979be2015-05-22 14:11:35 -07001824 if (customTokens) {
1825 /*
1826 * Look up tokens in the new cache only if the loginOptions don't have parameters
1827 * outside of those expected to be injected by the AccountManager, e.g.
1828 * ANDORID_PACKAGE_NAME.
1829 */
1830 String token = readCachedTokenInternal(
1831 accounts,
1832 account,
1833 authTokenType,
1834 callerPkg,
1835 callerPkgSigDigest);
1836 if (token != null) {
1837 Bundle result = new Bundle();
1838 result.putString(AccountManager.KEY_AUTHTOKEN, token);
1839 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1840 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
1841 onResult(response, result);
1842 return;
1843 }
1844 }
1845
Amith Yamasani04e0d262012-02-14 11:50:53 -08001846 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001847 false /* stripAuthTokenFromResult */, account.name,
1848 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001849 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001850 protected String toDebugString(long now) {
1851 if (loginOptions != null) loginOptions.keySet();
1852 return super.toDebugString(now) + ", getAuthToken"
1853 + ", " + account
1854 + ", authTokenType " + authTokenType
1855 + ", loginOptions " + loginOptions
1856 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1857 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001858
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001859 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001860 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001861 // If the caller doesn't have permission then create and return the
1862 // "grant permission" intent instead of the "getAuthToken" intent.
1863 if (!permissionGranted) {
1864 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1865 } else {
1866 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1867 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001868 }
1869
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001870 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001871 public void onResult(Bundle result) {
1872 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001873 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001874 Intent intent = newGrantCredentialsPermissionIntent(account, callerUid,
1875 new AccountAuthenticatorResponse(this),
1876 authTokenType,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001877 result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001878 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001879 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001880 onResult(bundle);
1881 return;
1882 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001883 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001884 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001885 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1886 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001887 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001888 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001889 "the type and name should not be empty");
1890 return;
1891 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001892 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08001893 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001894 saveAuthTokenToDatabase(
1895 mAccounts,
1896 resultAccount,
1897 authTokenType,
1898 authToken);
1899 }
1900 long expiryMillis = result.getLong(
1901 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
1902 if (customTokens
1903 && expiryMillis > System.currentTimeMillis()) {
1904 saveCachedToken(
1905 mAccounts,
1906 account,
1907 callerPkg,
1908 callerPkgSigDigest,
1909 authTokenType,
1910 authToken,
1911 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08001912 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001913 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001914
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001915 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08001916 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001917 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001918 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07001919 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001920 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001921 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001922 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07001923 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001924 }.bind();
1925 } finally {
1926 restoreCallingIdentity(identityToken);
1927 }
Fred Quintana60307342009-03-24 22:48:12 -07001928 }
1929
Carlos Valdivia91979be2015-05-22 14:11:35 -07001930 private byte[] calculatePackageSignatureDigest(String callerPkg) {
1931 MessageDigest digester;
1932 try {
1933 digester = MessageDigest.getInstance("SHA-256");
1934 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
1935 callerPkg, PackageManager.GET_SIGNATURES);
1936 for (Signature sig : pkgInfo.signatures) {
1937 digester.update(sig.toByteArray());
1938 }
1939 } catch (NoSuchAlgorithmException x) {
1940 Log.wtf(TAG, "SHA-256 should be available", x);
1941 digester = null;
1942 } catch (NameNotFoundException e) {
1943 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
1944 digester = null;
1945 }
1946 return (digester == null) ? null : digester.digest();
1947 }
1948
Dianne Hackborn41203752012-08-31 14:05:51 -07001949 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
1950 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001951 int uid = intent.getIntExtra(
1952 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
1953 String authTokenType = intent.getStringExtra(
1954 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
1955 String authTokenLabel = intent.getStringExtra(
1956 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_LABEL);
1957
1958 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
1959 0 /* when */);
Eric Fischeree452ee2009-08-31 17:58:06 -07001960 final String titleAndSubtitle =
1961 mContext.getString(R.string.permission_request_notification_with_subtitle,
1962 account.name);
1963 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07001964 String title = titleAndSubtitle;
1965 String subtitle = "";
1966 if (index > 0) {
1967 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001968 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07001969 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001970 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01001971 Context contextForUser = getContextForUser(user);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001972 n.color = contextForUser.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001973 com.android.internal.R.color.system_notification_accent_color);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01001974 n.setLatestEventInfo(contextForUser, title, subtitle,
Dianne Hackborn41203752012-08-31 14:05:51 -07001975 PendingIntent.getActivityAsUser(mContext, 0, intent,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001976 PendingIntent.FLAG_CANCEL_CURRENT, null, user));
1977 installNotification(getCredentialPermissionNotificationId(
1978 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001979 }
1980
Costin Manolache5f383ad92010-12-02 16:44:46 -08001981 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
1982 AccountAuthenticatorResponse response, String authTokenType, String authTokenLabel) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001983
1984 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07001985 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08001986 // Since it was set in Eclair+ we can't change it without breaking apps using
1987 // the intent from a non-Activity context.
1988 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001989 intent.addCategory(
1990 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08001991
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001992 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001993 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
1994 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001995 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001996
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001997 return intent;
1998 }
1999
2000 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2001 int uid) {
2002 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002003 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002004 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002005 final Pair<Pair<Account, String>, Integer> key =
2006 new Pair<Pair<Account, String>, Integer>(
2007 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002008 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002009 if (id == null) {
2010 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002011 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002012 }
2013 }
2014 return id;
2015 }
2016
Amith Yamasani04e0d262012-02-14 11:50:53 -08002017 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002018 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002019 synchronized (accounts.signinRequiredNotificationIds) {
2020 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002021 if (id == null) {
2022 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002023 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002024 }
2025 }
2026 return id;
2027 }
2028
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002029 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002030 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002031 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002032 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08002033 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2034 Log.v(TAG, "addAccount: accountType " + accountType
2035 + ", response " + response
2036 + ", authTokenType " + authTokenType
2037 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2038 + ", expectActivityLaunch " + expectActivityLaunch
2039 + ", caller's uid " + Binder.getCallingUid()
2040 + ", pid " + Binder.getCallingPid());
2041 }
Fred Quintana382601f2010-03-25 12:25:10 -07002042 if (response == null) throw new IllegalArgumentException("response is null");
2043 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002044 checkManageAccountsPermission();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002045
Amith Yamasani71e6c692013-03-24 17:39:28 -07002046 // Is user disallowed from modifying accounts?
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002047 int userId = Binder.getCallingUserHandle().getIdentifier();
2048 if (!canUserModifyAccounts(userId)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002049 try {
2050 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2051 "User is not allowed to add an account!");
2052 } catch (RemoteException re) {
2053 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002054 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002055 return;
2056 }
2057 if (!canUserModifyAccountsForType(userId, accountType)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002058 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002059 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2060 "User cannot modify accounts of this type (policy).");
2061 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002062 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002063 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2064 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002065 return;
2066 }
2067
Amith Yamasani04e0d262012-02-14 11:50:53 -08002068 UserAccounts accounts = getUserAccountsForCaller();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002069 final int pid = Binder.getCallingPid();
2070 final int uid = Binder.getCallingUid();
2071 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2072 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2073 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2074
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002075 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS);
2076
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002077 long identityToken = clearCallingIdentity();
2078 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002079 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002080 true /* stripAuthTokenFromResult */, null /* accountName */,
2081 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002082 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002083 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002084 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002085 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002086 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002087
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002088 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002089 protected String toDebugString(long now) {
2090 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002091 + ", accountType " + accountType
2092 + ", requiredFeatures "
2093 + (requiredFeatures != null
2094 ? TextUtils.join(",", requiredFeatures)
2095 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002096 }
2097 }.bind();
2098 } finally {
2099 restoreCallingIdentity(identityToken);
2100 }
Fred Quintana60307342009-03-24 22:48:12 -07002101 }
2102
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002103 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002104 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2105 final String authTokenType, final String[] requiredFeatures,
2106 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
2107 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2108 Log.v(TAG, "addAccount: accountType " + accountType
2109 + ", response " + response
2110 + ", authTokenType " + authTokenType
2111 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2112 + ", expectActivityLaunch " + expectActivityLaunch
2113 + ", caller's uid " + Binder.getCallingUid()
2114 + ", pid " + Binder.getCallingPid()
2115 + ", for user id " + userId);
2116 }
2117 if (response == null) throw new IllegalArgumentException("response is null");
2118 if (accountType == null) throw new IllegalArgumentException("accountType is null");
2119 checkManageAccountsPermission();
2120
2121 // Only allow the system process to add accounts of other users
2122 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
2123 + " trying to add account for " + userId);
2124
2125 // Is user disallowed from modifying accounts?
2126 if (!canUserModifyAccounts(userId)) {
2127 try {
2128 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2129 "User is not allowed to add an account!");
2130 } catch (RemoteException re) {
2131 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002132 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002133 return;
2134 }
2135 if (!canUserModifyAccountsForType(userId, accountType)) {
2136 try {
2137 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2138 "User cannot modify accounts of this type (policy).");
2139 } catch (RemoteException re) {
2140 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002141 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2142 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002143 return;
2144 }
2145
2146 UserAccounts accounts = getUserAccounts(userId);
2147 final int pid = Binder.getCallingPid();
2148 final int uid = Binder.getCallingUid();
2149 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2150 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2151 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2152
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002153 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS);
2154
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002155 long identityToken = clearCallingIdentity();
2156 try {
2157 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002158 true /* stripAuthTokenFromResult */, null /* accountName */,
2159 false /* authDetailsRequired */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002160 @Override
2161 public void run() throws RemoteException {
2162 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2163 options);
2164 }
2165
2166 @Override
2167 protected String toDebugString(long now) {
2168 return super.toDebugString(now) + ", addAccount"
2169 + ", accountType " + accountType
2170 + ", requiredFeatures "
2171 + (requiredFeatures != null
2172 ? TextUtils.join(",", requiredFeatures)
2173 : null);
2174 }
2175 }.bind();
2176 } finally {
2177 restoreCallingIdentity(identityToken);
2178 }
2179 }
2180
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002181 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002182 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2183 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2184 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2185 long identityToken = clearCallingIdentity();
2186 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002187 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002188 } finally {
2189 restoreCallingIdentity(identityToken);
2190 }
2191 }
2192
2193 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002194 public void confirmCredentialsAsUser(IAccountManagerResponse response,
2195 final Account account, final Bundle options, final boolean expectActivityLaunch,
2196 int userId) {
2197 // Only allow the system process to read accounts of other users
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01002198 enforceCrossUserPermission(userId, "User " + UserHandle.getCallingUserId()
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002199 + " trying to confirm account credentials for " + userId);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002200
Fred Quintana56285a62010-12-02 14:20:51 -08002201 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2202 Log.v(TAG, "confirmCredentials: " + account
2203 + ", response " + response
2204 + ", expectActivityLaunch " + expectActivityLaunch
2205 + ", caller's uid " + Binder.getCallingUid()
2206 + ", pid " + Binder.getCallingPid());
2207 }
Fred Quintana382601f2010-03-25 12:25:10 -07002208 if (response == null) throw new IllegalArgumentException("response is null");
2209 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002210 checkManageAccountsPermission();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002211 UserAccounts accounts = getUserAccounts(userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002212 long identityToken = clearCallingIdentity();
2213 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002214 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002215 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002216 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002217 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002218 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002219 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002220 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002221 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002222 protected String toDebugString(long now) {
2223 return super.toDebugString(now) + ", confirmCredentials"
2224 + ", " + account;
2225 }
2226 }.bind();
2227 } finally {
2228 restoreCallingIdentity(identityToken);
2229 }
Fred Quintana60307342009-03-24 22:48:12 -07002230 }
2231
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002232 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002233 public void updateCredentials(IAccountManagerResponse response, final Account account,
2234 final String authTokenType, final boolean expectActivityLaunch,
2235 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08002236 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2237 Log.v(TAG, "updateCredentials: " + account
2238 + ", response " + response
2239 + ", authTokenType " + authTokenType
2240 + ", expectActivityLaunch " + expectActivityLaunch
2241 + ", caller's uid " + Binder.getCallingUid()
2242 + ", pid " + Binder.getCallingPid());
2243 }
Fred Quintana382601f2010-03-25 12:25:10 -07002244 if (response == null) throw new IllegalArgumentException("response is null");
2245 if (account == null) throw new IllegalArgumentException("account is null");
2246 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002247 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002248 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002249 long identityToken = clearCallingIdentity();
2250 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002251 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002252 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002253 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002254 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002255 public void run() throws RemoteException {
2256 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2257 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002258 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002259 protected String toDebugString(long now) {
2260 if (loginOptions != null) loginOptions.keySet();
2261 return super.toDebugString(now) + ", updateCredentials"
2262 + ", " + account
2263 + ", authTokenType " + authTokenType
2264 + ", loginOptions " + loginOptions;
2265 }
2266 }.bind();
2267 } finally {
2268 restoreCallingIdentity(identityToken);
2269 }
Fred Quintana60307342009-03-24 22:48:12 -07002270 }
2271
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002272 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002273 public void editProperties(IAccountManagerResponse response, final String accountType,
2274 final boolean expectActivityLaunch) {
Fred Quintana56285a62010-12-02 14:20:51 -08002275 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2276 Log.v(TAG, "editProperties: accountType " + accountType
2277 + ", response " + response
2278 + ", expectActivityLaunch " + expectActivityLaunch
2279 + ", caller's uid " + Binder.getCallingUid()
2280 + ", pid " + Binder.getCallingPid());
2281 }
Fred Quintana382601f2010-03-25 12:25:10 -07002282 if (response == null) throw new IllegalArgumentException("response is null");
2283 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002284 checkManageAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002285 UserAccounts accounts = getUserAccountsForCaller();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002286 long identityToken = clearCallingIdentity();
2287 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002288 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002289 true /* stripAuthTokenFromResult */, null /* accountName */,
2290 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002291 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002292 public void run() throws RemoteException {
2293 mAuthenticator.editProperties(this, mAccountType);
2294 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002295 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002296 protected String toDebugString(long now) {
2297 return super.toDebugString(now) + ", editProperties"
2298 + ", accountType " + accountType;
2299 }
2300 }.bind();
2301 } finally {
2302 restoreCallingIdentity(identityToken);
2303 }
Fred Quintana60307342009-03-24 22:48:12 -07002304 }
2305
Fred Quintana33269202009-04-20 16:05:10 -07002306 private class GetAccountsByTypeAndFeatureSession extends Session {
2307 private final String[] mFeatures;
2308 private volatile Account[] mAccountsOfType = null;
2309 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2310 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002311 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002312
Amith Yamasani04e0d262012-02-14 11:50:53 -08002313 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002314 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002315 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002316 true /* stripAuthTokenFromResult */, null /* accountName */,
2317 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002318 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002319 mFeatures = features;
2320 }
2321
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002322 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002323 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002324 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002325 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2326 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002327 }
Fred Quintana33269202009-04-20 16:05:10 -07002328 // check whether each account matches the requested features
2329 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2330 mCurrentAccount = 0;
2331
2332 checkAccount();
2333 }
2334
2335 public void checkAccount() {
2336 if (mCurrentAccount >= mAccountsOfType.length) {
2337 sendResult();
2338 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002339 }
Fred Quintana33269202009-04-20 16:05:10 -07002340
Fred Quintana29e94b82010-03-10 12:11:51 -08002341 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2342 if (accountAuthenticator == null) {
2343 // It is possible that the authenticator has died, which is indicated by
2344 // mAuthenticator being set to null. If this happens then just abort.
2345 // There is no need to send back a result or error in this case since
2346 // that already happened when mAuthenticator was cleared.
2347 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2348 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2349 + " connected to the authenticator, " + toDebugString());
2350 }
2351 return;
2352 }
Fred Quintana33269202009-04-20 16:05:10 -07002353 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002354 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002355 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002356 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002357 }
2358 }
2359
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002360 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002361 public void onResult(Bundle result) {
2362 mNumResults++;
2363 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002364 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002365 return;
2366 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002367 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002368 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2369 }
2370 mCurrentAccount++;
2371 checkAccount();
2372 }
2373
2374 public void sendResult() {
2375 IAccountManagerResponse response = getResponseAndClose();
2376 if (response != null) {
2377 try {
2378 Account[] accounts = new Account[mAccountsWithFeatures.size()];
2379 for (int i = 0; i < accounts.length; i++) {
2380 accounts[i] = mAccountsWithFeatures.get(i);
2381 }
Fred Quintana56285a62010-12-02 14:20:51 -08002382 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2383 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2384 + response);
2385 }
Fred Quintana33269202009-04-20 16:05:10 -07002386 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002387 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07002388 response.onResult(result);
2389 } catch (RemoteException e) {
2390 // if the caller is dead then there is no one to care about remote exceptions
2391 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2392 Log.v(TAG, "failure while notifying response", e);
2393 }
2394 }
2395 }
2396 }
2397
2398
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002399 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002400 protected String toDebugString(long now) {
2401 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
2402 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
2403 }
2404 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002405
Amith Yamasani04e0d262012-02-14 11:50:53 -08002406 /**
2407 * Returns the accounts for a specific user
2408 * @hide
2409 */
2410 public Account[] getAccounts(int userId) {
2411 checkReadAccountsPermission();
2412 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002413 int callingUid = Binder.getCallingUid();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002414 long identityToken = clearCallingIdentity();
2415 try {
2416 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002417 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002418 }
2419 } finally {
2420 restoreCallingIdentity(identityToken);
2421 }
2422 }
2423
Amith Yamasanif29f2362012-04-05 18:29:52 -07002424 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002425 * Returns accounts for all running users.
2426 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07002427 * @hide
2428 */
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002429 public AccountAndUser[] getRunningAccounts() {
2430 final int[] runningUserIds;
2431 try {
2432 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
2433 } catch (RemoteException e) {
2434 // Running in system_server; should never happen
2435 throw new RuntimeException(e);
2436 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002437 return getAccounts(runningUserIds);
2438 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07002439
Jeff Sharkey6eb96202012-10-10 13:13:54 -07002440 /** {@hide} */
2441 public AccountAndUser[] getAllAccounts() {
2442 final List<UserInfo> users = getUserManager().getUsers();
2443 final int[] userIds = new int[users.size()];
2444 for (int i = 0; i < userIds.length; i++) {
2445 userIds[i] = users.get(i).id;
2446 }
2447 return getAccounts(userIds);
2448 }
2449
2450 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002451 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07002452 for (int userId : userIds) {
2453 UserAccounts userAccounts = getUserAccounts(userId);
2454 if (userAccounts == null) continue;
2455 synchronized (userAccounts.cacheLock) {
2456 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
2457 Binder.getCallingUid(), null);
2458 for (int a = 0; a < accounts.length; a++) {
2459 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07002460 }
2461 }
2462 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002463
2464 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
2465 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07002466 }
2467
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002468 @Override
2469 public Account[] getAccountsAsUser(String type, int userId) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002470 return getAccountsAsUser(type, userId, null, -1);
2471 }
2472
2473 private Account[] getAccountsAsUser(String type, int userId, String callingPackage,
2474 int packageUid) {
2475 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002476 // Only allow the system process to read accounts of other users
2477 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07002478 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08002479 && mContext.checkCallingOrSelfPermission(
2480 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
2481 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002482 throw new SecurityException("User " + UserHandle.getCallingUserId()
2483 + " trying to get account for " + userId);
2484 }
2485
Fred Quintana56285a62010-12-02 14:20:51 -08002486 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2487 Log.v(TAG, "getAccounts: accountType " + type
2488 + ", caller's uid " + Binder.getCallingUid()
2489 + ", pid " + Binder.getCallingPid());
2490 }
Amith Yamasani27db4682013-03-30 17:07:47 -07002491 // If the original calling app was using the framework account chooser activity, we'll
2492 // be passed in the original caller's uid here, which is what should be used for filtering.
2493 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
2494 callingUid = packageUid;
2495 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002496 checkReadAccountsPermission();
2497 long identityToken = clearCallingIdentity();
2498 try {
Simranjit Singh Kohli6a184872015-05-19 10:58:01 -07002499 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002500 synchronized (accounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002501 return getAccountsFromCacheLocked(accounts, type, callingUid, callingPackage);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002502 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002503 } finally {
2504 restoreCallingIdentity(identityToken);
2505 }
2506 }
2507
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002508 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002509 public boolean addSharedAccountAsUser(Account account, int userId) {
2510 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002511 UserAccounts accounts = getUserAccounts(userId);
2512 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002513 ContentValues values = new ContentValues();
2514 values.put(ACCOUNTS_NAME, account.name);
2515 values.put(ACCOUNTS_TYPE, account.type);
2516 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2517 new String[] {account.name, account.type});
2518 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
2519 if (accountId < 0) {
2520 Log.w(TAG, "insertAccountIntoDatabase: " + account
2521 + ", skipping the DB insert failed");
2522 return false;
2523 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002524 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002525 return true;
2526 }
2527
2528 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002529 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
2530 userId = handleIncomingUser(userId);
2531 UserAccounts accounts = getUserAccounts(userId);
2532 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002533 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002534 final ContentValues values = new ContentValues();
2535 values.put(ACCOUNTS_NAME, newName);
2536 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
2537 int r = db.update(
2538 TABLE_SHARED_ACCOUNTS,
2539 values,
2540 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2541 new String[] { account.name, account.type });
2542 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002543 int callingUid = getCallingUid();
2544 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
2545 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002546 // Recursively rename the account.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002547 renameAccountInternal(accounts, account, newName, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002548 }
2549 return r > 0;
2550 }
2551
2552 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08002553 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002554 return removeSharedAccountAsUser(account, userId, getCallingUid());
2555 }
2556
2557 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08002558 userId = handleIncomingUser(userId);
2559 UserAccounts accounts = getUserAccounts(userId);
2560 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002561 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002562 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
2563 new String[] {account.name, account.type});
2564 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002565 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
2566 sharedTableAccountId, accounts, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002567 removeAccountInternal(accounts, account);
2568 }
2569 return r > 0;
2570 }
2571
2572 @Override
2573 public Account[] getSharedAccountsAsUser(int userId) {
2574 userId = handleIncomingUser(userId);
2575 UserAccounts accounts = getUserAccounts(userId);
2576 ArrayList<Account> accountList = new ArrayList<Account>();
2577 Cursor cursor = null;
2578 try {
2579 cursor = accounts.openHelper.getReadableDatabase()
2580 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
2581 null, null, null, null, null);
2582 if (cursor != null && cursor.moveToFirst()) {
2583 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
2584 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
2585 do {
2586 accountList.add(new Account(cursor.getString(nameIndex),
2587 cursor.getString(typeIndex)));
2588 } while (cursor.moveToNext());
2589 }
2590 } finally {
2591 if (cursor != null) {
2592 cursor.close();
2593 }
2594 }
2595 Account[] accountArray = new Account[accountList.size()];
2596 accountList.toArray(accountArray);
2597 return accountArray;
2598 }
2599
2600 @Override
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002601 public Account[] getAccounts(String type) {
2602 return getAccountsAsUser(type, UserHandle.getCallingUserId());
2603 }
2604
Amith Yamasani27db4682013-03-30 17:07:47 -07002605 @Override
2606 public Account[] getAccountsForPackage(String packageName, int uid) {
2607 int callingUid = Binder.getCallingUid();
2608 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
2609 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
2610 + callingUid + " with uid=" + uid);
2611 }
2612 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid);
2613 }
2614
Amith Yamasani3b458ad2013-04-18 18:40:07 -07002615 @Override
2616 public Account[] getAccountsByTypeForPackage(String type, String packageName) {
2617 checkBinderPermission(android.Manifest.permission.INTERACT_ACROSS_USERS);
2618 int packageUid = -1;
2619 try {
2620 packageUid = AppGlobals.getPackageManager().getPackageUid(
2621 packageName, UserHandle.getCallingUserId());
2622 } catch (RemoteException re) {
2623 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
2624 return new Account[0];
2625 }
2626 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName, packageUid);
2627 }
2628
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002629 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002630 public void getAccountsByFeatures(IAccountManagerResponse response,
Fred Quintana33269202009-04-20 16:05:10 -07002631 String type, String[] features) {
Fred Quintana56285a62010-12-02 14:20:51 -08002632 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2633 Log.v(TAG, "getAccounts: accountType " + type
2634 + ", response " + response
2635 + ", features " + stringArrayToString(features)
2636 + ", caller's uid " + Binder.getCallingUid()
2637 + ", pid " + Binder.getCallingPid());
2638 }
Fred Quintana382601f2010-03-25 12:25:10 -07002639 if (response == null) throw new IllegalArgumentException("response is null");
2640 if (type == null) throw new IllegalArgumentException("accountType is null");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002641 checkReadAccountsPermission();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002642 UserAccounts userAccounts = getUserAccountsForCaller();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002643 int callingUid = Binder.getCallingUid();
Fred Quintana33269202009-04-20 16:05:10 -07002644 long identityToken = clearCallingIdentity();
2645 try {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002646 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002647 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002648 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002649 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002650 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002651 Bundle result = new Bundle();
2652 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
2653 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002654 return;
2655 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002656 new GetAccountsByTypeAndFeatureSession(userAccounts, response, type, features,
2657 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07002658 } finally {
2659 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002660 }
2661 }
2662
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002663 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
2664 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
2665 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
2666 try {
2667 if (cursor.moveToNext()) {
2668 return cursor.getLong(0);
2669 }
2670 return -1;
2671 } finally {
2672 cursor.close();
2673 }
2674 }
2675
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002676 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07002677 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002678 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07002679 try {
2680 if (cursor.moveToNext()) {
2681 return cursor.getLong(0);
2682 }
2683 return -1;
2684 } finally {
2685 cursor.close();
2686 }
2687 }
2688
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002689 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07002690 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
2691 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
2692 new String[]{key}, null, null, null);
2693 try {
2694 if (cursor.moveToNext()) {
2695 return cursor.getLong(0);
2696 }
2697 return -1;
2698 } finally {
2699 cursor.close();
2700 }
2701 }
2702
Fred Quintanaa698f422009-04-08 19:14:54 -07002703 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07002704 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07002705 IAccountManagerResponse mResponse;
2706 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002707 final boolean mExpectActivityLaunch;
2708 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002709 final String mAccountName;
2710 // Indicates if we need to add auth details(like last credential time)
2711 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002712 // If set, we need to update the last authenticated time. This is
2713 // currently
2714 // used on
2715 // successful confirming credentials.
2716 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07002717
Fred Quintana33269202009-04-20 16:05:10 -07002718 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07002719 private int mNumRequestContinued = 0;
2720 private int mNumErrors = 0;
2721
Fred Quintana60307342009-03-24 22:48:12 -07002722 IAccountAuthenticator mAuthenticator = null;
2723
Fred Quintana8570f742010-02-18 10:32:54 -08002724 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002725 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002726
Amith Yamasani04e0d262012-02-14 11:50:53 -08002727 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002728 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2729 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002730 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
2731 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
2732 }
2733
2734 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
2735 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
2736 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07002737 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08002738 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07002739 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08002740 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08002741 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07002742 mResponse = response;
2743 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07002744 mExpectActivityLaunch = expectActivityLaunch;
2745 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002746 mAccountName = accountName;
2747 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002748 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002749
Fred Quintanaa698f422009-04-08 19:14:54 -07002750 synchronized (mSessions) {
2751 mSessions.put(toString(), this);
2752 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002753 if (response != null) {
2754 try {
2755 response.asBinder().linkToDeath(this, 0 /* flags */);
2756 } catch (RemoteException e) {
2757 mResponse = null;
2758 binderDied();
2759 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002760 }
Fred Quintana60307342009-03-24 22:48:12 -07002761 }
2762
Fred Quintanaa698f422009-04-08 19:14:54 -07002763 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07002764 if (mResponse == null) {
2765 // this session has already been closed
2766 return null;
2767 }
Fred Quintana60307342009-03-24 22:48:12 -07002768 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07002769 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07002770 return response;
2771 }
2772
Fred Quintanaa698f422009-04-08 19:14:54 -07002773 private void close() {
2774 synchronized (mSessions) {
2775 if (mSessions.remove(toString()) == null) {
2776 // the session was already closed, so bail out now
2777 return;
2778 }
2779 }
2780 if (mResponse != null) {
2781 // stop listening for response deaths
2782 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
2783
2784 // clear this so that we don't accidentally send any further results
2785 mResponse = null;
2786 }
2787 cancelTimeout();
2788 unbind();
2789 }
2790
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002791 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002792 public void binderDied() {
2793 mResponse = null;
2794 close();
2795 }
2796
2797 protected String toDebugString() {
2798 return toDebugString(SystemClock.elapsedRealtime());
2799 }
2800
2801 protected String toDebugString(long now) {
2802 return "Session: expectLaunch " + mExpectActivityLaunch
2803 + ", connected " + (mAuthenticator != null)
2804 + ", stats (" + mNumResults + "/" + mNumRequestContinued
2805 + "/" + mNumErrors + ")"
2806 + ", lifetime " + ((now - mCreationTime) / 1000.0);
2807 }
2808
Fred Quintana60307342009-03-24 22:48:12 -07002809 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002810 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2811 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
2812 }
Fred Quintanab839afc2009-10-14 15:57:28 -07002813 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002814 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002815 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07002816 }
2817 }
2818
2819 private void unbind() {
2820 if (mAuthenticator != null) {
2821 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07002822 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07002823 }
2824 }
2825
2826 public void scheduleTimeout() {
2827 mMessageHandler.sendMessageDelayed(
2828 mMessageHandler.obtainMessage(MESSAGE_TIMED_OUT, this), TIMEOUT_DELAY_MS);
2829 }
2830
2831 public void cancelTimeout() {
2832 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
2833 }
2834
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002835 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002836 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07002837 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07002838 try {
2839 run();
2840 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002841 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07002842 "remote exception");
2843 }
Fred Quintana60307342009-03-24 22:48:12 -07002844 }
2845
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002846 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07002847 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002848 mAuthenticator = null;
2849 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002850 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002851 try {
2852 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2853 "disconnected");
2854 } catch (RemoteException e) {
2855 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2856 Log.v(TAG, "Session.onServiceDisconnected: "
2857 + "caught RemoteException while responding", e);
2858 }
2859 }
Fred Quintana60307342009-03-24 22:48:12 -07002860 }
2861 }
2862
Fred Quintanab839afc2009-10-14 15:57:28 -07002863 public abstract void run() throws RemoteException;
2864
Fred Quintana60307342009-03-24 22:48:12 -07002865 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07002866 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002867 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07002868 try {
2869 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
2870 "timeout");
2871 } catch (RemoteException e) {
2872 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2873 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
2874 e);
2875 }
2876 }
Fred Quintana60307342009-03-24 22:48:12 -07002877 }
2878 }
2879
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002880 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002881 public void onResult(Bundle result) {
2882 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002883 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002884 if (result != null) {
2885 boolean isSuccessfulConfirmCreds = result.getBoolean(
2886 AccountManager.KEY_BOOLEAN_RESULT, false);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002887 boolean isSuccessfulUpdateCreds =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002888 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
2889 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002890 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002891 // mUpdateLastAuthenticatedTime is true and the confirmRequest
2892 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07002893 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002894 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCreds);
2895 if (needUpdate || mAuthDetailsRequired) {
2896 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
2897 if (needUpdate && accountPresent) {
2898 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
2899 }
2900 if (mAuthDetailsRequired) {
2901 long lastAuthenticatedTime = -1;
2902 if (accountPresent) {
2903 lastAuthenticatedTime = DatabaseUtils.longForQuery(
2904 mAccounts.openHelper.getReadableDatabase(),
2905 "select " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
2906 + " from " +
2907 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
2908 + ACCOUNTS_TYPE + "=?",
2909 new String[] {
2910 mAccountName, mAccountType
2911 });
2912 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07002913 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002914 lastAuthenticatedTime);
2915 }
2916 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002917 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002918 if (result != null
2919 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2920 /*
2921 * The Authenticator API allows third party authenticators to
2922 * supply arbitrary intents to other apps that they can run,
2923 * this can be very bad when those apps are in the system like
2924 * the System Settings.
2925 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002926 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07002927 long bid = Binder.clearCallingIdentity();
2928 try {
2929 PackageManager pm = mContext.getPackageManager();
2930 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2931 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2932 if (PackageManager.SIGNATURE_MATCH !=
2933 pm.checkSignatures(authenticatorUid, targetUid)) {
2934 throw new SecurityException(
2935 "Activity to be started with KEY_INTENT must " +
2936 "share Authenticator's signatures");
2937 }
2938 } finally {
2939 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002940 }
2941 }
2942 if (result != null
2943 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002944 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2945 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002946 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
2947 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002948 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
2949 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002950 }
Fred Quintana60307342009-03-24 22:48:12 -07002951 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002952 IAccountManagerResponse response;
2953 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002954 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002955 response = mResponse;
2956 } else {
2957 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07002958 }
Fred Quintana60307342009-03-24 22:48:12 -07002959 if (response != null) {
2960 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07002961 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002962 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2963 Log.v(TAG, getClass().getSimpleName()
2964 + " calling onError() on response " + response);
2965 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002966 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07002967 "null bundle returned");
2968 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08002969 if (mStripAuthTokenFromResult) {
2970 result.remove(AccountManager.KEY_AUTHTOKEN);
2971 }
Fred Quintana56285a62010-12-02 14:20:51 -08002972 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2973 Log.v(TAG, getClass().getSimpleName()
2974 + " calling onResult() on response " + response);
2975 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002976 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
2977 (intent == null)) {
2978 // All AccountManager error codes are greater than 0
2979 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
2980 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2981 } else {
2982 response.onResult(result);
2983 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002984 }
Fred Quintana60307342009-03-24 22:48:12 -07002985 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07002986 // if the caller is dead then there is no one to care about remote exceptions
2987 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2988 Log.v(TAG, "failure while notifying response", e);
2989 }
Fred Quintana60307342009-03-24 22:48:12 -07002990 }
2991 }
2992 }
Fred Quintana60307342009-03-24 22:48:12 -07002993
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002994 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002995 public void onRequestContinued() {
2996 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07002997 }
2998
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002999 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003000 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003001 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003002 IAccountManagerResponse response = getResponseAndClose();
3003 if (response != null) {
3004 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003005 Log.v(TAG, getClass().getSimpleName()
3006 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003007 }
3008 try {
3009 response.onError(errorCode, errorMessage);
3010 } catch (RemoteException e) {
3011 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3012 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3013 }
3014 }
3015 } else {
3016 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3017 Log.v(TAG, "Session.onError: already closed");
3018 }
Fred Quintana60307342009-03-24 22:48:12 -07003019 }
3020 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003021
3022 /**
3023 * find the component name for the authenticator and initiate a bind
3024 * if no authenticator or the bind fails then return false, otherwise return true
3025 */
3026 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003027 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3028 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3029 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003030 if (authenticatorInfo == null) {
3031 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3032 Log.v(TAG, "there is no authenticator for " + authenticatorType
3033 + ", bailing out");
3034 }
3035 return false;
3036 }
3037
3038 Intent intent = new Intent();
3039 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3040 intent.setComponent(authenticatorInfo.componentName);
3041 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3042 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3043 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003044 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
3045 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003046 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3047 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3048 }
3049 return false;
3050 }
3051
3052
3053 return true;
3054 }
Fred Quintana60307342009-03-24 22:48:12 -07003055 }
3056
3057 private class MessageHandler extends Handler {
3058 MessageHandler(Looper looper) {
3059 super(looper);
3060 }
Costin Manolache3348f142009-09-29 18:58:36 -07003061
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003062 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003063 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07003064 switch (msg.what) {
3065 case MESSAGE_TIMED_OUT:
3066 Session session = (Session)msg.obj;
3067 session.onTimedOut();
3068 break;
3069
Amith Yamasani5be347b2013-03-31 17:44:31 -07003070 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00003071 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07003072 break;
3073
Fred Quintana60307342009-03-24 22:48:12 -07003074 default:
3075 throw new IllegalStateException("unhandled message: " + msg.what);
3076 }
3077 }
3078 }
3079
Amith Yamasani04e0d262012-02-14 11:50:53 -08003080 private static String getDatabaseName(int userId) {
3081 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07003082 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003083 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07003084 // Migrate old file, if it exists, to the new location.
3085 // Make sure the new file doesn't already exist. A dummy file could have been
3086 // accidentally created in the old location, causing the new one to become corrupted
3087 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08003088 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07003089 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07003090 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07003091 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07003092 if (!userDir.exists()) {
3093 if (!userDir.mkdirs()) {
3094 throw new IllegalStateException("User dir cannot be created: " + userDir);
3095 }
3096 }
3097 if (!oldFile.renameTo(databaseFile)) {
3098 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
3099 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003100 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003101 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003102 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08003103 }
3104
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003105 private static class DebugDbHelper{
3106 private DebugDbHelper() {
3107 }
3108
3109 private static String TABLE_DEBUG = "debug_table";
3110
3111 // Columns for the table
3112 private static String ACTION_TYPE = "action_type";
3113 private static String TIMESTAMP = "time";
3114 private static String CALLER_UID = "caller_uid";
3115 private static String TABLE_NAME = "table_name";
3116 private static String KEY = "primary_key";
3117
3118 // These actions correspond to the occurrence of real actions. Since
3119 // these are called by the authenticators, the uid associated will be
3120 // of the authenticator.
3121 private static String ACTION_SET_PASSWORD = "action_set_password";
3122 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
3123 private static String ACTION_ACCOUNT_ADD = "action_account_add";
3124 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
3125 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
3126 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
3127
3128 // These actions don't necessarily correspond to any action on
3129 // accountDb taking place. As an example, there might be a request for
3130 // addingAccount, which might not lead to addition of account on grounds
3131 // of bad authentication. We will still be logging it to keep track of
3132 // who called.
3133 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
3134 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
3135 private static String ACTION_CALLED_ACCOUNT_RENAME = "action_called_account_rename";
3136
3137 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3138
3139 private static String UPDATE_WHERE_CLAUSE = KEY + "=?";
3140
3141 private static void createDebugTable(SQLiteDatabase db) {
3142 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
3143 + ACCOUNTS_ID + " INTEGER,"
3144 + ACTION_TYPE + " TEXT NOT NULL, "
3145 + TIMESTAMP + " DATETIME,"
3146 + CALLER_UID + " INTEGER NOT NULL,"
3147 + TABLE_NAME + " TEXT NOT NULL,"
3148 + KEY + " INTEGER PRIMARY KEY)");
3149 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
3150 }
3151 }
3152
3153 private void logRecord(UserAccounts accounts, String action, String tableName) {
3154 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3155 logRecord(db, action, tableName, -1, accounts);
3156 }
3157
3158 /*
3159 * This function receives an opened writable database.
3160 */
3161 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3162 UserAccounts userAccount) {
3163 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
3164 }
3165
3166 /*
3167 * This function receives an opened writable database.
3168 */
3169 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3170 UserAccounts userAccount, int callingUid) {
3171 SQLiteStatement logStatement = userAccount.statementForLogging;
3172 logStatement.bindLong(1, accountId);
3173 logStatement.bindString(2, action);
3174 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
3175 logStatement.bindLong(4, callingUid);
3176 logStatement.bindString(5, tableName);
3177 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
3178 logStatement.execute();
3179 logStatement.clearBindings();
3180 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
3181 % MAX_DEBUG_DB_SIZE;
3182 }
3183
3184 /*
3185 * This should only be called once to compile the sql statement for logging
3186 * and to find the insertion point.
3187 */
3188 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
3189 UserAccounts userAccount) {
3190 // Initialize the count if not done earlier.
3191 int size = (int) getDebugTableRowCount(db);
3192 if (size >= MAX_DEBUG_DB_SIZE) {
3193 // Table is full, and we need to find the point where to insert.
3194 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
3195 } else {
3196 userAccount.debugDbInsertionPoint = size;
3197 }
3198 compileSqlStatementForLogging(db, userAccount);
3199 }
3200
3201 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
3202 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
3203 + " VALUES (?,?,?,?,?,?)";
3204 userAccount.statementForLogging = db.compileStatement(sql);
3205 }
3206
3207 private long getDebugTableRowCount(SQLiteDatabase db) {
3208 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
3209 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3210 }
3211
3212 /*
3213 * Finds the row key where the next insertion should take place. This should
3214 * be invoked only if the table has reached its full capacity.
3215 */
3216 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
3217 // This query finds the smallest timestamp value (and if 2 records have
3218 // same timestamp, the choose the lower id).
3219 String queryCountDebugDbRows = new StringBuilder()
3220 .append("SELECT ").append(DebugDbHelper.KEY)
3221 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
3222 .append(" ORDER BY ")
3223 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
3224 .append(" LIMIT 1")
3225 .toString();
3226 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3227 }
3228
Amith Yamasani04e0d262012-02-14 11:50:53 -08003229 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003230
Amith Yamasani04e0d262012-02-14 11:50:53 -08003231 public DatabaseHelper(Context context, int userId) {
3232 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07003233 }
3234
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003235 /**
3236 * This call needs to be made while the mCacheLock is held. The way to
3237 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
3238 * @param db The database.
3239 */
Fred Quintana60307342009-03-24 22:48:12 -07003240 @Override
3241 public void onCreate(SQLiteDatabase db) {
3242 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
3243 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3244 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3245 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3246 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003247 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003248 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
Fred Quintana60307342009-03-24 22:48:12 -07003249 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3250
3251 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
3252 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3253 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3254 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
3255 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
3256 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
3257
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003258 createGrantsTable(db);
3259
Fred Quintana60307342009-03-24 22:48:12 -07003260 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
3261 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3262 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
3263 + EXTRAS_KEY + " TEXT NOT NULL, "
3264 + EXTRAS_VALUE + " TEXT, "
3265 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
3266
3267 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
3268 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
3269 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07003270
Amith Yamasani67df64b2012-12-14 12:09:36 -08003271 createSharedAccountsTable(db);
3272
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003273 createAccountsDeletionTrigger(db);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003274
3275 DebugDbHelper.createDebugTable(db);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003276 }
3277
Amith Yamasani67df64b2012-12-14 12:09:36 -08003278 private void createSharedAccountsTable(SQLiteDatabase db) {
3279 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
3280 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3281 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3282 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3283 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3284 }
3285
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003286 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
3287 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
3288 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
3289 }
3290
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003291 private void addOldAccountNameColumn(SQLiteDatabase db) {
3292 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
3293 }
3294
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003295 private void addDebugTable(SQLiteDatabase db) {
3296 DebugDbHelper.createDebugTable(db);
3297 }
3298
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003299 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003300 db.execSQL(""
3301 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
3302 + " BEGIN"
3303 + " DELETE FROM " + TABLE_AUTHTOKENS
3304 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
3305 + " DELETE FROM " + TABLE_EXTRAS
3306 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003307 + " DELETE FROM " + TABLE_GRANTS
3308 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07003309 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07003310 }
3311
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003312 private void createGrantsTable(SQLiteDatabase db) {
3313 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
3314 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3315 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
3316 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
3317 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
3318 + "," + GRANTS_GRANTEE_UID + "))");
3319 }
3320
Fred Quintana60307342009-03-24 22:48:12 -07003321 @Override
3322 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003323 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07003324
Fred Quintanaa698f422009-04-08 19:14:54 -07003325 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003326 // no longer need to do anything since the work is done
3327 // when upgrading from version 2
3328 oldVersion++;
3329 }
3330
3331 if (oldVersion == 2) {
3332 createGrantsTable(db);
3333 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
3334 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07003335 oldVersion++;
3336 }
Costin Manolache3348f142009-09-29 18:58:36 -07003337
3338 if (oldVersion == 3) {
3339 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
3340 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
3341 oldVersion++;
3342 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003343
3344 if (oldVersion == 4) {
3345 createSharedAccountsTable(db);
3346 oldVersion++;
3347 }
3348
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003349 if (oldVersion == 5) {
3350 addOldAccountNameColumn(db);
3351 oldVersion++;
3352 }
3353
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003354 if (oldVersion == 6) {
3355 addLastSuccessfullAuthenticatedTimeColumn(db);
3356 oldVersion++;
3357 }
3358
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003359 if (oldVersion == 7) {
3360 addDebugTable(db);
3361 oldVersion++;
3362 }
3363
Amith Yamasani67df64b2012-12-14 12:09:36 -08003364 if (oldVersion != newVersion) {
3365 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
3366 }
Fred Quintana60307342009-03-24 22:48:12 -07003367 }
3368
3369 @Override
3370 public void onOpen(SQLiteDatabase db) {
3371 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
3372 }
3373 }
3374
Fred Quintana60307342009-03-24 22:48:12 -07003375 public IBinder onBind(Intent intent) {
3376 return asBinder();
3377 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003378
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003379 /**
3380 * Searches array of arguments for the specified string
3381 * @param args array of argument strings
3382 * @param value value to search for
3383 * @return true if the value is contained in the array
3384 */
3385 private static boolean scanArgs(String[] args, String value) {
3386 if (args != null) {
3387 for (String arg : args) {
3388 if (value.equals(arg)) {
3389 return true;
3390 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003391 }
3392 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003393 return false;
3394 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003395
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003396 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003397 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07003398 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3399 != PackageManager.PERMISSION_GRANTED) {
3400 fout.println("Permission Denial: can't dump AccountsManager from from pid="
3401 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
3402 + " without permission " + android.Manifest.permission.DUMP);
3403 return;
3404 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003405 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003406 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07003407
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003408 final List<UserInfo> users = getUserManager().getUsers();
3409 for (UserInfo user : users) {
3410 ipw.println("User " + user + ":");
3411 ipw.increaseIndent();
3412 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
3413 ipw.println();
3414 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08003415 }
3416 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003417
Amith Yamasani04e0d262012-02-14 11:50:53 -08003418 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
3419 String[] args, boolean isCheckinRequest) {
3420 synchronized (userAccounts.cacheLock) {
3421 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003422
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003423 if (isCheckinRequest) {
3424 // This is a checkin request. *Only* upload the account types and the count of each.
3425 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
3426 null, null, ACCOUNTS_TYPE, null, null);
3427 try {
3428 while (cursor.moveToNext()) {
3429 // print type,count
3430 fout.println(cursor.getString(0) + "," + cursor.getString(1));
3431 }
3432 } finally {
3433 if (cursor != null) {
3434 cursor.close();
3435 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003436 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003437 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003438 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07003439 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003440 fout.println("Accounts: " + accounts.length);
3441 for (Account account : accounts) {
3442 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003443 }
Fred Quintana307da1a2010-01-21 14:24:20 -08003444
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003445 // Add debug information.
3446 fout.println();
3447 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
3448 null, null, null, null, DebugDbHelper.TIMESTAMP);
3449 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
3450 fout.println("Accounts History");
3451 try {
3452 while (cursor.moveToNext()) {
3453 // print type,count
3454 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
3455 cursor.getString(2) + "," + cursor.getString(3) + ","
3456 + cursor.getString(4) + "," + cursor.getString(5));
3457 }
3458 } finally {
3459 cursor.close();
3460 }
3461
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003462 fout.println();
3463 synchronized (mSessions) {
3464 final long now = SystemClock.elapsedRealtime();
3465 fout.println("Active Sessions: " + mSessions.size());
3466 for (Session session : mSessions.values()) {
3467 fout.println(" " + session.toDebugString(now));
3468 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003469 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003470
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003471 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003472 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003473 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07003474 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003475 }
3476
Amith Yamasani04e0d262012-02-14 11:50:53 -08003477 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07003478 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003479 long identityToken = clearCallingIdentity();
3480 try {
3481 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3482 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
3483 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003484
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003485 if (intent.getComponent() != null &&
3486 GrantCredentialsPermissionActivity.class.getName().equals(
3487 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003488 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003489 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003490 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07003491 intent.addCategory(String.valueOf(notificationId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003492 Notification n = new Notification(android.R.drawable.stat_sys_warning, null,
3493 0 /* when */);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003494 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003495 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07003496 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003497 contextForUser.getText(R.string.notification_title).toString();
Alan Viverette4a357cd2015-03-18 18:37:18 -07003498 n.color = contextForUser.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003499 com.android.internal.R.color.system_notification_accent_color);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003500 n.setLatestEventInfo(contextForUser,
Fred Quintana33f889a2009-09-14 17:31:26 -07003501 String.format(notificationTitleFormat, account.name),
Dianne Hackborn41203752012-08-31 14:05:51 -07003502 message, PendingIntent.getActivityAsUser(
3503 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003504 null, user));
3505 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003506 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003507 } finally {
3508 restoreCallingIdentity(identityToken);
3509 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003510 }
3511
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003512 protected void installNotification(final int notificationId, final Notification n,
3513 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08003514 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003515 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08003516 }
3517
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003518 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003519 long identityToken = clearCallingIdentity();
3520 try {
3521 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003522 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003523 } finally {
3524 restoreCallingIdentity(identityToken);
3525 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003526 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003527
Fred Quintanab38eb142010-02-24 13:40:54 -08003528 /** Succeeds if any of the specified permissions are granted. */
3529 private void checkBinderPermission(String... permissions) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003530 final int uid = Binder.getCallingUid();
Fred Quintanab38eb142010-02-24 13:40:54 -08003531
3532 for (String perm : permissions) {
3533 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
3534 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003535 Log.v(TAG, " caller uid " + uid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08003536 }
3537 return;
3538 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003539 }
Fred Quintanab38eb142010-02-24 13:40:54 -08003540 String msg = "caller uid " + uid + " lacks any of " + TextUtils.join(",", permissions);
Fred Quintana56285a62010-12-02 14:20:51 -08003541 Log.w(TAG, " " + msg);
Fred Quintanab38eb142010-02-24 13:40:54 -08003542 throw new SecurityException(msg);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003543 }
3544
Amith Yamasani67df64b2012-12-14 12:09:36 -08003545 private int handleIncomingUser(int userId) {
3546 try {
3547 return ActivityManagerNative.getDefault().handleIncomingUser(
3548 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
3549 } catch (RemoteException re) {
3550 // Shouldn't happen, local.
3551 }
3552 return userId;
3553 }
3554
Christopher Tateccbf84f2013-05-08 15:25:41 -07003555 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003556 final int callingUserId = UserHandle.getUserId(callingUid);
3557
3558 final PackageManager userPackageManager;
3559 try {
3560 userPackageManager = mContext.createPackageContextAsUser(
3561 "android", 0, new UserHandle(callingUserId)).getPackageManager();
3562 } catch (NameNotFoundException e) {
3563 return false;
3564 }
3565
3566 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07003567 for (String name : packages) {
3568 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003569 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08003570 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08003571 && (packageInfo.applicationInfo.privateFlags
3572 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07003573 return true;
3574 }
3575 } catch (PackageManager.NameNotFoundException e) {
3576 return false;
3577 }
3578 }
3579 return false;
3580 }
3581
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003582 private boolean permissionIsGranted(Account account, String authTokenType, int callerUid) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07003583 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07003584 final boolean fromAuthenticator = account != null
3585 && hasAuthenticatorUid(account.type, callerUid);
3586 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08003587 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003588 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3589 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08003590 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003591 + ": is authenticator? " + fromAuthenticator
3592 + ", has explicit permission? " + hasExplicitGrants);
3593 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07003594 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003595 }
3596
Fred Quintana1a231912009-10-15 11:31:30 -07003597 private boolean hasAuthenticatorUid(String accountType, int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003598 final int callingUserId = UserHandle.getUserId(callingUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003599 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003600 mAuthenticatorCache.getAllServices(callingUserId)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003601 if (serviceInfo.type.type.equals(accountType)) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003602 return (serviceInfo.uid == callingUid) ||
Fred Quintana56285a62010-12-02 14:20:51 -08003603 (mPackageManager.checkSignatures(serviceInfo.uid, callingUid)
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003604 == PackageManager.SIGNATURE_MATCH);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003605 }
3606 }
3607 return false;
3608 }
3609
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003610 private boolean isAccountPresentForCaller(String accountName, String accountType) {
3611 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
3612 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
3613 if (account.name.equals(accountName)) {
3614 return true;
3615 }
3616 }
3617 }
3618 return false;
3619 }
3620
Amith Yamasani04e0d262012-02-14 11:50:53 -08003621 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
3622 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003623 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003624 return true;
3625 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003626 UserAccounts accounts = getUserAccountsForCaller();
3627 synchronized (accounts.cacheLock) {
3628 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
3629 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003630 account.name, account.type};
3631 final boolean permissionGranted =
3632 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
3633 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
3634 // TODO: Skip this check when running automated tests. Replace this
3635 // with a more general solution.
3636 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08003637 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003638 + " but ignoring since device is in test harness.");
3639 return true;
3640 }
3641 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003642 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003643 }
3644
3645 private void checkCallingUidAgainstAuthenticator(Account account) {
3646 final int uid = Binder.getCallingUid();
Fred Quintana31957f12009-10-21 13:43:10 -07003647 if (account == null || !hasAuthenticatorUid(account.type, uid)) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003648 String msg = "caller uid " + uid + " is different than the authenticator's uid";
3649 Log.w(TAG, msg);
3650 throw new SecurityException(msg);
3651 }
3652 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3653 Log.v(TAG, "caller uid " + uid + " is the same as the authenticator's uid");
3654 }
3655 }
3656
3657 private void checkAuthenticateAccountsPermission(Account account) {
3658 checkBinderPermission(Manifest.permission.AUTHENTICATE_ACCOUNTS);
3659 checkCallingUidAgainstAuthenticator(account);
3660 }
3661
3662 private void checkReadAccountsPermission() {
3663 checkBinderPermission(Manifest.permission.GET_ACCOUNTS);
3664 }
3665
3666 private void checkManageAccountsPermission() {
3667 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS);
3668 }
3669
Fred Quintanab38eb142010-02-24 13:40:54 -08003670 private void checkManageAccountsOrUseCredentialsPermissions() {
3671 checkBinderPermission(Manifest.permission.MANAGE_ACCOUNTS,
3672 Manifest.permission.USE_CREDENTIALS);
3673 }
3674
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003675 private boolean canUserModifyAccounts(int userId) {
3676 if (getUserManager().getUserRestrictions(new UserHandle(userId))
3677 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
3678 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003679 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003680 return true;
3681 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003682
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003683 private boolean canUserModifyAccountsForType(int userId, String accountType) {
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003684 DevicePolicyManager dpm = (DevicePolicyManager) mContext
3685 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003686 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02003687 if (typesArray == null) {
3688 return true;
3689 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01003690 for (String forbiddenType : typesArray) {
3691 if (forbiddenType.equals(accountType)) {
3692 return false;
3693 }
3694 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08003695 return true;
3696 }
3697
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003698 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07003699 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
3700 throws RemoteException {
3701 final int callingUid = getCallingUid();
3702
Amith Yamasani27db4682013-03-30 17:07:47 -07003703 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07003704 throw new SecurityException();
3705 }
3706
3707 if (value) {
3708 grantAppPermission(account, authTokenType, uid);
3709 } else {
3710 revokeAppPermission(account, authTokenType, uid);
3711 }
3712 }
3713
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003714 /**
3715 * Allow callers with the given uid permission to get credentials for account/authTokenType.
3716 * <p>
3717 * Although this is public it can only be accessed via the AccountManagerService object
3718 * which is in the system. This means we don't need to protect it with permissions.
3719 * @hide
3720 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003721 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003722 if (account == null || authTokenType == null) {
3723 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003724 return;
3725 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003726 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003727 synchronized (accounts.cacheLock) {
3728 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003729 db.beginTransaction();
3730 try {
3731 long accountId = getAccountIdLocked(db, account);
3732 if (accountId >= 0) {
3733 ContentValues values = new ContentValues();
3734 values.put(GRANTS_ACCOUNTS_ID, accountId);
3735 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
3736 values.put(GRANTS_GRANTEE_UID, uid);
3737 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
3738 db.setTransactionSuccessful();
3739 }
3740 } finally {
3741 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003742 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003743 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3744 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003745 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003746 }
3747
3748 /**
3749 * Don't allow callers with the given uid permission to get credentials for
3750 * account/authTokenType.
3751 * <p>
3752 * Although this is public it can only be accessed via the AccountManagerService object
3753 * which is in the system. This means we don't need to protect it with permissions.
3754 * @hide
3755 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07003756 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07003757 if (account == null || authTokenType == null) {
3758 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07003759 return;
3760 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003761 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003762 synchronized (accounts.cacheLock) {
3763 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003764 db.beginTransaction();
3765 try {
3766 long accountId = getAccountIdLocked(db, account);
3767 if (accountId >= 0) {
3768 db.delete(TABLE_GRANTS,
3769 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
3770 + GRANTS_GRANTEE_UID + "=?",
3771 new String[]{String.valueOf(accountId), authTokenType,
3772 String.valueOf(uid)});
3773 db.setTransactionSuccessful();
3774 }
3775 } finally {
3776 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003777 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003778 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
3779 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003780 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003781 }
Fred Quintana56285a62010-12-02 14:20:51 -08003782
3783 static final private String stringArrayToString(String[] value) {
3784 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
3785 }
3786
Amith Yamasani04e0d262012-02-14 11:50:53 -08003787 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
3788 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003789 if (oldAccountsForType != null) {
3790 ArrayList<Account> newAccountsList = new ArrayList<Account>();
3791 for (Account curAccount : oldAccountsForType) {
3792 if (!curAccount.equals(account)) {
3793 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003794 }
3795 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003796 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003797 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003798 } else {
3799 Account[] newAccountsForType = new Account[newAccountsList.size()];
3800 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003801 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003802 }
Fred Quintana56285a62010-12-02 14:20:51 -08003803 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003804 accounts.userDataCache.remove(account);
3805 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003806 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003807 }
3808
3809 /**
3810 * This assumes that the caller has already checked that the account is not already present.
3811 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08003812 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
3813 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003814 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
3815 Account[] newAccountsForType = new Account[oldLength + 1];
3816 if (accountsForType != null) {
3817 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08003818 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003819 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003820 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08003821 }
3822
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003823 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07003824 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003825 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07003826 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003827 return unfiltered;
3828 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003829 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
3830 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003831 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003832 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003833 // otherwise return non-shared accounts only.
3834 // This might be a temporary way to specify a whitelist
3835 String whiteList = mContext.getResources().getString(
3836 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
3837 for (String packageName : packages) {
3838 if (whiteList.contains(";" + packageName + ";")) {
3839 return unfiltered;
3840 }
3841 }
3842 ArrayList<Account> allowed = new ArrayList<Account>();
3843 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
3844 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003845 String requiredAccountType = "";
3846 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07003847 // If there's an explicit callingPackage specified, check if that package
3848 // opted in to see restricted accounts.
3849 if (callingPackage != null) {
3850 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003851 if (pi != null && pi.restrictedAccountType != null) {
3852 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07003853 }
3854 } else {
3855 // Otherwise check if the callingUid has a package that has opted in
3856 for (String packageName : packages) {
3857 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
3858 if (pi != null && pi.restrictedAccountType != null) {
3859 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07003860 break;
3861 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003862 }
3863 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003864 } catch (NameNotFoundException nnfe) {
3865 }
3866 for (Account account : unfiltered) {
3867 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003868 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07003869 } else {
3870 boolean found = false;
3871 for (Account shared : sharedAccounts) {
3872 if (shared.equals(account)) {
3873 found = true;
3874 break;
3875 }
3876 }
3877 if (!found) {
3878 allowed.add(account);
3879 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003880 }
3881 }
3882 Account[] filtered = new Account[allowed.size()];
3883 allowed.toArray(filtered);
3884 return filtered;
3885 } else {
3886 return unfiltered;
3887 }
3888 }
3889
Amith Yamasani27db4682013-03-30 17:07:47 -07003890 /*
3891 * packageName can be null. If not null, it should be used to filter out restricted accounts
3892 * that the package is not allowed to access.
3893 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003894 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07003895 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003896 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003897 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003898 if (accounts == null) {
3899 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08003900 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003901 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07003902 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003903 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003904 } else {
3905 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003906 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003907 totalLength += accounts.length;
3908 }
3909 if (totalLength == 0) {
3910 return EMPTY_ACCOUNT_ARRAY;
3911 }
3912 Account[] accounts = new Account[totalLength];
3913 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003914 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003915 System.arraycopy(accountsOfType, 0, accounts, totalLength,
3916 accountsOfType.length);
3917 totalLength += accountsOfType.length;
3918 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003919 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08003920 }
3921 }
3922
Amith Yamasani04e0d262012-02-14 11:50:53 -08003923 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3924 Account account, String key, String value) {
3925 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003926 if (userDataForAccount == null) {
3927 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003928 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003929 }
3930 if (value == null) {
3931 userDataForAccount.remove(key);
3932 } else {
3933 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003934 }
3935 }
3936
Carlos Valdivia91979be2015-05-22 14:11:35 -07003937 protected String readCachedTokenInternal(
3938 UserAccounts accounts,
3939 Account account,
3940 String tokenType,
3941 String callingPackage,
3942 byte[] pkgSigDigest) {
3943 synchronized (accounts.cacheLock) {
3944 TokenCache cache = getTokenCacheForAccountLocked(accounts, account);
3945 return cache.get(tokenType, callingPackage, pkgSigDigest);
3946 }
3947 }
3948
Amith Yamasani04e0d262012-02-14 11:50:53 -08003949 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
3950 Account account, String key, String value) {
3951 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003952 if (authTokensForAccount == null) {
3953 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003954 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003955 }
3956 if (value == null) {
3957 authTokensForAccount.remove(key);
3958 } else {
3959 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08003960 }
3961 }
3962
Amith Yamasani04e0d262012-02-14 11:50:53 -08003963 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
3964 String authTokenType) {
3965 synchronized (accounts.cacheLock) {
3966 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003967 if (authTokensForAccount == null) {
3968 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003969 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003970 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003971 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003972 }
3973 return authTokensForAccount.get(authTokenType);
3974 }
3975 }
3976
Amith Yamasani04e0d262012-02-14 11:50:53 -08003977 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
3978 synchronized (accounts.cacheLock) {
3979 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08003980 if (userDataForAccount == null) {
3981 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08003982 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003983 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003984 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08003985 }
3986 return userDataForAccount.get(key);
3987 }
3988 }
3989
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003990 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
3991 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08003992 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08003993 Cursor cursor = db.query(TABLE_EXTRAS,
3994 COLUMNS_EXTRAS_KEY_AND_VALUE,
3995 SELECTION_USERDATA_BY_ACCOUNT,
3996 new String[]{account.name, account.type},
3997 null, null, null);
3998 try {
3999 while (cursor.moveToNext()) {
4000 final String tmpkey = cursor.getString(0);
4001 final String value = cursor.getString(1);
4002 userDataForAccount.put(tmpkey, value);
4003 }
4004 } finally {
4005 cursor.close();
4006 }
4007 return userDataForAccount;
4008 }
4009
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004010 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
4011 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004012 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004013 Cursor cursor = db.query(TABLE_AUTHTOKENS,
4014 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
4015 SELECTION_AUTHTOKENS_BY_ACCOUNT,
4016 new String[]{account.name, account.type},
4017 null, null, null);
4018 try {
4019 while (cursor.moveToNext()) {
4020 final String type = cursor.getString(0);
4021 final String authToken = cursor.getString(1);
4022 authTokensForAccount.put(type, authToken);
4023 }
4024 } finally {
4025 cursor.close();
4026 }
4027 return authTokensForAccount;
4028 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004029
Carlos Valdivia91979be2015-05-22 14:11:35 -07004030 protected TokenCache getTokenCacheForAccountLocked(UserAccounts accounts, Account account) {
4031 WeakReference<TokenCache> cacheRef = accounts.accountTokenCaches.get(account);
4032 TokenCache cache;
4033 if (cacheRef == null || (cache = cacheRef.get()) == null) {
4034 cache = new TokenCache();
4035 cacheRef = new WeakReference<>(cache);
4036 accounts.accountTokenCaches.put(account, cacheRef);
4037 }
4038 return cache;
4039 }
4040
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004041 private Context getContextForUser(UserHandle user) {
4042 try {
4043 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
4044 } catch (NameNotFoundException e) {
4045 // Default to mContext, not finding the package system is running as is unlikely.
4046 return mContext;
4047 }
4048 }
Fred Quintana60307342009-03-24 22:48:12 -07004049}