blob: 96214d6b1a082c85ea3d24d08e0ee16aeb6796ae [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;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070032import android.annotation.NonNull;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080033import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070034import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070035import android.app.AppGlobals;
Svetoslavf3f02ac2015-09-08 14:36:35 -070036import android.app.AppOpsManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000040import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010041import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000042import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070043import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070044import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070045import android.content.ContentValues;
46import android.content.Context;
47import android.content.Intent;
48import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070049import android.content.ServiceConnection;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -080050import android.content.pm.ActivityInfo;
Doug Zongker885cfc232009-10-21 16:52:44 -070051import android.content.pm.ApplicationInfo;
52import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070053import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070054import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070055import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070056import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070057import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070058import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070059import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070060import android.database.Cursor;
61import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import android.database.sqlite.SQLiteDatabase;
63import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070064import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070065import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080067import android.os.Environment;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070068import android.os.FileUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.os.IBinder;
71import android.os.Looper;
72import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070073import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070074import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070075import android.os.RemoteException;
76import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070077import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070078import android.os.UserManager;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070079import android.os.storage.StorageManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070080import android.text.TextUtils;
81import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070082import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070083import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080084import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070085import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070086
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070087import com.android.internal.R;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070088import com.android.internal.annotations.VisibleForTesting;
Amith Yamasani67df64b2012-12-14 12:09:36 -080089import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080090import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -070091import com.android.internal.util.Preconditions;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070092import com.android.server.FgThread;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000093import com.android.server.LocalServices;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -060094import com.android.server.SystemService;
95
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070096import com.google.android.collect.Lists;
97import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070098
Oscar Montemayora8529f62009-11-18 10:14:20 -080099import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700100import java.io.FileDescriptor;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700101import java.io.IOException;
Fred Quintanaa698f422009-04-08 19:14:54 -0700102import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800103import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700104import java.security.MessageDigest;
105import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700106import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700107import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800108import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700109import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700110import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700111import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700112import java.util.HashSet;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800113import java.util.Iterator;
Fred Quintana56285a62010-12-02 14:20:51 -0800114import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700115import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800116import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800117import java.util.Map.Entry;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700118import java.util.concurrent.atomic.AtomicInteger;
119import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700120
Fred Quintana60307342009-03-24 22:48:12 -0700121/**
122 * A system service that provides account, password, and authtoken management for all
123 * accounts on the device. Some of these calls are implemented with the help of the corresponding
124 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
125 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700126 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700127 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700128 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700129public class AccountManagerService
130 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800131 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700132 private static final String TAG = "AccountManagerService";
133
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600134 public static class Lifecycle extends SystemService {
135 private AccountManagerService mService;
136
137 public Lifecycle(Context context) {
138 super(context);
139 }
140
141 @Override
142 public void onStart() {
143 mService = new AccountManagerService(getContext());
144 publishBinderService(Context.ACCOUNT_SERVICE, mService);
145 }
146
147 @Override
148 public void onBootPhase(int phase) {
149 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
150 mService.systemReady();
151 }
152 }
153
154 @Override
155 public void onUnlockUser(int userHandle) {
156 mService.onUnlockUser(userHandle);
157 }
158 }
159
Fred Quintana60307342009-03-24 22:48:12 -0700160 private static final String DATABASE_NAME = "accounts.db";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700161 private static final int PRE_N_DATABASE_VERSION = 9;
162 private static final int CE_DATABASE_VERSION = 10;
163 private static final int DE_DATABASE_VERSION = 1;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700164
165 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700166
167 private final Context mContext;
168
Fred Quintana56285a62010-12-02 14:20:51 -0800169 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700170 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800172
Fred Quintana60307342009-03-24 22:48:12 -0700173 private final MessageHandler mMessageHandler;
174
175 // Messages that can be sent on mHandler
176 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700177 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700178
Fred Quintana56285a62010-12-02 14:20:51 -0800179 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700180
181 private static final String TABLE_ACCOUNTS = "accounts";
182 private static final String ACCOUNTS_ID = "_id";
183 private static final String ACCOUNTS_NAME = "name";
184 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700185 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700186 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700187 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800188 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
189 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700190
191 private static final String TABLE_AUTHTOKENS = "authtokens";
192 private static final String AUTHTOKENS_ID = "_id";
193 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
194 private static final String AUTHTOKENS_TYPE = "type";
195 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
196
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700197 private static final String TABLE_GRANTS = "grants";
198 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
199 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
200 private static final String GRANTS_GRANTEE_UID = "uid";
201
Fred Quintana60307342009-03-24 22:48:12 -0700202 private static final String TABLE_EXTRAS = "extras";
203 private static final String EXTRAS_ID = "_id";
204 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
205 private static final String EXTRAS_KEY = "key";
206 private static final String EXTRAS_VALUE = "value";
207
208 private static final String TABLE_META = "meta";
209 private static final String META_KEY = "key";
210 private static final String META_VALUE = "value";
211
Amith Yamasani67df64b2012-12-14 12:09:36 -0800212 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700213 private static final String SHARED_ACCOUNTS_ID = "_id";
214
215 private static final String PRE_N_DATABASE_NAME = "accounts.db";
216 private static final String CE_DATABASE_NAME = "accounts_ce.db";
217 private static final String DE_DATABASE_NAME = "accounts_de.db";
218 private static final String CE_DB_PREFIX = "ceDb.";
219 private static final String CE_TABLE_ACCOUNTS = CE_DB_PREFIX + TABLE_ACCOUNTS;
220 private static final String CE_TABLE_AUTHTOKENS = CE_DB_PREFIX + TABLE_AUTHTOKENS;
221 private static final String CE_TABLE_EXTRAS = CE_DB_PREFIX + TABLE_EXTRAS;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800222
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700223 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
224 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700225 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800226
Carlos Valdivia91979be2015-05-22 14:11:35 -0700227 static {
228 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
229 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
230 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700231
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700232 private static final String COUNT_OF_MATCHING_GRANTS = ""
233 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
234 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
235 + " AND " + GRANTS_GRANTEE_UID + "=?"
236 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
237 + " AND " + ACCOUNTS_NAME + "=?"
238 + " AND " + ACCOUNTS_TYPE + "=?";
239
Fred Quintana56285a62010-12-02 14:20:51 -0800240 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
241 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700242
Fred Quintana56285a62010-12-02 14:20:51 -0800243 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
244 AUTHTOKENS_AUTHTOKEN};
245
246 private static final String SELECTION_USERDATA_BY_ACCOUNT =
247 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
248 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
249
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800250 private static final String META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX =
251 "auth_uid_for_type:";
252 private static final String META_KEY_DELIMITER = ":";
253 private static final String SELECTION_META_BY_AUTHENTICATOR_TYPE = META_KEY + " LIKE ?";
254
Fred Quintanaa698f422009-04-08 19:14:54 -0700255 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700256 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
257
Amith Yamasani04e0d262012-02-14 11:50:53 -0800258 static class UserAccounts {
259 private final int userId;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700260 private final DeDatabaseHelper openHelper;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800261 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
262 credentialsPermissionNotificationIds =
263 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
264 private final HashMap<Account, Integer> signinRequiredNotificationIds =
265 new HashMap<Account, Integer>();
266 private final Object cacheLock = new Object();
267 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700268 private final HashMap<String, Account[]> accountCache =
269 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800270 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800271 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800272 new HashMap<Account, HashMap<String, String>>();
273 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800274 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800275 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700276
277 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700278 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700279
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700280 /**
281 * protected by the {@link #cacheLock}
282 *
283 * Caches the previous names associated with an account. Previous names
284 * should be cached because we expect that when an Account is renamed,
285 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
286 * want to know if the accounts they care about have been renamed.
287 *
288 * The previous names are wrapped in an {@link AtomicReference} so that
289 * we can distinguish between those accounts with no previous names and
290 * those whose previous names haven't been cached (yet).
291 */
292 private final HashMap<Account, AtomicReference<String>> previousNameCache =
293 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800294
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700295 private int debugDbInsertionPoint = -1;
296 private SQLiteStatement statementForLogging;
297
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700298 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800299 this.userId = userId;
300 synchronized (cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700301 openHelper = DeDatabaseHelper.create(context, userId, preNDbFile, deDbFile);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800302 }
303 }
304 }
305
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700306 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600307 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800308
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700309 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700310 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700311
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700312 /**
313 * This should only be called by system code. One should only call this after the service
314 * has started.
315 * @return a reference to the AccountManagerService instance
316 * @hide
317 */
318 public static AccountManagerService getSingleton() {
319 return sThis.get();
320 }
Fred Quintana60307342009-03-24 22:48:12 -0700321
Fred Quintana56285a62010-12-02 14:20:51 -0800322 public AccountManagerService(Context context) {
323 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700324 }
325
Fred Quintana56285a62010-12-02 14:20:51 -0800326 public AccountManagerService(Context context, PackageManager packageManager,
327 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700328 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800329 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700330 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700331
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700332 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700333
Fred Quintana56285a62010-12-02 14:20:51 -0800334 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800335 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700336
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700337 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800338
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800339 IntentFilter intentFilter = new IntentFilter();
340 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
341 intentFilter.addDataScheme("package");
342 mContext.registerReceiver(new BroadcastReceiver() {
343 @Override
344 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700345 // Don't delete accounts when updating a authenticator's
346 // package.
347 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700348 /* Purging data requires file io, don't block the main thread. This is probably
349 * less than ideal because we are introducing a race condition where old grants
350 * could be exercised until they are purged. But that race condition existed
351 * anyway with the broadcast receiver.
352 *
353 * Ideally, we would completely clear the cache, purge data from the database,
354 * and then rebuild the cache. All under the cache lock. But that change is too
355 * large at this point.
356 */
357 Runnable r = new Runnable() {
358 @Override
359 public void run() {
360 purgeOldGrantsAll();
361 }
362 };
363 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700364 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800365 }
366 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800367
Amith Yamasani13593602012-03-22 16:16:17 -0700368 IntentFilter userFilter = new IntentFilter();
369 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800370 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700371 @Override
372 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800373 String action = intent.getAction();
374 if (Intent.ACTION_USER_REMOVED.equals(action)) {
375 onUserRemoved(intent);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800376 }
Amith Yamasani13593602012-03-22 16:16:17 -0700377 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800378 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800379 }
380
Dianne Hackborn164371f2013-10-01 19:10:13 -0700381 @Override
382 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
383 throws RemoteException {
384 try {
385 return super.onTransact(code, data, reply, flags);
386 } catch (RuntimeException e) {
387 // The account manager only throws security exceptions, so let's
388 // log all others.
389 if (!(e instanceof SecurityException)) {
390 Slog.wtf(TAG, "Account Manager Crash", e);
391 }
392 throw e;
393 }
394 }
395
Kenny Root26ff6622012-07-30 12:58:03 -0700396 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700397 }
398
Amith Yamasani258848d2012-08-10 17:06:33 -0700399 private UserManager getUserManager() {
400 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700401 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700402 }
403 return mUserManager;
404 }
405
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700406 /**
407 * Validate internal set of accounts against installed authenticators for
408 * given user. Clears cached authenticators before validating.
409 */
410 public void validateAccounts(int userId) {
411 final UserAccounts accounts = getUserAccounts(userId);
412
413 // Invalidate user-specific cache to make sure we catch any
414 // removed authenticators.
415 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
416 }
417
418 /**
419 * Validate internal set of accounts against installed authenticators for
420 * given user. Clear cached authenticators before validating when requested.
421 */
422 private void validateAccountsInternal(
423 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700424 if (Log.isLoggable(TAG, Log.DEBUG)) {
425 Log.d(TAG, "validateAccountsInternal " + accounts.userId
426 + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600427 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700428 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700429 if (invalidateAuthenticatorCache) {
430 mAuthenticatorCache.invalidateCache(accounts.userId);
431 }
432
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800433 final HashMap<String, Integer> knownAuth = new HashMap<>();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700434 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
435 mAuthenticatorCache.getAllServices(accounts.userId)) {
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800436 knownAuth.put(service.type.type, service.uid);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700437 }
438
Amith Yamasani04e0d262012-02-14 11:50:53 -0800439 synchronized (accounts.cacheLock) {
440 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800441 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800442
443 // Get a list of stored authenticator type and UID
444 Cursor metaCursor = db.query(
445 TABLE_META,
446 new String[] {META_KEY, META_VALUE},
447 SELECTION_META_BY_AUTHENTICATOR_TYPE,
448 new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
449 null /* groupBy */,
450 null /* having */,
451 META_KEY);
452 // Create a list of authenticator type whose previous uid no longer exists
453 HashSet<String> obsoleteAuthType = Sets.newHashSet();
454 try {
455 while (metaCursor.moveToNext()) {
456 String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
457 String uid = metaCursor.getString(1);
458 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uid)) {
459 // Should never happen.
460 Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
461 + ", uid empty: " + TextUtils.isEmpty(uid));
462 continue;
463 }
464 Integer knownUid = knownAuth.get(type);
465 if (knownUid != null && uid.equals(knownUid.toString())) {
466 // Remove it from the knownAuth list if it's unchanged.
467 knownAuth.remove(type);
468 } else {
469 // Only add it to the list if it no longer exists or uid different
470 obsoleteAuthType.add(type);
471 // And delete it from the TABLE_META
472 db.delete(
473 TABLE_META,
474 META_KEY + "=? AND " + META_VALUE + "=?",
475 new String[] {
476 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
477 uid}
478 );
479 }
480 }
481 } finally {
482 metaCursor.close();
483 }
484
485 // Add the newly registered authenticator to TABLE_META
486 Iterator<Entry<String, Integer>> iterator = knownAuth.entrySet().iterator();
487 while (iterator.hasNext()) {
488 Entry<String, Integer> entry = iterator.next();
489 ContentValues values = new ContentValues();
490 values.put(META_KEY,
491 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
492 values.put(META_VALUE, entry.getValue());
493 db.insert(TABLE_META, null, values);
494 }
495
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800496 Cursor cursor = db.query(TABLE_ACCOUNTS,
497 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800498 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800499 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800500 accounts.accountCache.clear();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700501 final HashMap<String, ArrayList<String>> accountNamesByType = new LinkedHashMap<>();
Fred Quintana56285a62010-12-02 14:20:51 -0800502 while (cursor.moveToNext()) {
503 final long accountId = cursor.getLong(0);
504 final String accountType = cursor.getString(1);
505 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700506
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800507 if (obsoleteAuthType.contains(accountType)) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700508 Slog.w(TAG, "deleting account " + accountName + " because type "
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800509 + accountType + "'s registered authenticator no longer exist.");
Fred Quintana56285a62010-12-02 14:20:51 -0800510 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
511 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700512
513 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
514 accountId, accounts);
515
Fred Quintana56285a62010-12-02 14:20:51 -0800516 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800517 accounts.userDataCache.remove(account);
518 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700519 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800520 } else {
521 ArrayList<String> accountNames = accountNamesByType.get(accountType);
522 if (accountNames == null) {
523 accountNames = new ArrayList<String>();
524 accountNamesByType.put(accountType, accountNames);
525 }
526 accountNames.add(accountName);
527 }
528 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700529 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800530 final String accountType = cur.getKey();
531 final ArrayList<String> accountNames = cur.getValue();
532 final Account[] accountsForType = new Account[accountNames.size()];
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700533 for (int i = 0; i < accountsForType.length; i++) {
534 accountsForType[i] = new Account(accountNames.get(i), accountType);
Fred Quintana56285a62010-12-02 14:20:51 -0800535 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800536 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800537 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800538 } finally {
539 cursor.close();
540 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800541 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800542 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800543 }
544 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700545 }
546
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800547 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
548 Context context,
549 int userId) {
550 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
551 HashMap<String, Integer> knownAuth = new HashMap<>();
552 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
553 .getAllServices(userId)) {
554 knownAuth.put(service.type.type, service.uid);
555 }
556 return knownAuth;
557 }
558
Amith Yamasani04e0d262012-02-14 11:50:53 -0800559 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700560 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800561 }
562
563 protected UserAccounts getUserAccounts(int userId) {
564 synchronized (mUsers) {
565 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700566 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800567 if (accounts == null) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700568 File preNDbFile = new File(getPreNDatabaseName(userId));
569 File deDbFile = new File(getDeDatabaseName(userId));
570 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700571 initializeDebugDbSizeAndCompileSqlStatementForLogging(
572 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800573 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700574 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700575 validateAccounts = true;
576 }
577 // open CE database if necessary
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600578 if (!accounts.openHelper.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700579 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
580 synchronized (accounts.cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700581 File preNDatabaseFile = new File(getPreNDatabaseName(userId));
582 File ceDatabaseFile = new File(getCeDatabaseName(userId));
583 CeDatabaseHelper.create(mContext, userId, preNDatabaseFile, ceDatabaseFile);
584 accounts.openHelper.attachCeDatabase(ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700585 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700586 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700587 }
588 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700589 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800590 }
591 return accounts;
592 }
593 }
594
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700595 private void syncDeCeAccountsLocked(UserAccounts accounts) {
596 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
597 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
598 List<Account> accountsToRemove = CeDatabaseHelper.findCeAccountsNotInDe(db);
599 if (!accountsToRemove.isEmpty()) {
600 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
601 + accounts.userId + " was locked. Removing accounts from CE tables");
602 logRecord(accounts, DebugDbHelper.ACTION_SYNC_DE_CE_ACCOUNTS, TABLE_ACCOUNTS);
603
604 for (Account account : accountsToRemove) {
605 removeAccountInternal(accounts, account, Process.myUid());
606 }
607 }
608 }
609
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700610 private void purgeOldGrantsAll() {
611 synchronized (mUsers) {
612 for (int i = 0; i < mUsers.size(); i++) {
613 purgeOldGrants(mUsers.valueAt(i));
614 }
615 }
616 }
617
618 private void purgeOldGrants(UserAccounts accounts) {
619 synchronized (accounts.cacheLock) {
620 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
621 final Cursor cursor = db.query(TABLE_GRANTS,
622 new String[]{GRANTS_GRANTEE_UID},
623 null, null, GRANTS_GRANTEE_UID, null, null);
624 try {
625 while (cursor.moveToNext()) {
626 final int uid = cursor.getInt(0);
627 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
628 if (packageExists) {
629 continue;
630 }
631 Log.d(TAG, "deleting grants for UID " + uid
632 + " because its package is no longer installed");
633 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
634 new String[]{Integer.toString(uid)});
635 }
636 } finally {
637 cursor.close();
638 }
639 }
640 }
641
Amith Yamasani13593602012-03-22 16:16:17 -0700642 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700643 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700644 if (userId < 1) return;
645
646 UserAccounts accounts;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700647 boolean userUnlocked;
Amith Yamasani13593602012-03-22 16:16:17 -0700648 synchronized (mUsers) {
649 accounts = mUsers.get(userId);
650 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600651 userUnlocked = mLocalUnlockedUsers.get(userId);
652 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700653 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700654 if (accounts != null) {
655 synchronized (accounts.cacheLock) {
656 accounts.openHelper.close();
657 }
Amith Yamasani13593602012-03-22 16:16:17 -0700658 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700659 Log.i(TAG, "Removing database files for user " + userId);
660 File dbFile = new File(getDeDatabaseName(userId));
Amith Yamasani13593602012-03-22 16:16:17 -0700661
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700662 deleteDbFileWarnIfFailed(dbFile);
663 // Remove CE file if user is unlocked, or FBE is not enabled
664 boolean fbeEnabled = StorageManager.isFileEncryptedNativeOrEmulated();
665 if (!fbeEnabled || userUnlocked) {
666 File ceDb = new File(getCeDatabaseName(userId));
667 if (ceDb.exists()) {
668 deleteDbFileWarnIfFailed(ceDb);
669 }
670 }
671 }
672
673 private static void deleteDbFileWarnIfFailed(File dbFile) {
674 if (!SQLiteDatabase.deleteDatabase(dbFile)) {
675 Log.w(TAG, "Database at " + dbFile + " was not deleted successfully");
Amith Yamasani13593602012-03-22 16:16:17 -0700676 }
677 }
678
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700679 @VisibleForTesting
680 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600681 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
682 }
683
684 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700685 if (Log.isLoggable(TAG, Log.VERBOSE)) {
686 Log.v(TAG, "onUserUnlocked " + userId);
687 }
688 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600689 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700690 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800691 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700692 syncSharedAccounts(userId);
693 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800694
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700695 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800696 // Check if there's a shared account that needs to be created as an account
697 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
698 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700699 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700700 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -0700701 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700702 : UserHandle.USER_SYSTEM;
703 if (parentUserId < 0) {
704 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
705 return;
706 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800707 for (Account sa : sharedAccounts) {
708 if (ArrayUtils.contains(accounts, sa)) continue;
709 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700710 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800711 }
712 }
713
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700714 @Override
715 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700716 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700717 }
718
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800719 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700720 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700721 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800722 if (Log.isLoggable(TAG, Log.VERBOSE)) {
723 Log.v(TAG, "getPassword: " + account
724 + ", caller's uid " + Binder.getCallingUid()
725 + ", pid " + Binder.getCallingPid());
726 }
Fred Quintana382601f2010-03-25 12:25:10 -0700727 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000728 int userId = UserHandle.getCallingUserId();
729 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700730 String msg = String.format(
731 "uid %s cannot get secrets for accounts of type: %s",
732 callingUid,
733 account.type);
734 throw new SecurityException(msg);
735 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700736 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700737 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700738 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800739 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700740 } finally {
741 restoreCallingIdentity(identityToken);
742 }
743 }
744
Amith Yamasani04e0d262012-02-14 11:50:53 -0800745 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700746 if (account == null) {
747 return null;
748 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600749 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700750 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
751 return null;
752 }
Fred Quintana31957f12009-10-21 13:43:10 -0700753
Amith Yamasani04e0d262012-02-14 11:50:53 -0800754 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700755 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
756 return CeDatabaseHelper.findAccountPasswordByNameAndType(db, account.name,
757 account.type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700758 }
759 }
760
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800761 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700762 public String getPreviousName(Account account) {
763 if (Log.isLoggable(TAG, Log.VERBOSE)) {
764 Log.v(TAG, "getPreviousName: " + account
765 + ", caller's uid " + Binder.getCallingUid()
766 + ", pid " + Binder.getCallingPid());
767 }
768 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700769 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700770 long identityToken = clearCallingIdentity();
771 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700772 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700773 return readPreviousNameInternal(accounts, account);
774 } finally {
775 restoreCallingIdentity(identityToken);
776 }
777 }
778
779 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
780 if (account == null) {
781 return null;
782 }
783 synchronized (accounts.cacheLock) {
784 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
785 if (previousNameRef == null) {
786 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
787 Cursor cursor = db.query(
788 TABLE_ACCOUNTS,
789 new String[]{ ACCOUNTS_PREVIOUS_NAME },
790 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
791 new String[] { account.name, account.type },
792 null,
793 null,
794 null);
795 try {
796 if (cursor.moveToNext()) {
797 String previousName = cursor.getString(0);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700798 previousNameRef = new AtomicReference<>(previousName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700799 accounts.previousNameCache.put(account, previousNameRef);
800 return previousName;
801 } else {
802 return null;
803 }
804 } finally {
805 cursor.close();
806 }
807 } else {
808 return previousNameRef.get();
809 }
810 }
811 }
812
813 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700814 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700815 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800816 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700817 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
818 account, key, callingUid, Binder.getCallingPid());
819 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800820 }
Fred Quintana382601f2010-03-25 12:25:10 -0700821 if (account == null) throw new IllegalArgumentException("account is null");
822 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000823 int userId = UserHandle.getCallingUserId();
824 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700825 String msg = String.format(
826 "uid %s cannot get user data for accounts of type: %s",
827 callingUid,
828 account.type);
829 throw new SecurityException(msg);
830 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600831 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -0700832 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
833 return null;
834 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700835 long identityToken = clearCallingIdentity();
836 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700837 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +0000838 synchronized (accounts.cacheLock) {
839 if (!accountExistsCacheLocked(accounts, account)) {
840 return null;
841 }
842 return readUserDataInternalLocked(accounts, account, key);
843 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700844 } finally {
845 restoreCallingIdentity(identityToken);
846 }
847 }
848
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800849 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100850 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700851 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800852 if (Log.isLoggable(TAG, Log.VERBOSE)) {
853 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100854 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700855 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800856 + ", pid " + Binder.getCallingPid());
857 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100858 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700859 if (isCrossUser(callingUid, userId)) {
860 throw new SecurityException(
861 String.format(
862 "User %s tying to get authenticator types for %s" ,
863 UserHandle.getCallingUserId(),
864 userId));
865 }
866
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700867 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700868 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000869 return getAuthenticatorTypesInternal(userId);
870
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700871 } finally {
872 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700873 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700874 }
875
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000876 /**
877 * Should only be called inside of a clearCallingIdentity block.
878 */
879 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
880 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
881 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
882 AuthenticatorDescription[] types =
883 new AuthenticatorDescription[authenticatorCollection.size()];
884 int i = 0;
885 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
886 : authenticatorCollection) {
887 types[i] = authenticator.type;
888 i++;
889 }
890 return types;
891 }
892
893
894
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700895 private boolean isCrossUser(int callingUid, int userId) {
896 return (userId != UserHandle.getCallingUserId()
897 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100898 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700899 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
900 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100901 }
902
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700903 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700904 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600905 Bundle.setDefusable(extras, true);
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700906 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800907 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700908 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700909 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800910 + ", pid " + Binder.getCallingPid());
911 }
Fred Quintana382601f2010-03-25 12:25:10 -0700912 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000913 int userId = UserHandle.getCallingUserId();
914 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700915 String msg = String.format(
916 "uid %s cannot explicitly add accounts of type: %s",
917 callingUid,
918 account.type);
919 throw new SecurityException(msg);
920 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700921 /*
922 * Child users are not allowed to add accounts. Only the accounts that are
923 * shared by the parent profile can be added to child profile.
924 *
925 * TODO: Only allow accounts that were shared to be added by
926 * a limited user.
927 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700928
Fred Quintana60307342009-03-24 22:48:12 -0700929 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700930 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700931 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700932 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700933 return addAccountInternal(accounts, account, password, extras, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700934 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700935 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700936 }
937 }
938
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000939 @Override
940 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700941 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700942 int callingUid = Binder.getCallingUid();
943 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
944 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000945 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700946 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800947 final UserAccounts fromAccounts = getUserAccounts(userFrom);
948 final UserAccounts toAccounts = getUserAccounts(userTo);
949 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000950 if (response != null) {
951 Bundle result = new Bundle();
952 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
953 try {
954 response.onResult(result);
955 } catch (RemoteException e) {
956 Slog.w(TAG, "Failed to report error back to the client." + e);
957 }
958 }
959 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800960 }
961
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000962 Slog.d(TAG, "Copying account " + account.name
963 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800964 long identityToken = clearCallingIdentity();
965 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000966 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800967 false /* stripAuthTokenFromResult */, account.name,
968 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700969 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800970 protected String toDebugString(long now) {
971 return super.toDebugString(now) + ", getAccountCredentialsForClone"
972 + ", " + account.type;
973 }
974
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700975 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800976 public void run() throws RemoteException {
977 mAuthenticator.getAccountCredentialsForCloning(this, account);
978 }
979
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700980 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800981 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600982 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000983 if (result != null
984 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
985 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700986 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800987 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800988 super.onResult(result);
989 }
990 }
991 }.bind();
992 } finally {
993 restoreCallingIdentity(identityToken);
994 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800995 }
996
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800997 @Override
998 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700999 final int callingUid = Binder.getCallingUid();
1000 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1001 String msg = String.format(
1002 "accountAuthenticated( account: %s, callerUid: %s)",
1003 account,
1004 callingUid);
1005 Log.v(TAG, msg);
1006 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001007 if (account == null) {
1008 throw new IllegalArgumentException("account is null");
1009 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001010 int userId = UserHandle.getCallingUserId();
1011 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001012 String msg = String.format(
1013 "uid %s cannot notify authentication for accounts of type: %s",
1014 callingUid,
1015 account.type);
1016 throw new SecurityException(msg);
1017 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001018
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001019 if (!canUserModifyAccounts(userId, callingUid) ||
1020 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001021 return false;
1022 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001023
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001024 long identityToken = clearCallingIdentity();
1025 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001026 UserAccounts accounts = getUserAccounts(userId);
1027 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001028 } finally {
1029 restoreCallingIdentity(identityToken);
1030 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001031 }
1032
1033 private boolean updateLastAuthenticatedTime(Account account) {
1034 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001035 synchronized (accounts.cacheLock) {
1036 final ContentValues values = new ContentValues();
1037 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
1038 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1039 int i = db.update(
1040 TABLE_ACCOUNTS,
1041 values,
1042 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1043 new String[] {
1044 account.name, account.type
1045 });
1046 if (i > 0) {
1047 return true;
1048 }
1049 }
1050 return false;
1051 }
1052
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001053 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001054 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1055 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001056 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001057 long id = clearCallingIdentity();
1058 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001059 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001060 false /* stripAuthTokenFromResult */, account.name,
1061 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001062 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001063 protected String toDebugString(long now) {
1064 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1065 + ", " + account.type;
1066 }
1067
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001068 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001069 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001070 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001071 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001072 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -07001073 for (Account acc : getAccounts(parentUserId,
1074 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001075 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001076 mAuthenticator.addAccountFromCredentials(
1077 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001078 break;
1079 }
1080 }
1081 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001082 }
1083
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001084 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001085 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001086 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001087 // TODO: Anything to do if if succedded?
1088 // TODO: If it failed: Show error notification? Should we remove the shadow
1089 // account to avoid retries?
1090 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001091 }
1092
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001093 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001094 public void onError(int errorCode, String errorMessage) {
1095 super.onError(errorCode, errorMessage);
1096 // TODO: Show error notification to user
1097 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1098 }
1099
1100 }.bind();
1101 } finally {
1102 restoreCallingIdentity(id);
1103 }
1104 }
1105
Amith Yamasani04e0d262012-02-14 11:50:53 -08001106 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001107 Bundle extras, int callingUid) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001108 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001109 if (account == null) {
1110 return false;
1111 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001112 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001113 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1114 + " is locked. callingUid=" + callingUid);
1115 return false;
1116 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001117 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001118 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001119 db.beginTransaction();
1120 try {
1121 long numMatches = DatabaseUtils.longForQuery(db,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001122 "select count(*) from " + CE_TABLE_ACCOUNTS
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001123 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1124 new String[]{account.name, account.type});
1125 if (numMatches > 0) {
1126 Log.w(TAG, "insertAccountIntoDatabase: " + account
1127 + ", skipping since the account already exists");
1128 return false;
1129 }
1130 ContentValues values = new ContentValues();
1131 values.put(ACCOUNTS_NAME, account.name);
1132 values.put(ACCOUNTS_TYPE, account.type);
1133 values.put(ACCOUNTS_PASSWORD, password);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001134 long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001135 if (accountId < 0) {
1136 Log.w(TAG, "insertAccountIntoDatabase: " + account
1137 + ", skipping the DB insert failed");
1138 return false;
1139 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001140 // Insert into DE table
1141 values = new ContentValues();
1142 values.put(ACCOUNTS_ID, accountId);
1143 values.put(ACCOUNTS_NAME, account.name);
1144 values.put(ACCOUNTS_TYPE, account.type);
1145 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1146 System.currentTimeMillis());
1147 if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1148 Log.w(TAG, "insertAccountIntoDatabase: " + account
1149 + ", skipping the DB insert failed");
1150 return false;
1151 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001152 if (extras != null) {
1153 for (String key : extras.keySet()) {
1154 final String value = extras.getString(key);
1155 if (insertExtraLocked(db, accountId, key, value) < 0) {
1156 Log.w(TAG, "insertAccountIntoDatabase: " + account
1157 + ", skipping since insertExtra failed for key " + key);
1158 return false;
1159 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001160 }
1161 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001162 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001163
1164 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1165 accounts, callingUid);
1166
Amith Yamasani04e0d262012-02-14 11:50:53 -08001167 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001168 } finally {
1169 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001170 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001171 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001172 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001173 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1174 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001175 }
1176 return true;
1177 }
1178
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001179 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001180 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001181 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001182 }
1183 }
1184
Amith Yamasani5be347b2013-03-31 17:44:31 -07001185 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001186 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001187 * running, then clone the account too.
1188 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001189 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001190 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001191 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001192 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001193 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001194 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001195 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001196 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001197 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1198 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001199 }
1200 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001201 }
1202 }
1203
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001204 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -07001205 ContentValues values = new ContentValues();
1206 values.put(EXTRAS_KEY, key);
1207 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1208 values.put(EXTRAS_VALUE, value);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001209 return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
Fred Quintana60307342009-03-24 22:48:12 -07001210 }
1211
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001212 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001213 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001214 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001215 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001216 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1217 Log.v(TAG, "hasFeatures: " + account
1218 + ", response " + response
1219 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001220 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001221 + ", pid " + Binder.getCallingPid());
1222 }
Fred Quintana382601f2010-03-25 12:25:10 -07001223 if (response == null) throw new IllegalArgumentException("response is null");
1224 if (account == null) throw new IllegalArgumentException("account is null");
1225 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001226 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001227 checkReadAccountsPermitted(callingUid, account.type, userId,
1228 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001229
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001230 long identityToken = clearCallingIdentity();
1231 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001232 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001233 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001234 } finally {
1235 restoreCallingIdentity(identityToken);
1236 }
1237 }
1238
1239 private class TestFeaturesSession extends Session {
1240 private final String[] mFeatures;
1241 private final Account mAccount;
1242
Amith Yamasani04e0d262012-02-14 11:50:53 -08001243 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001244 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001245 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001246 true /* stripAuthTokenFromResult */, account.name,
1247 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001248 mFeatures = features;
1249 mAccount = account;
1250 }
1251
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001252 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001253 public void run() throws RemoteException {
1254 try {
1255 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1256 } catch (RemoteException e) {
1257 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1258 }
1259 }
1260
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001261 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001262 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001263 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001264 IAccountManagerResponse response = getResponseAndClose();
1265 if (response != null) {
1266 try {
1267 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001268 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001269 return;
1270 }
Fred Quintana56285a62010-12-02 14:20:51 -08001271 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1272 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1273 + response);
1274 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001275 final Bundle newResult = new Bundle();
1276 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1277 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1278 response.onResult(newResult);
1279 } catch (RemoteException e) {
1280 // if the caller is dead then there is no one to care about remote exceptions
1281 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1282 Log.v(TAG, "failure while notifying response", e);
1283 }
1284 }
1285 }
1286 }
1287
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001288 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001289 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001290 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001291 + ", " + mAccount
1292 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1293 }
1294 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001295
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001296 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001297 public void renameAccount(
1298 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001299 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001300 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1301 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001302 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001303 + ", pid " + Binder.getCallingPid());
1304 }
1305 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001306 int userId = UserHandle.getCallingUserId();
1307 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001308 String msg = String.format(
1309 "uid %s cannot rename accounts of type: %s",
1310 callingUid,
1311 accountToRename.type);
1312 throw new SecurityException(msg);
1313 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001314 long identityToken = clearCallingIdentity();
1315 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001316 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001317 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001318 Bundle result = new Bundle();
1319 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1320 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1321 try {
1322 response.onResult(result);
1323 } catch (RemoteException e) {
1324 Log.w(TAG, e.getMessage());
1325 }
1326 } finally {
1327 restoreCallingIdentity(identityToken);
1328 }
1329 }
1330
1331 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001332 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001333 Account resultAccount = null;
1334 /*
1335 * Cancel existing notifications. Let authenticators
1336 * re-post notifications as required. But we don't know if
1337 * the authenticators have bound their notifications to
1338 * now stale account name data.
1339 *
1340 * With a rename api, we might not need to do this anymore but it
1341 * shouldn't hurt.
1342 */
1343 cancelNotification(
1344 getSigninRequiredNotificationId(accounts, accountToRename),
1345 new UserHandle(accounts.userId));
1346 synchronized(accounts.credentialsPermissionNotificationIds) {
1347 for (Pair<Pair<Account, String>, Integer> pair:
1348 accounts.credentialsPermissionNotificationIds.keySet()) {
1349 if (accountToRename.equals(pair.first.first)) {
1350 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1351 cancelNotification(id, new UserHandle(accounts.userId));
1352 }
1353 }
1354 }
1355 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001356 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001357 db.beginTransaction();
1358 boolean isSuccessful = false;
1359 Account renamedAccount = new Account(newName, accountToRename.type);
1360 try {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001361 final long accountId = getAccountIdLocked(db, accountToRename);
1362 if (accountId >= 0) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001363 final ContentValues values = new ContentValues();
1364 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001365 final String[] argsAccountId = { String.valueOf(accountId) };
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001366 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1367 // Update NAME/PREVIOUS_NAME in DE accounts table
1368 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001369 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1370 db.setTransactionSuccessful();
1371 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001372 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1373 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001374 }
1375 } finally {
1376 db.endTransaction();
1377 if (isSuccessful) {
1378 /*
1379 * Database transaction was successful. Clean up cached
1380 * data associated with the account in the user profile.
1381 */
1382 insertAccountIntoCacheLocked(accounts, renamedAccount);
1383 /*
1384 * Extract the data and token caches before removing the
1385 * old account to preserve the user data associated with
1386 * the account.
1387 */
1388 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1389 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1390 removeAccountFromCacheLocked(accounts, accountToRename);
1391 /*
1392 * Update the cached data associated with the renamed
1393 * account.
1394 */
1395 accounts.userDataCache.put(renamedAccount, tmpData);
1396 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1397 accounts.previousNameCache.put(
1398 renamedAccount,
1399 new AtomicReference<String>(accountToRename.name));
1400 resultAccount = renamedAccount;
1401
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001402 int parentUserId = accounts.userId;
1403 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001404 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001405 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001406 * those users with which the account was shared.
1407 */
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001408 List<UserInfo> users = getUserManager().getUsers(true);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001409 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001410 if (user.isRestricted()
1411 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001412 renameSharedAccountAsUser(accountToRename, newName, user.id);
1413 }
1414 }
1415 }
1416 sendAccountsChangedBroadcast(accounts.userId);
1417 }
1418 }
1419 }
1420 return resultAccount;
1421 }
1422
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001423 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001424 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001425 return userInfo != null && userInfo.canHaveProfile();
1426 }
1427
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001428 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001429 public void removeAccount(IAccountManagerResponse response, Account account,
1430 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001431 removeAccountAsUser(
1432 response,
1433 account,
1434 expectActivityLaunch,
1435 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001436 }
1437
1438 @Override
1439 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001440 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001441 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001442 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1443 Log.v(TAG, "removeAccount: " + account
1444 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001445 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001446 + ", pid " + Binder.getCallingPid()
1447 + ", for user id " + userId);
1448 }
1449 if (response == null) throw new IllegalArgumentException("response is null");
1450 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001451 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001452 if (isCrossUser(callingUid, userId)) {
1453 throw new SecurityException(
1454 String.format(
1455 "User %s tying remove account for %s" ,
1456 UserHandle.getCallingUserId(),
1457 userId));
1458 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001459 /*
1460 * Only the system or authenticator should be allowed to remove accounts for that
1461 * authenticator. This will let users remove accounts (via Settings in the system) but not
1462 * arbitrary applications (like competing authenticators).
1463 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001464 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001465 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1466 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001467 String msg = String.format(
1468 "uid %s cannot remove accounts of type: %s",
1469 callingUid,
1470 account.type);
1471 throw new SecurityException(msg);
1472 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001473 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001474 try {
1475 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1476 "User cannot modify accounts");
1477 } catch (RemoteException re) {
1478 }
1479 return;
1480 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001481 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001482 try {
1483 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1484 "User cannot modify accounts of this type (policy).");
1485 } catch (RemoteException re) {
1486 }
1487 return;
1488 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001489 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001490 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001491 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001492 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001493 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001494 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001495 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001496 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001497 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001498 }
1499 }
1500 }
1501
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001502 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1503
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001504 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001505 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1506 } finally {
1507 restoreCallingIdentity(identityToken);
1508 }
1509 }
1510
1511 @Override
1512 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001513 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001514 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1515 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001516 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001517 + ", pid " + Binder.getCallingPid());
1518 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001519 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001520 if (account == null) {
1521 /*
1522 * Null accounts should result in returning false, as per
1523 * AccountManage.addAccountExplicitly(...) java doc.
1524 */
1525 Log.e(TAG, "account is null");
1526 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001527 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001528 String msg = String.format(
1529 "uid %s cannot explicitly add accounts of type: %s",
1530 callingUid,
1531 account.type);
1532 throw new SecurityException(msg);
1533 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001534 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001535 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001536 long identityToken = clearCallingIdentity();
1537 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001538 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001539 } finally {
1540 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001541 }
Fred Quintana60307342009-03-24 22:48:12 -07001542 }
1543
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001544 private class RemoveAccountSession extends Session {
1545 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001546 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001547 Account account, boolean expectActivityLaunch) {
1548 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001549 true /* stripAuthTokenFromResult */, account.name,
1550 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001551 mAccount = account;
1552 }
1553
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001554 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001555 protected String toDebugString(long now) {
1556 return super.toDebugString(now) + ", removeAccount"
1557 + ", account " + mAccount;
1558 }
1559
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001560 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001561 public void run() throws RemoteException {
1562 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1563 }
1564
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001565 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001566 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001567 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001568 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1569 && !result.containsKey(AccountManager.KEY_INTENT)) {
1570 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001571 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001572 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001573 }
1574 IAccountManagerResponse response = getResponseAndClose();
1575 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001576 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1577 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1578 + response);
1579 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001580 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001581 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001582 try {
1583 response.onResult(result2);
1584 } catch (RemoteException e) {
1585 // ignore
1586 }
1587 }
1588 }
1589 super.onResult(result);
1590 }
1591 }
1592
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001593 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001594 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001595 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001596 }
1597
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001598 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001599 int deleted;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001600 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001601 if (!userUnlocked) {
1602 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
1603 + " is still locked. CE data will be removed later");
1604 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001605 synchronized (accounts.cacheLock) {
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001606 final SQLiteDatabase db = userUnlocked
1607 ? accounts.openHelper.getWritableDatabaseUserIsUnlocked()
1608 : accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001609 final long accountId = getAccountIdLocked(db, account);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001610 db.beginTransaction();
1611 try {
1612 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1613 + "=?", new String[]{account.name, account.type});
1614 if (userUnlocked) {
1615 // Delete from CE table
1616 deleted = db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1617 + "=?", new String[]{account.name, account.type});
1618 }
1619 db.setTransactionSuccessful();
1620 } finally {
1621 db.endTransaction();
1622 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001623 removeAccountFromCacheLocked(accounts, account);
1624 sendAccountsChangedBroadcast(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001625 String action = userUnlocked ? DebugDbHelper.ACTION_ACCOUNT_REMOVE
1626 : DebugDbHelper.ACTION_ACCOUNT_REMOVE_DE;
1627 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001628 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001629 long id = Binder.clearCallingIdentity();
1630 try {
1631 int parentUserId = accounts.userId;
1632 if (canHaveProfile(parentUserId)) {
1633 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001634 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001635 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001636 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001637 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001638 }
1639 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001640 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001641 } finally {
1642 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001643 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001644 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001645 }
1646
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001647 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001648 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001649 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001650 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1651 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001652 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001653 + ", pid " + Binder.getCallingPid());
1654 }
Fred Quintana382601f2010-03-25 12:25:10 -07001655 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1656 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001657 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001658 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001659 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001660 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001661 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001662 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001663 db.beginTransaction();
1664 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001665 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001666 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001667 db.setTransactionSuccessful();
1668 } finally {
1669 db.endTransaction();
1670 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001671 }
Fred Quintana60307342009-03-24 22:48:12 -07001672 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001673 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001674 }
1675 }
1676
Carlos Valdivia91979be2015-05-22 14:11:35 -07001677 private void invalidateCustomTokenLocked(
1678 UserAccounts accounts,
1679 String accountType,
1680 String authToken) {
1681 if (authToken == null || accountType == null) {
1682 return;
1683 }
1684 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001685 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001686 }
1687
Amith Yamasani04e0d262012-02-14 11:50:53 -08001688 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1689 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001690 if (authToken == null || accountType == null) {
1691 return;
1692 }
Fred Quintana33269202009-04-20 16:05:10 -07001693 Cursor cursor = db.rawQuery(
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001694 "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1695 + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1696 + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1697 + " FROM " + CE_TABLE_ACCOUNTS
1698 + " JOIN " + CE_TABLE_AUTHTOKENS
1699 + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1700 + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
1701 + " WHERE " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_AUTHTOKEN
1702 + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
Fred Quintana33269202009-04-20 16:05:10 -07001703 new String[]{authToken, accountType});
1704 try {
1705 while (cursor.moveToNext()) {
1706 long authTokenId = cursor.getLong(0);
1707 String accountName = cursor.getString(1);
1708 String authTokenType = cursor.getString(2);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001709 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001710 writeAuthTokenIntoCacheLocked(
1711 accounts,
1712 db,
1713 new Account(accountName, accountType),
1714 authTokenType,
1715 null);
Fred Quintana60307342009-03-24 22:48:12 -07001716 }
Fred Quintana33269202009-04-20 16:05:10 -07001717 } finally {
1718 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001719 }
1720 }
1721
Carlos Valdivia91979be2015-05-22 14:11:35 -07001722 private void saveCachedToken(
1723 UserAccounts accounts,
1724 Account account,
1725 String callerPkg,
1726 byte[] callerSigDigest,
1727 String tokenType,
1728 String token,
1729 long expiryMillis) {
1730
1731 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1732 return;
1733 }
1734 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001735 UserHandle.of(accounts.userId));
Carlos Valdivia91979be2015-05-22 14:11:35 -07001736 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001737 accounts.accountTokenCaches.put(
1738 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001739 }
1740 }
1741
Amith Yamasani04e0d262012-02-14 11:50:53 -08001742 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1743 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001744 if (account == null || type == null) {
1745 return false;
1746 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001747 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001748 UserHandle.of(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001749 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001750 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001751 db.beginTransaction();
1752 try {
1753 long accountId = getAccountIdLocked(db, account);
1754 if (accountId < 0) {
1755 return false;
1756 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001757 db.delete(CE_TABLE_AUTHTOKENS,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001758 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1759 new String[]{type});
1760 ContentValues values = new ContentValues();
1761 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1762 values.put(AUTHTOKENS_TYPE, type);
1763 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001764 if (db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001765 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001766 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001767 return true;
1768 }
Fred Quintana33269202009-04-20 16:05:10 -07001769 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001770 } finally {
1771 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001772 }
Fred Quintana60307342009-03-24 22:48:12 -07001773 }
1774 }
1775
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001776 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001777 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001778 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001779 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1780 Log.v(TAG, "peekAuthToken: " + account
1781 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001782 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001783 + ", pid " + Binder.getCallingPid());
1784 }
Fred Quintana382601f2010-03-25 12:25:10 -07001785 if (account == null) throw new IllegalArgumentException("account is null");
1786 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001787 int userId = UserHandle.getCallingUserId();
1788 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001789 String msg = String.format(
1790 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1791 callingUid,
1792 account.type);
1793 throw new SecurityException(msg);
1794 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001795 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001796 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
1797 + callingUid);
1798 return null;
1799 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001800 long identityToken = clearCallingIdentity();
1801 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001802 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001803 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001804 } finally {
1805 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001806 }
Fred Quintana60307342009-03-24 22:48:12 -07001807 }
1808
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001809 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001810 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001811 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001812 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1813 Log.v(TAG, "setAuthToken: " + account
1814 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001815 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001816 + ", pid " + Binder.getCallingPid());
1817 }
Fred Quintana382601f2010-03-25 12:25:10 -07001818 if (account == null) throw new IllegalArgumentException("account is null");
1819 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001820 int userId = UserHandle.getCallingUserId();
1821 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001822 String msg = String.format(
1823 "uid %s cannot set auth tokens associated with accounts of type: %s",
1824 callingUid,
1825 account.type);
1826 throw new SecurityException(msg);
1827 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001828 long identityToken = clearCallingIdentity();
1829 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001830 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001831 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001832 } finally {
1833 restoreCallingIdentity(identityToken);
1834 }
Fred Quintana60307342009-03-24 22:48:12 -07001835 }
1836
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001837 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001838 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001839 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001840 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1841 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001842 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001843 + ", pid " + Binder.getCallingPid());
1844 }
Fred Quintana382601f2010-03-25 12:25:10 -07001845 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001846 int userId = UserHandle.getCallingUserId();
1847 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001848 String msg = String.format(
1849 "uid %s cannot set secrets for accounts of type: %s",
1850 callingUid,
1851 account.type);
1852 throw new SecurityException(msg);
1853 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001854 long identityToken = clearCallingIdentity();
1855 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001856 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001857 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001858 } finally {
1859 restoreCallingIdentity(identityToken);
1860 }
Fred Quintana60307342009-03-24 22:48:12 -07001861 }
1862
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001863 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1864 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001865 if (account == null) {
1866 return;
1867 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001868 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001869 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001870 db.beginTransaction();
1871 try {
1872 final ContentValues values = new ContentValues();
1873 values.put(ACCOUNTS_PASSWORD, password);
1874 final long accountId = getAccountIdLocked(db, account);
1875 if (accountId >= 0) {
1876 final String[] argsAccountId = {String.valueOf(accountId)};
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001877 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1878 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001879 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001880 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001881 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001882
1883 String action = (password == null || password.length() == 0) ?
1884 DebugDbHelper.ACTION_CLEAR_PASSWORD
1885 : DebugDbHelper.ACTION_SET_PASSWORD;
1886 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001887 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001888 } finally {
1889 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001890 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001891 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001892 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001893 }
1894
Amith Yamasani04e0d262012-02-14 11:50:53 -08001895 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001896 Log.i(TAG, "the accounts changed, sending broadcast of "
1897 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001898 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001899 }
1900
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001901 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001902 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001903 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001904 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1905 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001906 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001907 + ", pid " + Binder.getCallingPid());
1908 }
Fred Quintana382601f2010-03-25 12:25:10 -07001909 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001910 int userId = UserHandle.getCallingUserId();
1911 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001912 String msg = String.format(
1913 "uid %s cannot clear passwords for accounts of type: %s",
1914 callingUid,
1915 account.type);
1916 throw new SecurityException(msg);
1917 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001918 long identityToken = clearCallingIdentity();
1919 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001920 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001921 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001922 } finally {
1923 restoreCallingIdentity(identityToken);
1924 }
Fred Quintana60307342009-03-24 22:48:12 -07001925 }
1926
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001927 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001928 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001929 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001930 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1931 Log.v(TAG, "setUserData: " + account
1932 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001933 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001934 + ", pid " + Binder.getCallingPid());
1935 }
Fred Quintana382601f2010-03-25 12:25:10 -07001936 if (key == null) throw new IllegalArgumentException("key is null");
1937 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001938 int userId = UserHandle.getCallingUserId();
1939 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001940 String msg = String.format(
1941 "uid %s cannot set user data for accounts of type: %s",
1942 callingUid,
1943 account.type);
1944 throw new SecurityException(msg);
1945 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001946 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001947 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001948 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00001949 synchronized (accounts.cacheLock) {
1950 if (!accountExistsCacheLocked(accounts, account)) {
1951 return;
1952 }
1953 setUserdataInternalLocked(accounts, account, key, value);
1954 }
Fred Quintana60307342009-03-24 22:48:12 -07001955 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001956 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001957 }
1958 }
1959
Simranjit Kohli858511c2016-03-10 18:36:11 +00001960 private boolean accountExistsCacheLocked(UserAccounts accounts, Account account) {
1961 if (accounts.accountCache.containsKey(account.type)) {
1962 for (Account acc : accounts.accountCache.get(account.type)) {
1963 if (acc.name.equals(account.name)) {
1964 return true;
1965 }
1966 }
1967 }
1968 return false;
1969 }
1970
1971 private void setUserdataInternalLocked(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001972 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001973 if (account == null || key == null) {
1974 return;
1975 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00001976 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1977 db.beginTransaction();
1978 try {
1979 long accountId = getAccountIdLocked(db, account);
1980 if (accountId < 0) {
1981 return;
1982 }
1983 long extrasId = getExtrasIdLocked(db, accountId, key);
1984 if (extrasId < 0) {
1985 extrasId = insertExtraLocked(db, accountId, key, value);
1986 if (extrasId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001987 return;
1988 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00001989 } else {
1990 ContentValues values = new ContentValues();
1991 values.put(EXTRAS_VALUE, value);
1992 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1993 return;
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001994 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001995 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00001996 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
1997 db.setTransactionSuccessful();
1998 } finally {
1999 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002000 }
2001 }
2002
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002003 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002004 if (result == null) {
2005 Log.e(TAG, "the result is unexpectedly null", new Exception());
2006 }
2007 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2008 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2009 + response);
2010 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002011 try {
2012 response.onResult(result);
2013 } catch (RemoteException e) {
2014 // if the caller is dead then there is no one to care about remote
2015 // exceptions
2016 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2017 Log.v(TAG, "failure while notifying response", e);
2018 }
2019 }
2020 }
2021
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002022 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002023 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2024 final String authTokenType)
2025 throws RemoteException {
2026 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002027 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2028
Fred Quintanad9640ec2012-05-23 12:37:00 -07002029 final int callingUid = getCallingUid();
2030 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07002031 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002032 throw new SecurityException("can only call from system");
2033 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002034 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002035 long identityToken = clearCallingIdentity();
2036 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002037 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002038 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2039 false /* stripAuthTokenFromResult */, null /* accountName */,
2040 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002041 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002042 protected String toDebugString(long now) {
2043 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002044 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002045 + ", authTokenType " + authTokenType;
2046 }
2047
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002048 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002049 public void run() throws RemoteException {
2050 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2051 }
2052
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002053 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002054 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002055 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002056 if (result != null) {
2057 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2058 Bundle bundle = new Bundle();
2059 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2060 super.onResult(bundle);
2061 return;
2062 } else {
2063 super.onResult(result);
2064 }
2065 }
2066 }.bind();
2067 } finally {
2068 restoreCallingIdentity(identityToken);
2069 }
2070 }
2071
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002072 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002073 public void getAuthToken(
2074 IAccountManagerResponse response,
2075 final Account account,
2076 final String authTokenType,
2077 final boolean notifyOnAuthFailure,
2078 final boolean expectActivityLaunch,
2079 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002080 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002081 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2082 Log.v(TAG, "getAuthToken: " + account
2083 + ", response " + response
2084 + ", authTokenType " + authTokenType
2085 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2086 + ", expectActivityLaunch " + expectActivityLaunch
2087 + ", caller's uid " + Binder.getCallingUid()
2088 + ", pid " + Binder.getCallingPid());
2089 }
Fred Quintana382601f2010-03-25 12:25:10 -07002090 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002091 try {
2092 if (account == null) {
2093 Slog.w(TAG, "getAuthToken called with null account");
2094 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2095 return;
2096 }
2097 if (authTokenType == null) {
2098 Slog.w(TAG, "getAuthToken called with null authTokenType");
2099 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2100 return;
2101 }
2102 } catch (RemoteException e) {
2103 Slog.w(TAG, "Failed to report error back to the client." + e);
2104 return;
2105 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002106 int userId = UserHandle.getCallingUserId();
2107 long ident = Binder.clearCallingIdentity();
2108 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002109 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002110 try {
2111 accounts = getUserAccounts(userId);
2112 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2113 AuthenticatorDescription.newKey(account.type), accounts.userId);
2114 } finally {
2115 Binder.restoreCallingIdentity(ident);
2116 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002117
Costin Manolachea40c6302010-12-13 14:50:45 -08002118 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002119 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002120
2121 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002122 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002123 final boolean permissionGranted =
2124 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002125
Carlos Valdivia91979be2015-05-22 14:11:35 -07002126 // Get the calling package. We will use it for the purpose of caching.
2127 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002128 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002129 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002130 try {
2131 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2132 } finally {
2133 Binder.restoreCallingIdentity(ident);
2134 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002135 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2136 String msg = String.format(
2137 "Uid %s is attempting to illegally masquerade as package %s!",
2138 callerUid,
2139 callerPkg);
2140 throw new SecurityException(msg);
2141 }
2142
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002143 // let authenticator know the identity of the caller
2144 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2145 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002146
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002147 if (notifyOnAuthFailure) {
2148 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002149 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002150
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002151 long identityToken = clearCallingIdentity();
2152 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002153 // Distill the caller's package signatures into a single digest.
2154 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2155
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002156 // if the caller has permission, do the peek. otherwise go the more expensive
2157 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002158 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002159 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002160 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002161 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002162 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2163 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2164 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002165 onResult(response, result);
2166 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002167 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002168 }
2169
Carlos Valdivia91979be2015-05-22 14:11:35 -07002170 if (customTokens) {
2171 /*
2172 * Look up tokens in the new cache only if the loginOptions don't have parameters
2173 * outside of those expected to be injected by the AccountManager, e.g.
2174 * ANDORID_PACKAGE_NAME.
2175 */
2176 String token = readCachedTokenInternal(
2177 accounts,
2178 account,
2179 authTokenType,
2180 callerPkg,
2181 callerPkgSigDigest);
2182 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002183 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2184 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2185 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002186 Bundle result = new Bundle();
2187 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2188 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2189 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2190 onResult(response, result);
2191 return;
2192 }
2193 }
2194
Amith Yamasani04e0d262012-02-14 11:50:53 -08002195 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002196 false /* stripAuthTokenFromResult */, account.name,
2197 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002198 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002199 protected String toDebugString(long now) {
2200 if (loginOptions != null) loginOptions.keySet();
2201 return super.toDebugString(now) + ", getAuthToken"
2202 + ", " + account
2203 + ", authTokenType " + authTokenType
2204 + ", loginOptions " + loginOptions
2205 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2206 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002207
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002208 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002209 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002210 // If the caller doesn't have permission then create and return the
2211 // "grant permission" intent instead of the "getAuthToken" intent.
2212 if (!permissionGranted) {
2213 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2214 } else {
2215 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2216 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002217 }
2218
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002219 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002220 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002221 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002222 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002223 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002224 Intent intent = newGrantCredentialsPermissionIntent(
2225 account,
2226 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002227 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002228 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002229 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002230 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002231 onResult(bundle);
2232 return;
2233 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002234 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002235 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002236 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2237 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002238 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002239 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002240 "the type and name should not be empty");
2241 return;
2242 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002243 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002244 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002245 saveAuthTokenToDatabase(
2246 mAccounts,
2247 resultAccount,
2248 authTokenType,
2249 authToken);
2250 }
2251 long expiryMillis = result.getLong(
2252 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2253 if (customTokens
2254 && expiryMillis > System.currentTimeMillis()) {
2255 saveCachedToken(
2256 mAccounts,
2257 account,
2258 callerPkg,
2259 callerPkgSigDigest,
2260 authTokenType,
2261 authToken,
2262 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002263 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002264 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002265
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002266 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002267 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002268 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002269 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002270 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002271 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002272 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002273 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002274 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002275 }.bind();
2276 } finally {
2277 restoreCallingIdentity(identityToken);
2278 }
Fred Quintana60307342009-03-24 22:48:12 -07002279 }
2280
Carlos Valdivia91979be2015-05-22 14:11:35 -07002281 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2282 MessageDigest digester;
2283 try {
2284 digester = MessageDigest.getInstance("SHA-256");
2285 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2286 callerPkg, PackageManager.GET_SIGNATURES);
2287 for (Signature sig : pkgInfo.signatures) {
2288 digester.update(sig.toByteArray());
2289 }
2290 } catch (NoSuchAlgorithmException x) {
2291 Log.wtf(TAG, "SHA-256 should be available", x);
2292 digester = null;
2293 } catch (NameNotFoundException e) {
2294 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2295 digester = null;
2296 }
2297 return (digester == null) ? null : digester.digest();
2298 }
2299
Dianne Hackborn41203752012-08-31 14:05:51 -07002300 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2301 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002302 int uid = intent.getIntExtra(
2303 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2304 String authTokenType = intent.getStringExtra(
2305 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002306 final String titleAndSubtitle =
2307 mContext.getString(R.string.permission_request_notification_with_subtitle,
2308 account.name);
2309 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002310 String title = titleAndSubtitle;
2311 String subtitle = "";
2312 if (index > 0) {
2313 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002314 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002315 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002316 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002317 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002318 Notification n = new Notification.Builder(contextForUser)
2319 .setSmallIcon(android.R.drawable.stat_sys_warning)
2320 .setWhen(0)
2321 .setColor(contextForUser.getColor(
2322 com.android.internal.R.color.system_notification_accent_color))
2323 .setContentTitle(title)
2324 .setContentText(subtitle)
2325 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2326 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2327 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002328 installNotification(getCredentialPermissionNotificationId(
2329 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002330 }
2331
Costin Manolache5f383ad92010-12-02 16:44:46 -08002332 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002333 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002334
2335 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002336 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002337 // Since it was set in Eclair+ we can't change it without breaking apps using
2338 // the intent from a non-Activity context.
2339 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002340 intent.addCategory(
2341 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002342
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002343 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002344 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2345 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002346 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002347
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002348 return intent;
2349 }
2350
2351 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2352 int uid) {
2353 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002354 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002355 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002356 final Pair<Pair<Account, String>, Integer> key =
2357 new Pair<Pair<Account, String>, Integer>(
2358 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002359 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002360 if (id == null) {
2361 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002362 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002363 }
2364 }
2365 return id;
2366 }
2367
Amith Yamasani04e0d262012-02-14 11:50:53 -08002368 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002369 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002370 synchronized (accounts.signinRequiredNotificationIds) {
2371 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002372 if (id == null) {
2373 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002374 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002375 }
2376 }
2377 return id;
2378 }
2379
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002380 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002381 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002382 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002383 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002384 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002385 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2386 Log.v(TAG, "addAccount: accountType " + accountType
2387 + ", response " + response
2388 + ", authTokenType " + authTokenType
2389 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2390 + ", expectActivityLaunch " + expectActivityLaunch
2391 + ", caller's uid " + Binder.getCallingUid()
2392 + ", pid " + Binder.getCallingPid());
2393 }
Fred Quintana382601f2010-03-25 12:25:10 -07002394 if (response == null) throw new IllegalArgumentException("response is null");
2395 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002396
Amith Yamasani71e6c692013-03-24 17:39:28 -07002397 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002398 final int uid = Binder.getCallingUid();
2399 final int userId = UserHandle.getUserId(uid);
2400 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002401 try {
2402 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2403 "User is not allowed to add an account!");
2404 } catch (RemoteException re) {
2405 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002406 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002407 return;
2408 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002409 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002410 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002411 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2412 "User cannot modify accounts of this type (policy).");
2413 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002414 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002415 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2416 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002417 return;
2418 }
2419
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002420 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002421 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2422 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2423 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2424
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002425 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002426 long identityToken = clearCallingIdentity();
2427 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002428 UserAccounts accounts = getUserAccounts(usrId);
2429 logRecordWithUid(
2430 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002431 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002432 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002433 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002434 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002435 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002436 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002437 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002438 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002439
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002440 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002441 protected String toDebugString(long now) {
2442 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002443 + ", accountType " + accountType
2444 + ", requiredFeatures "
2445 + (requiredFeatures != null
2446 ? TextUtils.join(",", requiredFeatures)
2447 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002448 }
2449 }.bind();
2450 } finally {
2451 restoreCallingIdentity(identityToken);
2452 }
Fred Quintana60307342009-03-24 22:48:12 -07002453 }
2454
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002455 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002456 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2457 final String authTokenType, final String[] requiredFeatures,
2458 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002459 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002460 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002461 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2462 Log.v(TAG, "addAccount: accountType " + accountType
2463 + ", response " + response
2464 + ", authTokenType " + authTokenType
2465 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2466 + ", expectActivityLaunch " + expectActivityLaunch
2467 + ", caller's uid " + Binder.getCallingUid()
2468 + ", pid " + Binder.getCallingPid()
2469 + ", for user id " + userId);
2470 }
2471 if (response == null) throw new IllegalArgumentException("response is null");
2472 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002473 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002474 if (isCrossUser(callingUid, userId)) {
2475 throw new SecurityException(
2476 String.format(
2477 "User %s trying to add account for %s" ,
2478 UserHandle.getCallingUserId(),
2479 userId));
2480 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002481
2482 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002483 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002484 try {
2485 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2486 "User is not allowed to add an account!");
2487 } catch (RemoteException re) {
2488 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002489 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002490 return;
2491 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002492 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002493 try {
2494 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2495 "User cannot modify accounts of this type (policy).");
2496 } catch (RemoteException re) {
2497 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002498 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2499 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002500 return;
2501 }
2502
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002503 final int pid = Binder.getCallingPid();
2504 final int uid = Binder.getCallingUid();
2505 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2506 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2507 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2508
2509 long identityToken = clearCallingIdentity();
2510 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002511 UserAccounts accounts = getUserAccounts(userId);
2512 logRecordWithUid(
2513 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002514 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002515 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002516 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002517 @Override
2518 public void run() throws RemoteException {
2519 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2520 options);
2521 }
2522
2523 @Override
2524 protected String toDebugString(long now) {
2525 return super.toDebugString(now) + ", addAccount"
2526 + ", accountType " + accountType
2527 + ", requiredFeatures "
2528 + (requiredFeatures != null
2529 ? TextUtils.join(",", requiredFeatures)
2530 : null);
2531 }
2532 }.bind();
2533 } finally {
2534 restoreCallingIdentity(identityToken);
2535 }
2536 }
2537
Sandra Kwan78812282015-11-04 11:19:47 -08002538 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002539 public void startAddAccountSession(
2540 final IAccountManagerResponse response,
2541 final String accountType,
2542 final String authTokenType,
2543 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002544 final boolean expectActivityLaunch,
2545 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002546 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002547 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2548 Log.v(TAG,
2549 "startAddAccountSession: accountType " + accountType
2550 + ", response " + response
2551 + ", authTokenType " + authTokenType
2552 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2553 + ", expectActivityLaunch " + expectActivityLaunch
2554 + ", caller's uid " + Binder.getCallingUid()
2555 + ", pid " + Binder.getCallingPid());
2556 }
2557 if (response == null) {
2558 throw new IllegalArgumentException("response is null");
2559 }
2560 if (accountType == null) {
2561 throw new IllegalArgumentException("accountType is null");
2562 }
2563
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002564 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002565 // Only allow system to start session
2566 if (!isSystemUid(uid)) {
2567 String msg = String.format(
2568 "uid %s cannot stat add account session.",
2569 uid);
2570 throw new SecurityException(msg);
2571 }
2572
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002573 final int userId = UserHandle.getUserId(uid);
2574 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002575 try {
2576 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2577 "User is not allowed to add an account!");
2578 } catch (RemoteException re) {
2579 }
2580 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2581 return;
2582 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002583 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002584 try {
2585 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2586 "User cannot modify accounts of this type (policy).");
2587 } catch (RemoteException re) {
2588 }
2589 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2590 userId);
2591 return;
2592 }
Sandra Kwan78812282015-11-04 11:19:47 -08002593 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08002594 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2595 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2596 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2597
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002598 // Check to see if the Password should be included to the caller.
2599 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2600 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07002601 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002602
Sandra Kwan78812282015-11-04 11:19:47 -08002603 int usrId = UserHandle.getCallingUserId();
2604 long identityToken = clearCallingIdentity();
2605 try {
2606 UserAccounts accounts = getUserAccounts(usrId);
2607 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2608 TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002609 new StartAccountSession(
2610 accounts,
2611 response,
2612 accountType,
2613 expectActivityLaunch,
2614 null /* accountName */,
2615 false /* authDetailsRequired */,
2616 true /* updateLastAuthenticationTime */,
2617 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002618 @Override
2619 public void run() throws RemoteException {
2620 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2621 requiredFeatures, options);
2622 }
2623
2624 @Override
2625 protected String toDebugString(long now) {
2626 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2627 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2628 + accountType + ", requiredFeatures "
2629 + (requiredFeatures != null ? requiredFeaturesStr : null);
2630 }
2631 }.bind();
2632 } finally {
2633 restoreCallingIdentity(identityToken);
2634 }
2635 }
2636
2637 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2638 private abstract class StartAccountSession extends Session {
2639
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002640 private final boolean mIsPasswordForwardingAllowed;
2641
2642 public StartAccountSession(
2643 UserAccounts accounts,
2644 IAccountManagerResponse response,
2645 String accountType,
2646 boolean expectActivityLaunch,
2647 String accountName,
2648 boolean authDetailsRequired,
2649 boolean updateLastAuthenticationTime,
2650 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002651 super(accounts, response, accountType, expectActivityLaunch,
2652 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2653 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002654 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08002655 }
2656
2657 @Override
2658 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002659 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002660 mNumResults++;
2661 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08002662 if (result != null
2663 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08002664 checkKeyIntent(
2665 Binder.getCallingUid(),
2666 intent);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002667 // Omit passwords if the caller isn't permitted to see them.
2668 if (!mIsPasswordForwardingAllowed) {
2669 result.remove(AccountManager.KEY_PASSWORD);
2670 }
Sandra Kwan78812282015-11-04 11:19:47 -08002671 }
Sandra Kwan78812282015-11-04 11:19:47 -08002672 IAccountManagerResponse response;
2673 if (mExpectActivityLaunch && result != null
2674 && result.containsKey(AccountManager.KEY_INTENT)) {
2675 response = mResponse;
2676 } else {
2677 response = getResponseAndClose();
2678 }
2679 if (response == null) {
2680 return;
2681 }
2682 if (result == null) {
2683 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2684 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2685 + response);
2686 }
2687 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2688 "null bundle returned");
2689 return;
2690 }
2691
2692 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2693 // All AccountManager error codes are greater
2694 // than 0
2695 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2696 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2697 return;
2698 }
2699
2700 // Strip auth token from result.
2701 result.remove(AccountManager.KEY_AUTHTOKEN);
2702
2703 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2704 Log.v(TAG,
2705 getClass().getSimpleName() + " calling onResult() on response " + response);
2706 }
2707
2708 // Get the session bundle created by authenticator. The
2709 // bundle contains data necessary for finishing the session
2710 // later. The session bundle will be encrypted here and
2711 // decrypted later when trying to finish the session.
2712 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2713 if (sessionBundle != null) {
2714 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2715 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08002716 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002717 Log.w(TAG, "Account type in session bundle doesn't match request.");
2718 }
2719 // Add accountType info to session bundle. This will
2720 // override any value set by authenticator.
2721 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2722
2723 // Encrypt session bundle before returning to caller.
2724 try {
2725 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2726 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2727 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2728 } catch (GeneralSecurityException e) {
2729 if (Log.isLoggable(TAG, Log.DEBUG)) {
2730 Log.v(TAG, "Failed to encrypt session bundle!", e);
2731 }
2732 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2733 "failed to encrypt session bundle");
2734 return;
2735 }
2736 }
2737
2738 sendResponse(response, result);
2739 }
2740 }
2741
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002742 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08002743 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002744 @NonNull Bundle sessionBundle,
2745 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002746 Bundle appInfo,
2747 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002748 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08002749 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002750 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2751 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002752 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002753 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08002754 + ", caller's uid " + callingUid
2755 + ", caller's user id " + UserHandle.getCallingUserId()
2756 + ", pid " + Binder.getCallingPid()
2757 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002758 }
2759 if (response == null) {
2760 throw new IllegalArgumentException("response is null");
2761 }
2762
2763 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2764 // Account type is added to it before encryption.
2765 if (sessionBundle == null || sessionBundle.size() == 0) {
2766 throw new IllegalArgumentException("sessionBundle is empty");
2767 }
2768
Sandra Kwan0b84b452016-01-20 15:25:42 -08002769 // Only allow the system process to finish session for other users
2770 if (isCrossUser(callingUid, userId)) {
2771 throw new SecurityException(
2772 String.format(
2773 "User %s trying to finish session for %s without cross user permission",
2774 UserHandle.getCallingUserId(),
2775 userId));
2776 }
2777
Sandra Kwana578d112015-12-16 16:01:43 -08002778 // Only allow system to finish session
Sandra Kwan0b84b452016-01-20 15:25:42 -08002779 if (!isSystemUid(callingUid)) {
Sandra Kwana578d112015-12-16 16:01:43 -08002780 String msg = String.format(
Sandra Kwan0b84b452016-01-20 15:25:42 -08002781 "uid %s cannot finish session because it's not system uid.",
2782 callingUid);
Sandra Kwana578d112015-12-16 16:01:43 -08002783 throw new SecurityException(msg);
2784 }
2785
Sandra Kwan0b84b452016-01-20 15:25:42 -08002786 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002787 sendErrorResponse(response,
2788 AccountManager.ERROR_CODE_USER_RESTRICTED,
2789 "User is not allowed to add an account!");
2790 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2791 return;
2792 }
2793
2794 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002795 final Bundle decryptedBundle;
2796 final String accountType;
2797 // First decrypt session bundle to get account type for checking permission.
2798 try {
2799 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2800 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2801 if (decryptedBundle == null) {
2802 sendErrorResponse(
2803 response,
2804 AccountManager.ERROR_CODE_BAD_REQUEST,
2805 "failed to decrypt session bundle");
2806 return;
2807 }
2808 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2809 // Account type cannot be null. This should not happen if session bundle was created
2810 // properly by #StartAccountSession.
2811 if (TextUtils.isEmpty(accountType)) {
2812 sendErrorResponse(
2813 response,
2814 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2815 "accountType is empty");
2816 return;
2817 }
2818
2819 // If by any chances, decryptedBundle contains colliding keys with
2820 // system info
2821 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2822 // update credentials flow, we should replace with the new values of the current call.
2823 if (appInfo != null) {
2824 decryptedBundle.putAll(appInfo);
2825 }
2826
2827 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08002828 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002829 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2830 } catch (GeneralSecurityException e) {
2831 if (Log.isLoggable(TAG, Log.DEBUG)) {
2832 Log.v(TAG, "Failed to decrypt session bundle!", e);
2833 }
2834 sendErrorResponse(
2835 response,
2836 AccountManager.ERROR_CODE_BAD_REQUEST,
2837 "failed to decrypt session bundle");
2838 return;
2839 }
2840
Sandra Kwan0b84b452016-01-20 15:25:42 -08002841 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002842 sendErrorResponse(
2843 response,
2844 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2845 "User cannot modify accounts of this type (policy).");
2846 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2847 userId);
2848 return;
2849 }
2850
2851 long identityToken = clearCallingIdentity();
2852 try {
2853 UserAccounts accounts = getUserAccounts(userId);
2854 logRecordWithUid(
2855 accounts,
2856 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2857 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002858 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002859 new Session(
2860 accounts,
2861 response,
2862 accountType,
2863 expectActivityLaunch,
2864 true /* stripAuthTokenFromResult */,
2865 null /* accountName */,
2866 false /* authDetailsRequired */,
2867 true /* updateLastAuthenticationTime */) {
2868 @Override
2869 public void run() throws RemoteException {
2870 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2871 }
2872
2873 @Override
2874 protected String toDebugString(long now) {
2875 return super.toDebugString(now)
2876 + ", finishSession"
2877 + ", accountType " + accountType;
2878 }
2879 }.bind();
2880 } finally {
2881 restoreCallingIdentity(identityToken);
2882 }
2883 }
2884
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002885 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002886 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2887 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2888 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2889 long identityToken = clearCallingIdentity();
2890 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002891 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002892 } finally {
2893 restoreCallingIdentity(identityToken);
2894 }
2895 }
2896
2897 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002898 public void confirmCredentialsAsUser(
2899 IAccountManagerResponse response,
2900 final Account account,
2901 final Bundle options,
2902 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002903 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002904 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002905 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002906 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2907 Log.v(TAG, "confirmCredentials: " + account
2908 + ", response " + response
2909 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002910 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002911 + ", pid " + Binder.getCallingPid());
2912 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002913 // Only allow the system process to read accounts of other users
2914 if (isCrossUser(callingUid, userId)) {
2915 throw new SecurityException(
2916 String.format(
2917 "User %s trying to confirm account credentials for %s" ,
2918 UserHandle.getCallingUserId(),
2919 userId));
2920 }
Fred Quintana382601f2010-03-25 12:25:10 -07002921 if (response == null) throw new IllegalArgumentException("response is null");
2922 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002923 long identityToken = clearCallingIdentity();
2924 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002925 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002926 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002927 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002928 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002929 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002930 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002931 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002932 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002933 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002934 protected String toDebugString(long now) {
2935 return super.toDebugString(now) + ", confirmCredentials"
2936 + ", " + account;
2937 }
2938 }.bind();
2939 } finally {
2940 restoreCallingIdentity(identityToken);
2941 }
Fred Quintana60307342009-03-24 22:48:12 -07002942 }
2943
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002944 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002945 public void updateCredentials(IAccountManagerResponse response, final Account account,
2946 final String authTokenType, final boolean expectActivityLaunch,
2947 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002948 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002949 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2950 Log.v(TAG, "updateCredentials: " + account
2951 + ", response " + response
2952 + ", authTokenType " + authTokenType
2953 + ", expectActivityLaunch " + expectActivityLaunch
2954 + ", caller's uid " + Binder.getCallingUid()
2955 + ", pid " + Binder.getCallingPid());
2956 }
Fred Quintana382601f2010-03-25 12:25:10 -07002957 if (response == null) throw new IllegalArgumentException("response is null");
2958 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002959 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002960 long identityToken = clearCallingIdentity();
2961 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002962 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002963 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002964 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002965 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002966 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002967 public void run() throws RemoteException {
2968 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2969 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002970 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002971 protected String toDebugString(long now) {
2972 if (loginOptions != null) loginOptions.keySet();
2973 return super.toDebugString(now) + ", updateCredentials"
2974 + ", " + account
2975 + ", authTokenType " + authTokenType
2976 + ", loginOptions " + loginOptions;
2977 }
2978 }.bind();
2979 } finally {
2980 restoreCallingIdentity(identityToken);
2981 }
Fred Quintana60307342009-03-24 22:48:12 -07002982 }
2983
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002984 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002985 public void startUpdateCredentialsSession(
2986 IAccountManagerResponse response,
2987 final Account account,
2988 final String authTokenType,
2989 final boolean expectActivityLaunch,
2990 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002991 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08002992 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2993 Log.v(TAG,
2994 "startUpdateCredentialsSession: " + account + ", response " + response
2995 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
2996 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
2997 + ", pid " + Binder.getCallingPid());
2998 }
2999 if (response == null) {
3000 throw new IllegalArgumentException("response is null");
3001 }
3002 if (account == null) {
3003 throw new IllegalArgumentException("account is null");
3004 }
Sandra Kwana578d112015-12-16 16:01:43 -08003005
3006 final int uid = Binder.getCallingUid();
3007 // Only allow system to start session
3008 if (!isSystemUid(uid)) {
3009 String msg = String.format(
3010 "uid %s cannot start update credentials session.",
3011 uid);
3012 throw new SecurityException(msg);
3013 }
3014
Sandra Kwane68c37e2015-11-12 17:11:49 -08003015 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003016
3017 // Check to see if the Password should be included to the caller.
3018 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3019 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003020 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003021
Sandra Kwane68c37e2015-11-12 17:11:49 -08003022 long identityToken = clearCallingIdentity();
3023 try {
3024 UserAccounts accounts = getUserAccounts(userId);
3025 new StartAccountSession(
3026 accounts,
3027 response,
3028 account.type,
3029 expectActivityLaunch,
3030 account.name,
3031 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003032 true /* updateLastCredentialTime */,
3033 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003034 @Override
3035 public void run() throws RemoteException {
3036 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3037 loginOptions);
3038 }
3039
3040 @Override
3041 protected String toDebugString(long now) {
3042 if (loginOptions != null)
3043 loginOptions.keySet();
3044 return super.toDebugString(now)
3045 + ", startUpdateCredentialsSession"
3046 + ", " + account
3047 + ", authTokenType " + authTokenType
3048 + ", loginOptions " + loginOptions;
3049 }
3050 }.bind();
3051 } finally {
3052 restoreCallingIdentity(identityToken);
3053 }
3054 }
3055
3056 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003057 public void isCredentialsUpdateSuggested(
3058 IAccountManagerResponse response,
3059 final Account account,
3060 final String statusToken) {
3061 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3062 Log.v(TAG,
3063 "isCredentialsUpdateSuggested: " + account + ", response " + response
3064 + ", caller's uid " + Binder.getCallingUid()
3065 + ", pid " + Binder.getCallingPid());
3066 }
3067 if (response == null) {
3068 throw new IllegalArgumentException("response is null");
3069 }
3070 if (account == null) {
3071 throw new IllegalArgumentException("account is null");
3072 }
3073 if (TextUtils.isEmpty(statusToken)) {
3074 throw new IllegalArgumentException("status token is empty");
3075 }
3076
3077 int uid = Binder.getCallingUid();
3078 // Only allow system to start session
3079 if (!isSystemUid(uid)) {
3080 String msg = String.format(
3081 "uid %s cannot stat add account session.",
3082 uid);
3083 throw new SecurityException(msg);
3084 }
3085
3086 int usrId = UserHandle.getCallingUserId();
3087 long identityToken = clearCallingIdentity();
3088 try {
3089 UserAccounts accounts = getUserAccounts(usrId);
3090 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3091 false /* stripAuthTokenFromResult */, account.name,
3092 false /* authDetailsRequired */) {
3093 @Override
3094 protected String toDebugString(long now) {
3095 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3096 + ", " + account;
3097 }
3098
3099 @Override
3100 public void run() throws RemoteException {
3101 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3102 }
3103
3104 @Override
3105 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003106 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003107 IAccountManagerResponse response = getResponseAndClose();
3108 if (response == null) {
3109 return;
3110 }
3111
3112 if (result == null) {
3113 sendErrorResponse(
3114 response,
3115 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3116 "null bundle");
3117 return;
3118 }
3119
3120 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3121 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3122 + response);
3123 }
3124 // Check to see if an error occurred. We know if an error occurred because all
3125 // error codes are greater than 0.
3126 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3127 sendErrorResponse(response,
3128 result.getInt(AccountManager.KEY_ERROR_CODE),
3129 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3130 return;
3131 }
3132 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3133 sendErrorResponse(
3134 response,
3135 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3136 "no result in response");
3137 return;
3138 }
3139 final Bundle newResult = new Bundle();
3140 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3141 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3142 sendResponse(response, newResult);
3143 }
3144 }.bind();
3145 } finally {
3146 restoreCallingIdentity(identityToken);
3147 }
3148 }
3149
3150 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003151 public void editProperties(IAccountManagerResponse response, final String accountType,
3152 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003153 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003154 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3155 Log.v(TAG, "editProperties: accountType " + accountType
3156 + ", response " + response
3157 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003158 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003159 + ", pid " + Binder.getCallingPid());
3160 }
Fred Quintana382601f2010-03-25 12:25:10 -07003161 if (response == null) throw new IllegalArgumentException("response is null");
3162 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003163 int userId = UserHandle.getCallingUserId();
3164 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003165 String msg = String.format(
3166 "uid %s cannot edit authenticator properites for account type: %s",
3167 callingUid,
3168 accountType);
3169 throw new SecurityException(msg);
3170 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003171 long identityToken = clearCallingIdentity();
3172 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003173 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003174 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003175 true /* stripAuthTokenFromResult */, null /* accountName */,
3176 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003177 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003178 public void run() throws RemoteException {
3179 mAuthenticator.editProperties(this, mAccountType);
3180 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003181 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003182 protected String toDebugString(long now) {
3183 return super.toDebugString(now) + ", editProperties"
3184 + ", accountType " + accountType;
3185 }
3186 }.bind();
3187 } finally {
3188 restoreCallingIdentity(identityToken);
3189 }
Fred Quintana60307342009-03-24 22:48:12 -07003190 }
3191
Amith Yamasani12747872015-12-07 14:19:49 -08003192 @Override
3193 public boolean someUserHasAccount(@NonNull final Account account) {
3194 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3195 throw new SecurityException("Only system can check for accounts across users");
3196 }
3197 final long token = Binder.clearCallingIdentity();
3198 try {
3199 AccountAndUser[] allAccounts = getAllAccounts();
3200 for (int i = allAccounts.length - 1; i >= 0; i--) {
3201 if (allAccounts[i].account.equals(account)) {
3202 return true;
3203 }
3204 }
3205 return false;
3206 } finally {
3207 Binder.restoreCallingIdentity(token);
3208 }
3209 }
3210
Fred Quintana33269202009-04-20 16:05:10 -07003211 private class GetAccountsByTypeAndFeatureSession extends Session {
3212 private final String[] mFeatures;
3213 private volatile Account[] mAccountsOfType = null;
3214 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3215 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003216 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003217
Amith Yamasani04e0d262012-02-14 11:50:53 -08003218 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003219 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003220 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003221 true /* stripAuthTokenFromResult */, null /* accountName */,
3222 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003223 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003224 mFeatures = features;
3225 }
3226
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003227 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003228 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003229 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003230 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3231 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003232 }
Fred Quintana33269202009-04-20 16:05:10 -07003233 // check whether each account matches the requested features
3234 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
3235 mCurrentAccount = 0;
3236
3237 checkAccount();
3238 }
3239
3240 public void checkAccount() {
3241 if (mCurrentAccount >= mAccountsOfType.length) {
3242 sendResult();
3243 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003244 }
Fred Quintana33269202009-04-20 16:05:10 -07003245
Fred Quintana29e94b82010-03-10 12:11:51 -08003246 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3247 if (accountAuthenticator == null) {
3248 // It is possible that the authenticator has died, which is indicated by
3249 // mAuthenticator being set to null. If this happens then just abort.
3250 // There is no need to send back a result or error in this case since
3251 // that already happened when mAuthenticator was cleared.
3252 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3253 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3254 + " connected to the authenticator, " + toDebugString());
3255 }
3256 return;
3257 }
Fred Quintana33269202009-04-20 16:05:10 -07003258 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003259 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003260 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003261 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003262 }
3263 }
3264
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003265 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003266 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003267 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003268 mNumResults++;
3269 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003270 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003271 return;
3272 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003273 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003274 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3275 }
3276 mCurrentAccount++;
3277 checkAccount();
3278 }
3279
3280 public void sendResult() {
3281 IAccountManagerResponse response = getResponseAndClose();
3282 if (response != null) {
3283 try {
3284 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3285 for (int i = 0; i < accounts.length; i++) {
3286 accounts[i] = mAccountsWithFeatures.get(i);
3287 }
Fred Quintana56285a62010-12-02 14:20:51 -08003288 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3289 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3290 + response);
3291 }
Fred Quintana33269202009-04-20 16:05:10 -07003292 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003293 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003294 response.onResult(result);
3295 } catch (RemoteException e) {
3296 // if the caller is dead then there is no one to care about remote exceptions
3297 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3298 Log.v(TAG, "failure while notifying response", e);
3299 }
3300 }
3301 }
3302 }
3303
3304
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003305 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003306 protected String toDebugString(long now) {
3307 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3308 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3309 }
3310 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003311
Amith Yamasani04e0d262012-02-14 11:50:53 -08003312 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003313 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003314 * @hide
3315 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003316 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003317 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003318 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003319 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3320 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003321 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003322 return new Account[0];
3323 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003324 long identityToken = clearCallingIdentity();
3325 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003326 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003327 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003328 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003329 callingUid,
3330 null, // packageName
3331 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003332 } finally {
3333 restoreCallingIdentity(identityToken);
3334 }
3335 }
3336
Amith Yamasanif29f2362012-04-05 18:29:52 -07003337 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003338 * Returns accounts for all running users.
3339 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003340 * @hide
3341 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003342 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003343 public AccountAndUser[] getRunningAccounts() {
3344 final int[] runningUserIds;
3345 try {
3346 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3347 } catch (RemoteException e) {
3348 // Running in system_server; should never happen
3349 throw new RuntimeException(e);
3350 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003351 return getAccounts(runningUserIds);
3352 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003353
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003354 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003355 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003356 public AccountAndUser[] getAllAccounts() {
3357 final List<UserInfo> users = getUserManager().getUsers();
3358 final int[] userIds = new int[users.size()];
3359 for (int i = 0; i < userIds.length; i++) {
3360 userIds[i] = users.get(i).id;
3361 }
3362 return getAccounts(userIds);
3363 }
3364
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003365 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003366 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003367 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003368 for (int userId : userIds) {
3369 UserAccounts userAccounts = getUserAccounts(userId);
3370 if (userAccounts == null) continue;
3371 synchronized (userAccounts.cacheLock) {
3372 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3373 Binder.getCallingUid(), null);
3374 for (int a = 0; a < accounts.length; a++) {
3375 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003376 }
3377 }
3378 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003379
3380 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3381 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003382 }
3383
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003384 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003385 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003386 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3387 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003388 }
3389
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003390 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003391 private Account[] getAccountsAsUser(
3392 String type,
3393 int userId,
3394 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003395 int packageUid,
3396 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003397 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003398 // Only allow the system process to read accounts of other users
3399 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003400 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003401 && mContext.checkCallingOrSelfPermission(
3402 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3403 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003404 throw new SecurityException("User " + UserHandle.getCallingUserId()
3405 + " trying to get account for " + userId);
3406 }
3407
Fred Quintana56285a62010-12-02 14:20:51 -08003408 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3409 Log.v(TAG, "getAccounts: accountType " + type
3410 + ", caller's uid " + Binder.getCallingUid()
3411 + ", pid " + Binder.getCallingPid());
3412 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003413 // If the original calling app was using the framework account chooser activity, we'll
3414 // be passed in the original caller's uid here, which is what should be used for filtering.
3415 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3416 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003417 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003418 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003419
Svetoslavf3f02ac2015-09-08 14:36:35 -07003420 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3421 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003422 if (visibleAccountTypes.isEmpty()
3423 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003424 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003425 } else if (visibleAccountTypes.contains(type)) {
3426 // Prune the list down to just the requested type.
3427 visibleAccountTypes = new ArrayList<>();
3428 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003429 } // else aggregate all the visible accounts (it won't matter if the
3430 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003431
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003432 long identityToken = clearCallingIdentity();
3433 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003434 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003435 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003436 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003437 callingUid,
3438 callingPackage,
3439 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003440 } finally {
3441 restoreCallingIdentity(identityToken);
3442 }
3443 }
3444
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003445 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003446 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003447 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003448 int callingUid,
3449 String callingPackage,
3450 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003451 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003452 ArrayList<Account> visibleAccounts = new ArrayList<>();
3453 for (String visibleType : visibleAccountTypes) {
3454 Account[] accountsForType = getAccountsFromCacheLocked(
3455 userAccounts, visibleType, callingUid, callingPackage);
3456 if (accountsForType != null) {
3457 visibleAccounts.addAll(Arrays.asList(accountsForType));
3458 }
3459 }
3460 Account[] result = new Account[visibleAccounts.size()];
3461 for (int i = 0; i < visibleAccounts.size(); i++) {
3462 result[i] = visibleAccounts.get(i);
3463 }
3464 return result;
3465 }
3466 }
3467
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003468 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003469 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
3470 checkManageUsersPermission("addSharedAccountsFromParentUser");
3471 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3472 for (Account account : accounts) {
3473 addSharedAccountAsUser(account, userId);
3474 }
3475 }
3476
3477 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003478 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003479 UserAccounts accounts = getUserAccounts(userId);
3480 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003481 ContentValues values = new ContentValues();
3482 values.put(ACCOUNTS_NAME, account.name);
3483 values.put(ACCOUNTS_TYPE, account.type);
3484 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3485 new String[] {account.name, account.type});
3486 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3487 if (accountId < 0) {
3488 Log.w(TAG, "insertAccountIntoDatabase: " + account
3489 + ", skipping the DB insert failed");
3490 return false;
3491 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003492 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003493 return true;
3494 }
3495
3496 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003497 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3498 userId = handleIncomingUser(userId);
3499 UserAccounts accounts = getUserAccounts(userId);
3500 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003501 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003502 final ContentValues values = new ContentValues();
3503 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003504 int r = db.update(
3505 TABLE_SHARED_ACCOUNTS,
3506 values,
3507 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3508 new String[] { account.name, account.type });
3509 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003510 int callingUid = getCallingUid();
3511 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3512 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003513 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003514 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003515 }
3516 return r > 0;
3517 }
3518
3519 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003520 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003521 return removeSharedAccountAsUser(account, userId, getCallingUid());
3522 }
3523
3524 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003525 userId = handleIncomingUser(userId);
3526 UserAccounts accounts = getUserAccounts(userId);
3527 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003528 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003529 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3530 new String[] {account.name, account.type});
3531 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003532 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3533 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003534 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003535 }
3536 return r > 0;
3537 }
3538
3539 @Override
3540 public Account[] getSharedAccountsAsUser(int userId) {
3541 userId = handleIncomingUser(userId);
3542 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003543 ArrayList<Account> accountList = new ArrayList<>();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003544 Cursor cursor = null;
3545 try {
3546 cursor = accounts.openHelper.getReadableDatabase()
3547 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3548 null, null, null, null, null);
3549 if (cursor != null && cursor.moveToFirst()) {
3550 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3551 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3552 do {
3553 accountList.add(new Account(cursor.getString(nameIndex),
3554 cursor.getString(typeIndex)));
3555 } while (cursor.moveToNext());
3556 }
3557 } finally {
3558 if (cursor != null) {
3559 cursor.close();
3560 }
3561 }
3562 Account[] accountArray = new Account[accountList.size()];
3563 accountList.toArray(accountArray);
3564 return accountArray;
3565 }
3566
3567 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003568 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003569 public Account[] getAccounts(String type, String opPackageName) {
3570 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003571 }
3572
Amith Yamasani27db4682013-03-30 17:07:47 -07003573 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003574 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003575 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003576 int callingUid = Binder.getCallingUid();
3577 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3578 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3579 + callingUid + " with uid=" + uid);
3580 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003581 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3582 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003583 }
3584
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003585 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003586 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003587 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3588 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003589 int packageUid = -1;
3590 try {
3591 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07003592 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3593 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003594 } catch (RemoteException re) {
3595 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3596 return new Account[0];
3597 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003598 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3599 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003600 }
3601
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003602 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003603 public void getAccountsByFeatures(
3604 IAccountManagerResponse response,
3605 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003606 String[] features,
3607 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003608 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003609 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3610 Log.v(TAG, "getAccounts: accountType " + type
3611 + ", response " + response
3612 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003613 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003614 + ", pid " + Binder.getCallingPid());
3615 }
Fred Quintana382601f2010-03-25 12:25:10 -07003616 if (response == null) throw new IllegalArgumentException("response is null");
3617 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003618 int userId = UserHandle.getCallingUserId();
3619
Svetoslavf3f02ac2015-09-08 14:36:35 -07003620 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3621 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003622 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003623 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003624 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003625 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3626 try {
3627 response.onResult(result);
3628 } catch (RemoteException e) {
3629 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3630 }
3631 return;
3632 }
Fred Quintana33269202009-04-20 16:05:10 -07003633 long identityToken = clearCallingIdentity();
3634 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003635 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003636 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003637 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003638 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003639 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003640 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08003641 Bundle result = new Bundle();
3642 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3643 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003644 return;
3645 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003646 new GetAccountsByTypeAndFeatureSession(
3647 userAccounts,
3648 response,
3649 type,
3650 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003651 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07003652 } finally {
3653 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07003654 }
3655 }
3656
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003657 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3658 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3659 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3660 try {
3661 if (cursor.moveToNext()) {
3662 return cursor.getLong(0);
3663 }
3664 return -1;
3665 } finally {
3666 cursor.close();
3667 }
3668 }
3669
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003670 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07003671 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003672 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07003673 try {
3674 if (cursor.moveToNext()) {
3675 return cursor.getLong(0);
3676 }
3677 return -1;
3678 } finally {
3679 cursor.close();
3680 }
3681 }
3682
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003683 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003684 Cursor cursor = db.query(CE_TABLE_EXTRAS, new String[]{EXTRAS_ID},
Fred Quintana60307342009-03-24 22:48:12 -07003685 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3686 new String[]{key}, null, null, null);
3687 try {
3688 if (cursor.moveToNext()) {
3689 return cursor.getLong(0);
3690 }
3691 return -1;
3692 } finally {
3693 cursor.close();
3694 }
3695 }
3696
Fred Quintanaa698f422009-04-08 19:14:54 -07003697 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07003698 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07003699 IAccountManagerResponse mResponse;
3700 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003701 final boolean mExpectActivityLaunch;
3702 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003703 final String mAccountName;
3704 // Indicates if we need to add auth details(like last credential time)
3705 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003706 // If set, we need to update the last authenticated time. This is
3707 // currently
3708 // used on
3709 // successful confirming credentials.
3710 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07003711
Fred Quintana33269202009-04-20 16:05:10 -07003712 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07003713 private int mNumRequestContinued = 0;
3714 private int mNumErrors = 0;
3715
Fred Quintana60307342009-03-24 22:48:12 -07003716 IAccountAuthenticator mAuthenticator = null;
3717
Fred Quintana8570f742010-02-18 10:32:54 -08003718 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003719 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003720
Amith Yamasani04e0d262012-02-14 11:50:53 -08003721 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003722 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3723 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003724 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3725 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3726 }
3727
3728 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3729 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3730 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07003731 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003732 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07003733 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08003734 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003735 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07003736 mResponse = response;
3737 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003738 mExpectActivityLaunch = expectActivityLaunch;
3739 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003740 mAccountName = accountName;
3741 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003742 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003743
Fred Quintanaa698f422009-04-08 19:14:54 -07003744 synchronized (mSessions) {
3745 mSessions.put(toString(), this);
3746 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003747 if (response != null) {
3748 try {
3749 response.asBinder().linkToDeath(this, 0 /* flags */);
3750 } catch (RemoteException e) {
3751 mResponse = null;
3752 binderDied();
3753 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003754 }
Fred Quintana60307342009-03-24 22:48:12 -07003755 }
3756
Fred Quintanaa698f422009-04-08 19:14:54 -07003757 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07003758 if (mResponse == null) {
3759 // this session has already been closed
3760 return null;
3761 }
Fred Quintana60307342009-03-24 22:48:12 -07003762 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07003763 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07003764 return response;
3765 }
3766
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003767 /**
3768 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
3769 * security policy.
3770 *
3771 * In particular we want to make sure that the Authenticator doesn't try to trick users
3772 * into launching aribtrary intents on the device via by tricking to click authenticator
3773 * supplied entries in the system Settings app.
3774 */
3775 protected void checkKeyIntent(
3776 int authUid,
3777 Intent intent) throws SecurityException {
3778 long bid = Binder.clearCallingIdentity();
3779 try {
3780 PackageManager pm = mContext.getPackageManager();
3781 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3782 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
3783 int targetUid = targetActivityInfo.applicationInfo.uid;
3784 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid)) {
3785 String pkgName = targetActivityInfo.packageName;
3786 String activityName = targetActivityInfo.name;
3787 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
3788 + "does not share a signature with the supplying authenticator (%s).";
3789 throw new SecurityException(
3790 String.format(tmpl, activityName, pkgName, mAccountType));
3791 }
3792 } finally {
3793 Binder.restoreCallingIdentity(bid);
3794 }
3795 }
3796
Fred Quintanaa698f422009-04-08 19:14:54 -07003797 private void close() {
3798 synchronized (mSessions) {
3799 if (mSessions.remove(toString()) == null) {
3800 // the session was already closed, so bail out now
3801 return;
3802 }
3803 }
3804 if (mResponse != null) {
3805 // stop listening for response deaths
3806 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3807
3808 // clear this so that we don't accidentally send any further results
3809 mResponse = null;
3810 }
3811 cancelTimeout();
3812 unbind();
3813 }
3814
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003815 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003816 public void binderDied() {
3817 mResponse = null;
3818 close();
3819 }
3820
3821 protected String toDebugString() {
3822 return toDebugString(SystemClock.elapsedRealtime());
3823 }
3824
3825 protected String toDebugString(long now) {
3826 return "Session: expectLaunch " + mExpectActivityLaunch
3827 + ", connected " + (mAuthenticator != null)
3828 + ", stats (" + mNumResults + "/" + mNumRequestContinued
3829 + "/" + mNumErrors + ")"
3830 + ", lifetime " + ((now - mCreationTime) / 1000.0);
3831 }
3832
Fred Quintana60307342009-03-24 22:48:12 -07003833 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003834 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3835 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3836 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003837 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003838 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003839 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003840 }
3841 }
3842
3843 private void unbind() {
3844 if (mAuthenticator != null) {
3845 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003846 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003847 }
3848 }
3849
Fred Quintana60307342009-03-24 22:48:12 -07003850 public void cancelTimeout() {
3851 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3852 }
3853
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003854 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003855 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003856 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003857 try {
3858 run();
3859 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003860 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003861 "remote exception");
3862 }
Fred Quintana60307342009-03-24 22:48:12 -07003863 }
3864
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003865 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003866 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003867 mAuthenticator = null;
3868 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003869 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003870 try {
3871 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3872 "disconnected");
3873 } catch (RemoteException e) {
3874 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3875 Log.v(TAG, "Session.onServiceDisconnected: "
3876 + "caught RemoteException while responding", e);
3877 }
3878 }
Fred Quintana60307342009-03-24 22:48:12 -07003879 }
3880 }
3881
Fred Quintanab839afc2009-10-14 15:57:28 -07003882 public abstract void run() throws RemoteException;
3883
Fred Quintana60307342009-03-24 22:48:12 -07003884 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003885 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003886 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003887 try {
3888 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3889 "timeout");
3890 } catch (RemoteException e) {
3891 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3892 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3893 e);
3894 }
3895 }
Fred Quintana60307342009-03-24 22:48:12 -07003896 }
3897 }
3898
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003899 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003900 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003901 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07003902 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003903 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003904 if (result != null) {
3905 boolean isSuccessfulConfirmCreds = result.getBoolean(
3906 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003907 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003908 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3909 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003910 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003911 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3912 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003913 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003914 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003915 if (needUpdate || mAuthDetailsRequired) {
3916 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3917 if (needUpdate && accountPresent) {
3918 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3919 }
3920 if (mAuthDetailsRequired) {
3921 long lastAuthenticatedTime = -1;
3922 if (accountPresent) {
3923 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3924 mAccounts.openHelper.getReadableDatabase(),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003925 "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3926 + " FROM " +
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003927 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3928 + ACCOUNTS_TYPE + "=?",
3929 new String[] {
3930 mAccountName, mAccountType
3931 });
3932 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003933 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003934 lastAuthenticatedTime);
3935 }
3936 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003937 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003938 if (result != null
3939 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003940 checkKeyIntent(
3941 Binder.getCallingUid(),
3942 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003943 }
3944 if (result != null
3945 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003946 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3947 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003948 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3949 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003950 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3951 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003952 }
Fred Quintana60307342009-03-24 22:48:12 -07003953 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003954 IAccountManagerResponse response;
3955 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003956 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003957 response = mResponse;
3958 } else {
3959 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003960 }
Fred Quintana60307342009-03-24 22:48:12 -07003961 if (response != null) {
3962 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07003963 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08003964 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3965 Log.v(TAG, getClass().getSimpleName()
3966 + " calling onError() on response " + response);
3967 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003968 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07003969 "null bundle returned");
3970 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08003971 if (mStripAuthTokenFromResult) {
3972 result.remove(AccountManager.KEY_AUTHTOKEN);
3973 }
Fred Quintana56285a62010-12-02 14:20:51 -08003974 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3975 Log.v(TAG, getClass().getSimpleName()
3976 + " calling onResult() on response " + response);
3977 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003978 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3979 (intent == null)) {
3980 // All AccountManager error codes are greater than 0
3981 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3982 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3983 } else {
3984 response.onResult(result);
3985 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003986 }
Fred Quintana60307342009-03-24 22:48:12 -07003987 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003988 // if the caller is dead then there is no one to care about remote exceptions
3989 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3990 Log.v(TAG, "failure while notifying response", e);
3991 }
Fred Quintana60307342009-03-24 22:48:12 -07003992 }
3993 }
3994 }
Fred Quintana60307342009-03-24 22:48:12 -07003995
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003996 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003997 public void onRequestContinued() {
3998 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003999 }
4000
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004001 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004002 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004003 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004004 IAccountManagerResponse response = getResponseAndClose();
4005 if (response != null) {
4006 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004007 Log.v(TAG, getClass().getSimpleName()
4008 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004009 }
4010 try {
4011 response.onError(errorCode, errorMessage);
4012 } catch (RemoteException e) {
4013 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4014 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4015 }
4016 }
4017 } else {
4018 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4019 Log.v(TAG, "Session.onError: already closed");
4020 }
Fred Quintana60307342009-03-24 22:48:12 -07004021 }
4022 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004023
4024 /**
4025 * find the component name for the authenticator and initiate a bind
4026 * if no authenticator or the bind fails then return false, otherwise return true
4027 */
4028 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004029 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4030 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4031 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004032 if (authenticatorInfo == null) {
4033 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4034 Log.v(TAG, "there is no authenticator for " + authenticatorType
4035 + ", bailing out");
4036 }
4037 return false;
4038 }
4039
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004040 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004041 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004042 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4043 + " which isn't encryption aware");
4044 return false;
4045 }
4046
Fred Quintanab839afc2009-10-14 15:57:28 -07004047 Intent intent = new Intent();
4048 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4049 intent.setComponent(authenticatorInfo.componentName);
4050 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4051 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4052 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004053 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004054 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004055 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4056 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4057 }
4058 return false;
4059 }
4060
Fred Quintanab839afc2009-10-14 15:57:28 -07004061 return true;
4062 }
Fred Quintana60307342009-03-24 22:48:12 -07004063 }
4064
4065 private class MessageHandler extends Handler {
4066 MessageHandler(Looper looper) {
4067 super(looper);
4068 }
Costin Manolache3348f142009-09-29 18:58:36 -07004069
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004070 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004071 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004072 switch (msg.what) {
4073 case MESSAGE_TIMED_OUT:
4074 Session session = (Session)msg.obj;
4075 session.onTimedOut();
4076 break;
4077
Amith Yamasani5be347b2013-03-31 17:44:31 -07004078 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004079 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004080 break;
4081
Fred Quintana60307342009-03-24 22:48:12 -07004082 default:
4083 throw new IllegalStateException("unhandled message: " + msg.what);
4084 }
4085 }
4086 }
4087
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004088 @VisibleForTesting
4089 String getPreNDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07004090 File systemDir = Environment.getDataSystemDirectory();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004091 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
4092 PRE_N_DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004093 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07004094 // Migrate old file, if it exists, to the new location.
4095 // Make sure the new file doesn't already exist. A dummy file could have been
4096 // accidentally created in the old location, causing the new one to become corrupted
4097 // as well.
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004098 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07004099 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07004100 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07004101 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07004102 if (!userDir.exists()) {
4103 if (!userDir.mkdirs()) {
4104 throw new IllegalStateException("User dir cannot be created: " + userDir);
4105 }
4106 }
4107 if (!oldFile.renameTo(databaseFile)) {
4108 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
4109 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004110 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004111 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004112 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08004113 }
4114
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004115 @VisibleForTesting
4116 String getDeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004117 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
4118 DE_DATABASE_NAME);
4119 return databaseFile.getPath();
4120 }
4121
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004122 @VisibleForTesting
4123 String getCeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004124 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4125 CE_DATABASE_NAME);
4126 return databaseFile.getPath();
4127 }
4128
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004129 private static class DebugDbHelper{
4130 private DebugDbHelper() {
4131 }
4132
4133 private static String TABLE_DEBUG = "debug_table";
4134
4135 // Columns for the table
4136 private static String ACTION_TYPE = "action_type";
4137 private static String TIMESTAMP = "time";
4138 private static String CALLER_UID = "caller_uid";
4139 private static String TABLE_NAME = "table_name";
4140 private static String KEY = "primary_key";
4141
4142 // These actions correspond to the occurrence of real actions. Since
4143 // these are called by the authenticators, the uid associated will be
4144 // of the authenticator.
4145 private static String ACTION_SET_PASSWORD = "action_set_password";
4146 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4147 private static String ACTION_ACCOUNT_ADD = "action_account_add";
4148 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004149 private static String ACTION_ACCOUNT_REMOVE_DE = "action_account_remove_de";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004150 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4151 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4152
4153 // These actions don't necessarily correspond to any action on
4154 // accountDb taking place. As an example, there might be a request for
4155 // addingAccount, which might not lead to addition of account on grounds
4156 // of bad authentication. We will still be logging it to keep track of
4157 // who called.
4158 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4159 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004160 private static String ACTION_SYNC_DE_CE_ACCOUNTS = "action_sync_de_ce_accounts";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004161
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004162 //This action doesn't add account to accountdb. Account is only
4163 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08004164 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004165 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4166 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08004167
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004168 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4169
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004170 private static void createDebugTable(SQLiteDatabase db) {
4171 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4172 + ACCOUNTS_ID + " INTEGER,"
4173 + ACTION_TYPE + " TEXT NOT NULL, "
4174 + TIMESTAMP + " DATETIME,"
4175 + CALLER_UID + " INTEGER NOT NULL,"
4176 + TABLE_NAME + " TEXT NOT NULL,"
4177 + KEY + " INTEGER PRIMARY KEY)");
4178 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4179 }
4180 }
4181
4182 private void logRecord(UserAccounts accounts, String action, String tableName) {
4183 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4184 logRecord(db, action, tableName, -1, accounts);
4185 }
4186
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004187 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4188 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4189 logRecord(db, action, tableName, -1, accounts, uid);
4190 }
4191
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004192 /*
4193 * This function receives an opened writable database.
4194 */
4195 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4196 UserAccounts userAccount) {
4197 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4198 }
4199
4200 /*
4201 * This function receives an opened writable database.
4202 */
4203 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4204 UserAccounts userAccount, int callingUid) {
4205 SQLiteStatement logStatement = userAccount.statementForLogging;
4206 logStatement.bindLong(1, accountId);
4207 logStatement.bindString(2, action);
4208 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4209 logStatement.bindLong(4, callingUid);
4210 logStatement.bindString(5, tableName);
4211 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
4212 logStatement.execute();
4213 logStatement.clearBindings();
4214 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4215 % MAX_DEBUG_DB_SIZE;
4216 }
4217
4218 /*
4219 * This should only be called once to compile the sql statement for logging
4220 * and to find the insertion point.
4221 */
4222 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4223 UserAccounts userAccount) {
4224 // Initialize the count if not done earlier.
4225 int size = (int) getDebugTableRowCount(db);
4226 if (size >= MAX_DEBUG_DB_SIZE) {
4227 // Table is full, and we need to find the point where to insert.
4228 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4229 } else {
4230 userAccount.debugDbInsertionPoint = size;
4231 }
4232 compileSqlStatementForLogging(db, userAccount);
4233 }
4234
4235 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4236 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4237 + " VALUES (?,?,?,?,?,?)";
4238 userAccount.statementForLogging = db.compileStatement(sql);
4239 }
4240
4241 private long getDebugTableRowCount(SQLiteDatabase db) {
4242 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4243 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4244 }
4245
4246 /*
4247 * Finds the row key where the next insertion should take place. This should
4248 * be invoked only if the table has reached its full capacity.
4249 */
4250 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4251 // This query finds the smallest timestamp value (and if 2 records have
4252 // same timestamp, the choose the lower id).
4253 String queryCountDebugDbRows = new StringBuilder()
4254 .append("SELECT ").append(DebugDbHelper.KEY)
4255 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4256 .append(" ORDER BY ")
4257 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4258 .append(" LIMIT 1")
4259 .toString();
4260 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4261 }
4262
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004263 static class PreNDatabaseHelper extends SQLiteOpenHelper {
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004264 private final Context mContext;
4265 private final int mUserId;
4266
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004267 public PreNDatabaseHelper(Context context, int userId, String preNDatabaseName) {
4268 super(context, preNDatabaseName, null, PRE_N_DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004269 mContext = context;
4270 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004271 }
4272
4273 @Override
4274 public void onCreate(SQLiteDatabase db) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004275 // We use PreNDatabaseHelper only if pre-N db exists
4276 throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004277 }
4278
Amith Yamasani67df64b2012-12-14 12:09:36 -08004279 private void createSharedAccountsTable(SQLiteDatabase db) {
4280 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4281 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4282 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4283 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4284 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4285 }
4286
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004287 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4288 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4289 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4290 }
4291
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004292 private void addOldAccountNameColumn(SQLiteDatabase db) {
4293 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4294 }
4295
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004296 private void addDebugTable(SQLiteDatabase db) {
4297 DebugDbHelper.createDebugTable(db);
4298 }
4299
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004300 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004301 db.execSQL(""
4302 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4303 + " BEGIN"
4304 + " DELETE FROM " + TABLE_AUTHTOKENS
4305 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4306 + " DELETE FROM " + TABLE_EXTRAS
4307 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004308 + " DELETE FROM " + TABLE_GRANTS
4309 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004310 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004311 }
4312
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004313 private void createGrantsTable(SQLiteDatabase db) {
4314 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4315 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4316 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4317 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4318 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4319 + "," + GRANTS_GRANTEE_UID + "))");
4320 }
4321
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004322 private void populateMetaTableWithAuthTypeAndUID(
4323 SQLiteDatabase db,
4324 Map<String, Integer> authTypeAndUIDMap) {
4325 Iterator<Entry<String, Integer>> iterator = authTypeAndUIDMap.entrySet().iterator();
4326 while (iterator.hasNext()) {
4327 Entry<String, Integer> entry = iterator.next();
4328 ContentValues values = new ContentValues();
4329 values.put(META_KEY,
4330 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
4331 values.put(META_VALUE, entry.getValue());
4332 db.insert(TABLE_META, null, values);
4333 }
4334 }
4335
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004336 /**
4337 * Pre-N database may need an upgrade before splitting
4338 */
Fred Quintana60307342009-03-24 22:48:12 -07004339 @Override
4340 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004341 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004342
Fred Quintanaa698f422009-04-08 19:14:54 -07004343 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004344 // no longer need to do anything since the work is done
4345 // when upgrading from version 2
4346 oldVersion++;
4347 }
4348
4349 if (oldVersion == 2) {
4350 createGrantsTable(db);
4351 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4352 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004353 oldVersion++;
4354 }
Costin Manolache3348f142009-09-29 18:58:36 -07004355
4356 if (oldVersion == 3) {
4357 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4358 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4359 oldVersion++;
4360 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004361
4362 if (oldVersion == 4) {
4363 createSharedAccountsTable(db);
4364 oldVersion++;
4365 }
4366
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004367 if (oldVersion == 5) {
4368 addOldAccountNameColumn(db);
4369 oldVersion++;
4370 }
4371
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004372 if (oldVersion == 6) {
4373 addLastSuccessfullAuthenticatedTimeColumn(db);
4374 oldVersion++;
4375 }
4376
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004377 if (oldVersion == 7) {
4378 addDebugTable(db);
4379 oldVersion++;
4380 }
4381
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004382 if (oldVersion == 8) {
4383 populateMetaTableWithAuthTypeAndUID(
4384 db,
4385 AccountManagerService.getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
4386 oldVersion++;
4387 }
4388
Amith Yamasani67df64b2012-12-14 12:09:36 -08004389 if (oldVersion != newVersion) {
4390 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4391 }
Fred Quintana60307342009-03-24 22:48:12 -07004392 }
4393
4394 @Override
4395 public void onOpen(SQLiteDatabase db) {
4396 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4397 }
4398 }
4399
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004400 static class DeDatabaseHelper extends SQLiteOpenHelper {
4401
4402 private final int mUserId;
4403 private volatile boolean mCeAttached;
4404
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004405 private DeDatabaseHelper(Context context, int userId, String deDatabaseName) {
4406 super(context, deDatabaseName, null, DE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004407 mUserId = userId;
4408 }
4409
4410 /**
4411 * This call needs to be made while the mCacheLock is held. The way to
4412 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4413 * @param db The database.
4414 */
4415 @Override
4416 public void onCreate(SQLiteDatabase db) {
4417 Log.i(TAG, "Creating DE database for user " + mUserId);
4418 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4419 + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4420 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4421 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4422 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4423 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4424 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4425
4426 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4427 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4428 + META_VALUE + " TEXT)");
4429
4430 createGrantsTable(db);
4431 createSharedAccountsTable(db);
4432 createAccountsDeletionTrigger(db);
4433 DebugDbHelper.createDebugTable(db);
4434 }
4435
4436 private void createSharedAccountsTable(SQLiteDatabase db) {
4437 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4438 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4439 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4440 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4441 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4442 }
4443
4444 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4445 db.execSQL(""
4446 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4447 + " BEGIN"
4448 + " DELETE FROM " + TABLE_GRANTS
4449 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4450 + " END");
4451 }
4452
4453 private void createGrantsTable(SQLiteDatabase db) {
4454 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4455 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4456 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4457 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4458 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4459 + "," + GRANTS_GRANTEE_UID + "))");
4460 }
4461
4462 @Override
4463 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4464 Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4465
4466 if (oldVersion != newVersion) {
4467 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4468 }
4469 }
4470
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004471 public void attachCeDatabase(File ceDbFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004472 SQLiteDatabase db = getWritableDatabase();
4473 db.execSQL("ATTACH DATABASE '" + ceDbFile.getPath()+ "' AS ceDb");
4474 mCeAttached = true;
4475 }
4476
4477 public boolean isCeDatabaseAttached() {
4478 return mCeAttached;
4479 }
4480
4481
4482 public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
4483 if(!mCeAttached) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004484 Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user " + mUserId
4485 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004486 }
4487 return super.getReadableDatabase();
4488 }
4489
4490 public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
4491 if(!mCeAttached) {
4492 Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004493 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004494 }
4495 return super.getWritableDatabase();
4496 }
4497
4498 @Override
4499 public void onOpen(SQLiteDatabase db) {
4500 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
4501 }
4502
4503 private void migratePreNDbToDe(File preNDbFile) {
4504 Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
4505 SQLiteDatabase db = getWritableDatabase();
4506 db.execSQL("ATTACH DATABASE '" + preNDbFile.getPath() + "' AS preNDb");
4507 db.beginTransaction();
4508 // Copy accounts fields
4509 db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
4510 + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4511 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4512 + ") "
4513 + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4514 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4515 + " FROM preNDb." + TABLE_ACCOUNTS);
4516 // Copy SHARED_ACCOUNTS
4517 db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
4518 + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
4519 "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4520 + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
4521 // Copy DEBUG_TABLE
4522 db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
4523 + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4524 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4525 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
4526 "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4527 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4528 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
4529 + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
4530 // Copy GRANTS
4531 db.execSQL("INSERT INTO " + TABLE_GRANTS
4532 + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4533 + GRANTS_GRANTEE_UID + ") " +
4534 "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4535 + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
4536 // Copy META
4537 db.execSQL("INSERT INTO " + TABLE_META
4538 + "(" + META_KEY + "," + META_VALUE + ") "
4539 + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
4540 db.setTransactionSuccessful();
4541 db.endTransaction();
4542
4543 db.execSQL("DETACH DATABASE preNDb");
4544 }
4545
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004546 static DeDatabaseHelper create(
4547 Context context,
4548 int userId,
4549 File preNDatabaseFile,
4550 File deDatabaseFile) {
4551 boolean newDbExists = deDatabaseFile.exists();
4552 DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId,
4553 deDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004554 // If the db just created, and there is a legacy db, migrate it
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004555 if (!newDbExists && preNDatabaseFile.exists()) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004556 // Migrate legacy db to the latest version - PRE_N_DATABASE_VERSION
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004557 PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId,
4558 preNDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004559 // Open the database to force upgrade if required
4560 preNDatabaseHelper.getWritableDatabase();
4561 preNDatabaseHelper.close();
4562 // Move data without SPII to DE
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004563 deDatabaseHelper.migratePreNDbToDe(preNDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004564 }
4565 return deDatabaseHelper;
4566 }
4567 }
4568
4569 static class CeDatabaseHelper extends SQLiteOpenHelper {
4570
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004571 public CeDatabaseHelper(Context context, String ceDatabaseName) {
4572 super(context, ceDatabaseName, null, CE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004573 }
4574
4575 /**
4576 * This call needs to be made while the mCacheLock is held.
4577 * @param db The database.
4578 */
4579 @Override
4580 public void onCreate(SQLiteDatabase db) {
4581 Log.i(TAG, "Creating CE database " + getDatabaseName());
4582 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4583 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4584 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4585 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4586 + ACCOUNTS_PASSWORD + " TEXT, "
4587 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4588
4589 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
4590 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4591 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4592 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
4593 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
4594 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
4595
4596 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
4597 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4598 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
4599 + EXTRAS_KEY + " TEXT NOT NULL, "
4600 + EXTRAS_VALUE + " TEXT, "
4601 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
4602
4603 createAccountsDeletionTrigger(db);
4604 }
4605
4606 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4607 db.execSQL(""
4608 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4609 + " BEGIN"
4610 + " DELETE FROM " + TABLE_AUTHTOKENS
4611 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4612 + " DELETE FROM " + TABLE_EXTRAS
4613 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4614 + " END");
4615 }
4616
4617 @Override
4618 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4619 Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
4620
4621 if (oldVersion == 9) {
4622 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4623 Log.v(TAG, "onUpgrade upgrading to v10");
4624 }
4625 db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
4626 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
4627 // Recreate the trigger, since the old one references the table to be removed
4628 db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
4629 createAccountsDeletionTrigger(db);
4630 db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
4631 db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
4632 oldVersion ++;
4633 }
4634
4635 if (oldVersion != newVersion) {
4636 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4637 }
4638 }
4639
4640 @Override
4641 public void onOpen(SQLiteDatabase db) {
4642 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
4643 }
4644
4645 static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
4646 String type) {
4647 Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
4648 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
4649 new String[]{name, type}, null, null, null);
4650 try {
4651 if (cursor.moveToNext()) {
4652 return cursor.getString(0);
4653 }
4654 return null;
4655 } finally {
4656 cursor.close();
4657 }
4658 }
4659
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004660 static List<Account> findCeAccountsNotInDe(SQLiteDatabase db) {
4661 // Select accounts from CE that do not exist in DE
4662 Cursor cursor = db.rawQuery(
4663 "SELECT " + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4664 + " FROM " + CE_TABLE_ACCOUNTS
4665 + " WHERE NOT EXISTS "
4666 + " (SELECT " + ACCOUNTS_ID + " FROM " + TABLE_ACCOUNTS
4667 + " WHERE " + ACCOUNTS_ID + "=" + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
4668 + " )", null);
4669 try {
4670 List<Account> accounts = new ArrayList<>(cursor.getCount());
4671 while (cursor.moveToNext()) {
4672 String accountName = cursor.getString(0);
4673 String accountType = cursor.getString(1);
4674 accounts.add(new Account(accountName, accountType));
4675 }
4676 return accounts;
4677 } finally {
4678 cursor.close();
4679 }
4680 }
4681
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004682 /**
4683 * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
4684 * it also performs migration to the new CE database.
4685 * @param context
4686 * @param userId id of the user where the database is located
4687 */
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004688 static CeDatabaseHelper create(
4689 Context context,
4690 int userId,
4691 File preNDatabaseFile,
4692 File ceDatabaseFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004693 boolean newDbExists = ceDatabaseFile.exists();
4694 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4695 Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004696 + preNDatabaseFile.exists() + " newDbExists=" + newDbExists);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004697 }
4698 boolean removeOldDb = false;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004699 if (!newDbExists && preNDatabaseFile.exists()) {
4700 removeOldDb = migratePreNDbToCe(preNDatabaseFile, ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004701 }
4702 // Try to open and upgrade if necessary
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004703 CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, ceDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004704 ceHelper.getWritableDatabase();
4705 ceHelper.close();
4706 if (removeOldDb) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004707 Slog.i(TAG, "Migration complete - removing pre-N db " + preNDatabaseFile);
4708 if (!SQLiteDatabase.deleteDatabase(preNDatabaseFile)) {
4709 Slog.e(TAG, "Cannot remove pre-N db " + preNDatabaseFile);
4710 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004711 }
4712 return ceHelper;
4713 }
4714
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004715 private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004716 Slog.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004717 try {
4718 FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
4719 } catch (IOException e) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004720 Slog.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004721 // Try to remove potentially damaged file if I/O error occurred
4722 deleteDbFileWarnIfFailed(ceDbFile);
4723 return false;
4724 }
4725 return true;
4726 }
4727 }
4728
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004729 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004730 return asBinder();
4731 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004732
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004733 /**
4734 * Searches array of arguments for the specified string
4735 * @param args array of argument strings
4736 * @param value value to search for
4737 * @return true if the value is contained in the array
4738 */
4739 private static boolean scanArgs(String[] args, String value) {
4740 if (args != null) {
4741 for (String arg : args) {
4742 if (value.equals(arg)) {
4743 return true;
4744 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004745 }
4746 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004747 return false;
4748 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004749
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004750 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004751 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07004752 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4753 != PackageManager.PERMISSION_GRANTED) {
4754 fout.println("Permission Denial: can't dump AccountsManager from from pid="
4755 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4756 + " without permission " + android.Manifest.permission.DUMP);
4757 return;
4758 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004759 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004760 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004761
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004762 final List<UserInfo> users = getUserManager().getUsers();
4763 for (UserInfo user : users) {
4764 ipw.println("User " + user + ":");
4765 ipw.increaseIndent();
4766 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4767 ipw.println();
4768 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08004769 }
4770 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004771
Amith Yamasani04e0d262012-02-14 11:50:53 -08004772 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4773 String[] args, boolean isCheckinRequest) {
4774 synchronized (userAccounts.cacheLock) {
4775 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004776
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004777 if (isCheckinRequest) {
4778 // This is a checkin request. *Only* upload the account types and the count of each.
4779 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4780 null, null, ACCOUNTS_TYPE, null, null);
4781 try {
4782 while (cursor.moveToNext()) {
4783 // print type,count
4784 fout.println(cursor.getString(0) + "," + cursor.getString(1));
4785 }
4786 } finally {
4787 if (cursor != null) {
4788 cursor.close();
4789 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004790 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004791 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004792 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07004793 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004794 fout.println("Accounts: " + accounts.length);
4795 for (Account account : accounts) {
4796 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004797 }
Fred Quintana307da1a2010-01-21 14:24:20 -08004798
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004799 // Add debug information.
4800 fout.println();
4801 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4802 null, null, null, null, DebugDbHelper.TIMESTAMP);
4803 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4804 fout.println("Accounts History");
4805 try {
4806 while (cursor.moveToNext()) {
4807 // print type,count
4808 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4809 cursor.getString(2) + "," + cursor.getString(3) + ","
4810 + cursor.getString(4) + "," + cursor.getString(5));
4811 }
4812 } finally {
4813 cursor.close();
4814 }
4815
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004816 fout.println();
4817 synchronized (mSessions) {
4818 final long now = SystemClock.elapsedRealtime();
4819 fout.println("Active Sessions: " + mSessions.size());
4820 for (Session session : mSessions.values()) {
4821 fout.println(" " + session.toDebugString(now));
4822 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004823 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004824
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004825 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004826 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004827 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004828 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004829 }
4830
Amith Yamasani04e0d262012-02-14 11:50:53 -08004831 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07004832 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004833 long identityToken = clearCallingIdentity();
4834 try {
4835 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4836 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4837 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004838
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004839 if (intent.getComponent() != null &&
4840 GrantCredentialsPermissionActivity.class.getName().equals(
4841 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004842 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004843 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004844 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004845 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004846 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004847 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07004848 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004849 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004850 Notification n = new Notification.Builder(contextForUser)
4851 .setWhen(0)
4852 .setSmallIcon(android.R.drawable.stat_sys_warning)
4853 .setColor(contextForUser.getColor(
4854 com.android.internal.R.color.system_notification_accent_color))
4855 .setContentTitle(String.format(notificationTitleFormat, account.name))
4856 .setContentText(message)
4857 .setContentIntent(PendingIntent.getActivityAsUser(
4858 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4859 null, user))
4860 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004861 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004862 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004863 } finally {
4864 restoreCallingIdentity(identityToken);
4865 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004866 }
4867
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004868 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004869 protected void installNotification(final int notificationId, final Notification n,
4870 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08004871 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004872 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08004873 }
4874
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004875 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004876 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004877 long identityToken = clearCallingIdentity();
4878 try {
4879 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004880 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004881 } finally {
4882 restoreCallingIdentity(identityToken);
4883 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004884 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004885
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004886 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
4887 for (String perm : permissions) {
4888 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
4889 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4890 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
4891 }
4892 final int opCode = AppOpsManager.permissionToOpCode(perm);
4893 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
4894 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
4895 return true;
4896 }
4897 }
4898 }
4899 return false;
4900 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004901
Amith Yamasani67df64b2012-12-14 12:09:36 -08004902 private int handleIncomingUser(int userId) {
4903 try {
4904 return ActivityManagerNative.getDefault().handleIncomingUser(
4905 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
4906 } catch (RemoteException re) {
4907 // Shouldn't happen, local.
4908 }
4909 return userId;
4910 }
4911
Christopher Tateccbf84f2013-05-08 15:25:41 -07004912 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004913 final int callingUserId = UserHandle.getUserId(callingUid);
4914
4915 final PackageManager userPackageManager;
4916 try {
4917 userPackageManager = mContext.createPackageContextAsUser(
4918 "android", 0, new UserHandle(callingUserId)).getPackageManager();
4919 } catch (NameNotFoundException e) {
4920 return false;
4921 }
4922
4923 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07004924 for (String name : packages) {
4925 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004926 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08004927 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08004928 && (packageInfo.applicationInfo.privateFlags
4929 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07004930 return true;
4931 }
4932 } catch (PackageManager.NameNotFoundException e) {
4933 return false;
4934 }
4935 }
4936 return false;
4937 }
4938
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004939 private boolean permissionIsGranted(
4940 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07004941 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07004942 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004943 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07004944 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08004945 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004946 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4947 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08004948 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004949 + ": is authenticator? " + fromAuthenticator
4950 + ", has explicit permission? " + hasExplicitGrants);
4951 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07004952 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004953 }
4954
Svetoslavf3f02ac2015-09-08 14:36:35 -07004955 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
4956 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004957 if (accountType == null) {
4958 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004959 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07004960 return getTypesVisibleToCaller(callingUid, userId,
4961 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004962 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004963 }
4964
4965 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
4966 if (accountType == null) {
4967 return false;
4968 } else {
4969 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
4970 }
4971 }
4972
Svetoslavf3f02ac2015-09-08 14:36:35 -07004973 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
4974 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004975 boolean isPermitted =
4976 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
4977 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004978 return getTypesForCaller(callingUid, userId, isPermitted);
4979 }
4980
4981 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
4982 return getTypesForCaller(callingUid, userId, false);
4983 }
4984
4985 private List<String> getTypesForCaller(
4986 int callingUid, int userId, boolean isOtherwisePermitted) {
4987 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004988 long identityToken = Binder.clearCallingIdentity();
4989 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
4990 try {
4991 serviceInfos = mAuthenticatorCache.getAllServices(userId);
4992 } finally {
4993 Binder.restoreCallingIdentity(identityToken);
4994 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004995 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004996 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004997 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
4998 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
4999 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005000 }
5001 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005002 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005003 }
5004
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005005 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5006 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5007 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5008 if (account.name.equals(accountName)) {
5009 return true;
5010 }
5011 }
5012 }
5013 return false;
5014 }
5015
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005016 private static void checkManageUsersPermission(String message) {
5017 if (ActivityManager.checkComponentPermission(
5018 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5019 != PackageManager.PERMISSION_GRANTED) {
5020 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5021 }
5022 }
5023
Amith Yamasani04e0d262012-02-14 11:50:53 -08005024 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5025 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07005026 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005027 return true;
5028 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005029 UserAccounts accounts = getUserAccountsForCaller();
5030 synchronized (accounts.cacheLock) {
5031 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
5032 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005033 account.name, account.type};
5034 final boolean permissionGranted =
5035 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
5036 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5037 // TODO: Skip this check when running automated tests. Replace this
5038 // with a more general solution.
5039 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08005040 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005041 + " but ignoring since device is in test harness.");
5042 return true;
5043 }
5044 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005045 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005046 }
5047
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005048 private boolean isSystemUid(int callingUid) {
5049 String[] packages = null;
5050 long ident = Binder.clearCallingIdentity();
5051 try {
5052 packages = mPackageManager.getPackagesForUid(callingUid);
5053 } finally {
5054 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005055 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005056 if (packages != null) {
5057 for (String name : packages) {
5058 try {
5059 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5060 if (packageInfo != null
5061 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5062 != 0) {
5063 return true;
5064 }
5065 } catch (PackageManager.NameNotFoundException e) {
5066 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5067 }
5068 }
5069 } else {
5070 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005071 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005072 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005073 }
5074
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005075 /** Succeeds if any of the specified permissions are granted. */
5076 private void checkReadAccountsPermitted(
5077 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005078 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005079 int userId,
5080 String opPackageName) {
5081 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005082 String msg = String.format(
5083 "caller uid %s cannot access %s accounts",
5084 callingUid,
5085 accountType);
5086 Log.w(TAG, " " + msg);
5087 throw new SecurityException(msg);
5088 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005089 }
5090
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005091 private boolean canUserModifyAccounts(int userId, int callingUid) {
5092 // the managing app can always modify accounts
5093 if (isProfileOwner(callingUid)) {
5094 return true;
5095 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005096 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5097 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5098 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005099 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005100 return true;
5101 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005102
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005103 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5104 // the managing app can always modify accounts
5105 if (isProfileOwner(callingUid)) {
5106 return true;
5107 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005108 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5109 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005110 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005111 if (typesArray == null) {
5112 return true;
5113 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005114 for (String forbiddenType : typesArray) {
5115 if (forbiddenType.equals(accountType)) {
5116 return false;
5117 }
5118 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005119 return true;
5120 }
5121
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005122 private boolean isProfileOwner(int uid) {
5123 final DevicePolicyManagerInternal dpmi =
5124 LocalServices.getService(DevicePolicyManagerInternal.class);
5125 return (dpmi != null)
5126 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5127 }
5128
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005129 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005130 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5131 throws RemoteException {
5132 final int callingUid = getCallingUid();
5133
Amith Yamasani27db4682013-03-30 17:07:47 -07005134 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005135 throw new SecurityException();
5136 }
5137
5138 if (value) {
5139 grantAppPermission(account, authTokenType, uid);
5140 } else {
5141 revokeAppPermission(account, authTokenType, uid);
5142 }
5143 }
5144
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005145 /**
5146 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5147 * <p>
5148 * Although this is public it can only be accessed via the AccountManagerService object
5149 * which is in the system. This means we don't need to protect it with permissions.
5150 * @hide
5151 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005152 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005153 if (account == null || authTokenType == null) {
5154 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005155 return;
5156 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005157 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005158 synchronized (accounts.cacheLock) {
5159 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005160 db.beginTransaction();
5161 try {
5162 long accountId = getAccountIdLocked(db, account);
5163 if (accountId >= 0) {
5164 ContentValues values = new ContentValues();
5165 values.put(GRANTS_ACCOUNTS_ID, accountId);
5166 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
5167 values.put(GRANTS_GRANTEE_UID, uid);
5168 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
5169 db.setTransactionSuccessful();
5170 }
5171 } finally {
5172 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005173 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005174 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005175 UserHandle.of(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005176 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005177 }
5178
5179 /**
5180 * Don't allow callers with the given uid permission to get credentials for
5181 * account/authTokenType.
5182 * <p>
5183 * Although this is public it can only be accessed via the AccountManagerService object
5184 * which is in the system. This means we don't need to protect it with permissions.
5185 * @hide
5186 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005187 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005188 if (account == null || authTokenType == null) {
5189 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005190 return;
5191 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005192 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005193 synchronized (accounts.cacheLock) {
5194 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005195 db.beginTransaction();
5196 try {
5197 long accountId = getAccountIdLocked(db, account);
5198 if (accountId >= 0) {
5199 db.delete(TABLE_GRANTS,
5200 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
5201 + GRANTS_GRANTEE_UID + "=?",
5202 new String[]{String.valueOf(accountId), authTokenType,
5203 String.valueOf(uid)});
5204 db.setTransactionSuccessful();
5205 }
5206 } finally {
5207 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005208 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005209 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5210 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005211 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005212 }
Fred Quintana56285a62010-12-02 14:20:51 -08005213
5214 static final private String stringArrayToString(String[] value) {
5215 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5216 }
5217
Amith Yamasani04e0d262012-02-14 11:50:53 -08005218 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5219 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005220 if (oldAccountsForType != null) {
5221 ArrayList<Account> newAccountsList = new ArrayList<Account>();
5222 for (Account curAccount : oldAccountsForType) {
5223 if (!curAccount.equals(account)) {
5224 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005225 }
5226 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005227 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005228 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005229 } else {
5230 Account[] newAccountsForType = new Account[newAccountsList.size()];
5231 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005232 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005233 }
Fred Quintana56285a62010-12-02 14:20:51 -08005234 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005235 accounts.userDataCache.remove(account);
5236 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005237 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005238 }
5239
5240 /**
5241 * This assumes that the caller has already checked that the account is not already present.
5242 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08005243 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5244 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005245 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5246 Account[] newAccountsForType = new Account[oldLength + 1];
5247 if (accountsForType != null) {
5248 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005249 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005250 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005251 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08005252 }
5253
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005254 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07005255 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005256 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07005257 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005258 return unfiltered;
5259 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005260 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005261 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005262 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005263 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005264 // otherwise return non-shared accounts only.
5265 // This might be a temporary way to specify a whitelist
5266 String whiteList = mContext.getResources().getString(
5267 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5268 for (String packageName : packages) {
5269 if (whiteList.contains(";" + packageName + ";")) {
5270 return unfiltered;
5271 }
5272 }
5273 ArrayList<Account> allowed = new ArrayList<Account>();
5274 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5275 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005276 String requiredAccountType = "";
5277 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005278 // If there's an explicit callingPackage specified, check if that package
5279 // opted in to see restricted accounts.
5280 if (callingPackage != null) {
5281 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005282 if (pi != null && pi.restrictedAccountType != null) {
5283 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005284 }
5285 } else {
5286 // Otherwise check if the callingUid has a package that has opted in
5287 for (String packageName : packages) {
5288 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5289 if (pi != null && pi.restrictedAccountType != null) {
5290 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005291 break;
5292 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005293 }
5294 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005295 } catch (NameNotFoundException nnfe) {
5296 }
5297 for (Account account : unfiltered) {
5298 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005299 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005300 } else {
5301 boolean found = false;
5302 for (Account shared : sharedAccounts) {
5303 if (shared.equals(account)) {
5304 found = true;
5305 break;
5306 }
5307 }
5308 if (!found) {
5309 allowed.add(account);
5310 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005311 }
5312 }
5313 Account[] filtered = new Account[allowed.size()];
5314 allowed.toArray(filtered);
5315 return filtered;
5316 } else {
5317 return unfiltered;
5318 }
5319 }
5320
Amith Yamasani27db4682013-03-30 17:07:47 -07005321 /*
5322 * packageName can be null. If not null, it should be used to filter out restricted accounts
5323 * that the package is not allowed to access.
5324 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005325 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07005326 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005327 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005328 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005329 if (accounts == null) {
5330 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005331 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005332 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07005333 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005334 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005335 } else {
5336 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005337 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005338 totalLength += accounts.length;
5339 }
5340 if (totalLength == 0) {
5341 return EMPTY_ACCOUNT_ARRAY;
5342 }
5343 Account[] accounts = new Account[totalLength];
5344 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005345 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005346 System.arraycopy(accountsOfType, 0, accounts, totalLength,
5347 accountsOfType.length);
5348 totalLength += accountsOfType.length;
5349 }
Amith Yamasani27db4682013-03-30 17:07:47 -07005350 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005351 }
5352 }
5353
Amith Yamasani04e0d262012-02-14 11:50:53 -08005354 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5355 Account account, String key, String value) {
5356 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005357 if (userDataForAccount == null) {
5358 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005359 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005360 }
5361 if (value == null) {
5362 userDataForAccount.remove(key);
5363 } else {
5364 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005365 }
5366 }
5367
Carlos Valdivia91979be2015-05-22 14:11:35 -07005368 protected String readCachedTokenInternal(
5369 UserAccounts accounts,
5370 Account account,
5371 String tokenType,
5372 String callingPackage,
5373 byte[] pkgSigDigest) {
5374 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005375 return accounts.accountTokenCaches.get(
5376 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005377 }
5378 }
5379
Amith Yamasani04e0d262012-02-14 11:50:53 -08005380 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5381 Account account, String key, String value) {
5382 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005383 if (authTokensForAccount == null) {
5384 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005385 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005386 }
5387 if (value == null) {
5388 authTokensForAccount.remove(key);
5389 } else {
5390 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005391 }
5392 }
5393
Amith Yamasani04e0d262012-02-14 11:50:53 -08005394 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5395 String authTokenType) {
5396 synchronized (accounts.cacheLock) {
5397 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005398 if (authTokensForAccount == null) {
5399 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005400 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005401 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005402 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005403 }
5404 return authTokensForAccount.get(authTokenType);
5405 }
5406 }
5407
Simranjit Kohli858511c2016-03-10 18:36:11 +00005408 protected String readUserDataInternalLocked(
5409 UserAccounts accounts, Account account, String key) {
5410 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
5411 if (userDataForAccount == null) {
5412 // need to populate the cache for this account
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005413 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Simranjit Kohli858511c2016-03-10 18:36:11 +00005414 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
5415 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005416 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005417 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005418 }
5419
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005420 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
5421 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005422 HashMap<String, String> userDataForAccount = new HashMap<>();
5423 Cursor cursor = db.query(CE_TABLE_EXTRAS,
Fred Quintana56285a62010-12-02 14:20:51 -08005424 COLUMNS_EXTRAS_KEY_AND_VALUE,
5425 SELECTION_USERDATA_BY_ACCOUNT,
5426 new String[]{account.name, account.type},
5427 null, null, null);
5428 try {
5429 while (cursor.moveToNext()) {
5430 final String tmpkey = cursor.getString(0);
5431 final String value = cursor.getString(1);
5432 userDataForAccount.put(tmpkey, value);
5433 }
5434 } finally {
5435 cursor.close();
5436 }
5437 return userDataForAccount;
5438 }
5439
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005440 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
5441 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005442 HashMap<String, String> authTokensForAccount = new HashMap<>();
5443 Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
Fred Quintana56285a62010-12-02 14:20:51 -08005444 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
5445 SELECTION_AUTHTOKENS_BY_ACCOUNT,
5446 new String[]{account.name, account.type},
5447 null, null, null);
5448 try {
5449 while (cursor.moveToNext()) {
5450 final String type = cursor.getString(0);
5451 final String authToken = cursor.getString(1);
5452 authTokensForAccount.put(type, authToken);
5453 }
5454 } finally {
5455 cursor.close();
5456 }
5457 return authTokensForAccount;
5458 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005459
5460 private Context getContextForUser(UserHandle user) {
5461 try {
5462 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5463 } catch (NameNotFoundException e) {
5464 // Default to mContext, not finding the package system is running as is unlikely.
5465 return mContext;
5466 }
5467 }
Sandra Kwan78812282015-11-04 11:19:47 -08005468
5469 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5470 try {
5471 response.onResult(result);
5472 } catch (RemoteException e) {
5473 // if the caller is dead then there is no one to care about remote
5474 // exceptions
5475 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5476 Log.v(TAG, "failure while notifying response", e);
5477 }
5478 }
5479 }
5480
5481 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5482 String errorMessage) {
5483 try {
5484 response.onError(errorCode, errorMessage);
5485 } catch (RemoteException e) {
5486 // if the caller is dead then there is no one to care about remote
5487 // exceptions
5488 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5489 Log.v(TAG, "failure while notifying response", e);
5490 }
5491 }
5492 }
Fred Quintana60307342009-03-24 22:48:12 -07005493}