blob: 39f054c81a8f7ebd09ec2220376d25d96b30e08d [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);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700412 // Invalidate user-specific cache to make sure we catch any
413 // removed authenticators.
414 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
415 }
416
417 /**
418 * Validate internal set of accounts against installed authenticators for
419 * given user. Clear cached authenticators before validating when requested.
420 */
421 private void validateAccountsInternal(
422 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700423 if (Log.isLoggable(TAG, Log.DEBUG)) {
424 Log.d(TAG, "validateAccountsInternal " + accounts.userId
425 + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600426 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700427 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700428
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700429 if (invalidateAuthenticatorCache) {
430 mAuthenticatorCache.invalidateCache(accounts.userId);
431 }
432
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700433 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
434 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -0700435 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700436
Amith Yamasani04e0d262012-02-14 11:50:53 -0800437 synchronized (accounts.cacheLock) {
438 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800439 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800440
441 // Get a list of stored authenticator type and UID
442 Cursor metaCursor = db.query(
443 TABLE_META,
444 new String[] {META_KEY, META_VALUE},
445 SELECTION_META_BY_AUTHENTICATOR_TYPE,
446 new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
447 null /* groupBy */,
448 null /* having */,
449 META_KEY);
450 // Create a list of authenticator type whose previous uid no longer exists
451 HashSet<String> obsoleteAuthType = Sets.newHashSet();
452 try {
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700453 SparseBooleanArray knownUids = null;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800454 while (metaCursor.moveToNext()) {
455 String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
456 String uid = metaCursor.getString(1);
457 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uid)) {
458 // Should never happen.
459 Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
460 + ", uid empty: " + TextUtils.isEmpty(uid));
461 continue;
462 }
463 Integer knownUid = knownAuth.get(type);
464 if (knownUid != null && uid.equals(knownUid.toString())) {
465 // Remove it from the knownAuth list if it's unchanged.
466 knownAuth.remove(type);
467 } else {
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700468 /*
469 * The authenticator is presently not cached and should only be triggered
470 * when we think an authenticator has been removed (or is being updated).
471 * But we still want to check if any data with the associated uid is
472 * around. This is an (imperfect) signal that the package may be updating.
473 *
474 * A side effect of this is that an authenticator sharing a uid with
475 * multiple apps won't get its credentials wiped as long as some app with
476 * that uid is still on the device. But I suspect that this is a rare case.
477 * And it isn't clear to me how an attacker could really exploit that
478 * feature.
479 *
480 * The upshot is that we don't have to worry about accounts getting
481 * uninstalled while the authenticator's package is being updated.
482 *
483 */
484 if (knownUids == null) {
485 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
486 }
487 if (!knownUids.get(Integer.parseInt(uid))) {
488 // The authenticator is not presently available to the cache. And the
489 // package no longer has a data directory (so we surmise it isn't updating).
490 // So purge its data from the account databases.
491 obsoleteAuthType.add(type);
492 // And delete it from the TABLE_META
493 db.delete(
494 TABLE_META,
495 META_KEY + "=? AND " + META_VALUE + "=?",
496 new String[] {
497 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
498 uid}
499 );
500 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800501 }
502 }
503 } finally {
504 metaCursor.close();
505 }
506
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700507 // Add the newly registered authenticator to TABLE_META. If old authenticators have
508 // been renabled (after being updated for example), then we just overwrite the old
509 // values.
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800510 Iterator<Entry<String, Integer>> iterator = knownAuth.entrySet().iterator();
511 while (iterator.hasNext()) {
512 Entry<String, Integer> entry = iterator.next();
513 ContentValues values = new ContentValues();
514 values.put(META_KEY,
515 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
516 values.put(META_VALUE, entry.getValue());
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700517 db.insertWithOnConflict(TABLE_META, null, values, SQLiteDatabase.CONFLICT_REPLACE);
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800518 }
519
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800520 Cursor cursor = db.query(TABLE_ACCOUNTS,
521 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800522 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800523 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800524 accounts.accountCache.clear();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700525 final HashMap<String, ArrayList<String>> accountNamesByType = new LinkedHashMap<>();
Fred Quintana56285a62010-12-02 14:20:51 -0800526 while (cursor.moveToNext()) {
527 final long accountId = cursor.getLong(0);
528 final String accountType = cursor.getString(1);
529 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700530
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800531 if (obsoleteAuthType.contains(accountType)) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700532 Slog.w(TAG, "deleting account " + accountName + " because type "
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800533 + accountType + "'s registered authenticator no longer exist.");
Fyodor Kupolov627fc202016-06-03 11:03:03 -0700534 db.beginTransaction();
535 try {
536 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
537 // Also delete from CE table if user is unlocked; if user is currently
538 // locked the account will be removed later by syncDeCeAccountsLocked
539 if (userUnlocked) {
540 db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
541 }
542 db.setTransactionSuccessful();
543 } finally {
544 db.endTransaction();
545 }
Fred Quintana56285a62010-12-02 14:20:51 -0800546 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700547
548 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
549 accountId, accounts);
550
Fred Quintana56285a62010-12-02 14:20:51 -0800551 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800552 accounts.userDataCache.remove(account);
553 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700554 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800555 } else {
556 ArrayList<String> accountNames = accountNamesByType.get(accountType);
557 if (accountNames == null) {
558 accountNames = new ArrayList<String>();
559 accountNamesByType.put(accountType, accountNames);
560 }
561 accountNames.add(accountName);
562 }
563 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700564 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800565 final String accountType = cur.getKey();
566 final ArrayList<String> accountNames = cur.getValue();
567 final Account[] accountsForType = new Account[accountNames.size()];
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700568 for (int i = 0; i < accountsForType.length; i++) {
569 accountsForType[i] = new Account(accountNames.get(i), accountType);
Fred Quintana56285a62010-12-02 14:20:51 -0800570 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800571 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800572 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800573 } finally {
574 cursor.close();
575 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800576 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800577 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800578 }
579 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700580 }
581
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700582 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
583 // Get the UIDs of all apps that might have data on the device. We want
584 // to preserve user data if the app might otherwise be storing data.
585 List<PackageInfo> pkgsWithData =
586 mPackageManager.getInstalledPackagesAsUser(
587 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
588 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
589 for (PackageInfo pkgInfo : pkgsWithData) {
590 if (pkgInfo.applicationInfo != null
591 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
592 knownUids.put(pkgInfo.applicationInfo.uid, true);
593 }
594 }
595 return knownUids;
596 }
597
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800598 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
599 Context context,
600 int userId) {
601 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700602 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
603 }
604
605 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
606 IAccountAuthenticatorCache authCache,
607 int userId) {
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800608 HashMap<String, Integer> knownAuth = new HashMap<>();
609 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
610 .getAllServices(userId)) {
611 knownAuth.put(service.type.type, service.uid);
612 }
613 return knownAuth;
614 }
615
Amith Yamasani04e0d262012-02-14 11:50:53 -0800616 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700617 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800618 }
619
620 protected UserAccounts getUserAccounts(int userId) {
621 synchronized (mUsers) {
622 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700623 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800624 if (accounts == null) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700625 File preNDbFile = new File(getPreNDatabaseName(userId));
626 File deDbFile = new File(getDeDatabaseName(userId));
627 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700628 initializeDebugDbSizeAndCompileSqlStatementForLogging(
629 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800630 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700631 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700632 validateAccounts = true;
633 }
634 // open CE database if necessary
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600635 if (!accounts.openHelper.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700636 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
637 synchronized (accounts.cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700638 File preNDatabaseFile = new File(getPreNDatabaseName(userId));
639 File ceDatabaseFile = new File(getCeDatabaseName(userId));
640 CeDatabaseHelper.create(mContext, userId, preNDatabaseFile, ceDatabaseFile);
641 accounts.openHelper.attachCeDatabase(ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700642 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700643 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700644 }
645 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700646 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800647 }
648 return accounts;
649 }
650 }
651
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700652 private void syncDeCeAccountsLocked(UserAccounts accounts) {
653 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
654 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
655 List<Account> accountsToRemove = CeDatabaseHelper.findCeAccountsNotInDe(db);
656 if (!accountsToRemove.isEmpty()) {
657 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
658 + accounts.userId + " was locked. Removing accounts from CE tables");
659 logRecord(accounts, DebugDbHelper.ACTION_SYNC_DE_CE_ACCOUNTS, TABLE_ACCOUNTS);
660
661 for (Account account : accountsToRemove) {
662 removeAccountInternal(accounts, account, Process.myUid());
663 }
664 }
665 }
666
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700667 private void purgeOldGrantsAll() {
668 synchronized (mUsers) {
669 for (int i = 0; i < mUsers.size(); i++) {
670 purgeOldGrants(mUsers.valueAt(i));
671 }
672 }
673 }
674
675 private void purgeOldGrants(UserAccounts accounts) {
676 synchronized (accounts.cacheLock) {
677 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
678 final Cursor cursor = db.query(TABLE_GRANTS,
679 new String[]{GRANTS_GRANTEE_UID},
680 null, null, GRANTS_GRANTEE_UID, null, null);
681 try {
682 while (cursor.moveToNext()) {
683 final int uid = cursor.getInt(0);
684 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
685 if (packageExists) {
686 continue;
687 }
688 Log.d(TAG, "deleting grants for UID " + uid
689 + " because its package is no longer installed");
690 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
691 new String[]{Integer.toString(uid)});
692 }
693 } finally {
694 cursor.close();
695 }
696 }
697 }
698
Amith Yamasani13593602012-03-22 16:16:17 -0700699 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700700 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700701 if (userId < 1) return;
702
703 UserAccounts accounts;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700704 boolean userUnlocked;
Amith Yamasani13593602012-03-22 16:16:17 -0700705 synchronized (mUsers) {
706 accounts = mUsers.get(userId);
707 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600708 userUnlocked = mLocalUnlockedUsers.get(userId);
709 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700710 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700711 if (accounts != null) {
712 synchronized (accounts.cacheLock) {
713 accounts.openHelper.close();
714 }
Amith Yamasani13593602012-03-22 16:16:17 -0700715 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700716 Log.i(TAG, "Removing database files for user " + userId);
717 File dbFile = new File(getDeDatabaseName(userId));
Amith Yamasani13593602012-03-22 16:16:17 -0700718
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700719 deleteDbFileWarnIfFailed(dbFile);
720 // Remove CE file if user is unlocked, or FBE is not enabled
721 boolean fbeEnabled = StorageManager.isFileEncryptedNativeOrEmulated();
722 if (!fbeEnabled || userUnlocked) {
723 File ceDb = new File(getCeDatabaseName(userId));
724 if (ceDb.exists()) {
725 deleteDbFileWarnIfFailed(ceDb);
726 }
727 }
728 }
729
730 private static void deleteDbFileWarnIfFailed(File dbFile) {
731 if (!SQLiteDatabase.deleteDatabase(dbFile)) {
732 Log.w(TAG, "Database at " + dbFile + " was not deleted successfully");
Amith Yamasani13593602012-03-22 16:16:17 -0700733 }
734 }
735
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700736 @VisibleForTesting
737 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600738 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
739 }
740
741 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700742 if (Log.isLoggable(TAG, Log.VERBOSE)) {
743 Log.v(TAG, "onUserUnlocked " + userId);
744 }
745 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600746 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700747 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800748 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700749 syncSharedAccounts(userId);
750 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800751
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700752 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800753 // Check if there's a shared account that needs to be created as an account
754 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
755 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700756 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700757 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -0700758 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700759 : UserHandle.USER_SYSTEM;
760 if (parentUserId < 0) {
761 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
762 return;
763 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800764 for (Account sa : sharedAccounts) {
765 if (ArrayUtils.contains(accounts, sa)) continue;
766 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700767 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800768 }
769 }
770
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700771 @Override
772 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700773 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700774 }
775
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800776 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700777 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700778 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800779 if (Log.isLoggable(TAG, Log.VERBOSE)) {
780 Log.v(TAG, "getPassword: " + account
781 + ", caller's uid " + Binder.getCallingUid()
782 + ", pid " + Binder.getCallingPid());
783 }
Fred Quintana382601f2010-03-25 12:25:10 -0700784 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000785 int userId = UserHandle.getCallingUserId();
786 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700787 String msg = String.format(
788 "uid %s cannot get secrets for accounts of type: %s",
789 callingUid,
790 account.type);
791 throw new SecurityException(msg);
792 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700793 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700794 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700795 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800796 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700797 } finally {
798 restoreCallingIdentity(identityToken);
799 }
800 }
801
Amith Yamasani04e0d262012-02-14 11:50:53 -0800802 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700803 if (account == null) {
804 return null;
805 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600806 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700807 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
808 return null;
809 }
Fred Quintana31957f12009-10-21 13:43:10 -0700810
Amith Yamasani04e0d262012-02-14 11:50:53 -0800811 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700812 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
813 return CeDatabaseHelper.findAccountPasswordByNameAndType(db, account.name,
814 account.type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700815 }
816 }
817
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800818 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700819 public String getPreviousName(Account account) {
820 if (Log.isLoggable(TAG, Log.VERBOSE)) {
821 Log.v(TAG, "getPreviousName: " + account
822 + ", caller's uid " + Binder.getCallingUid()
823 + ", pid " + Binder.getCallingPid());
824 }
825 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700826 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700827 long identityToken = clearCallingIdentity();
828 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700829 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700830 return readPreviousNameInternal(accounts, account);
831 } finally {
832 restoreCallingIdentity(identityToken);
833 }
834 }
835
836 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
837 if (account == null) {
838 return null;
839 }
840 synchronized (accounts.cacheLock) {
841 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
842 if (previousNameRef == null) {
843 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
844 Cursor cursor = db.query(
845 TABLE_ACCOUNTS,
846 new String[]{ ACCOUNTS_PREVIOUS_NAME },
847 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
848 new String[] { account.name, account.type },
849 null,
850 null,
851 null);
852 try {
853 if (cursor.moveToNext()) {
854 String previousName = cursor.getString(0);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700855 previousNameRef = new AtomicReference<>(previousName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700856 accounts.previousNameCache.put(account, previousNameRef);
857 return previousName;
858 } else {
859 return null;
860 }
861 } finally {
862 cursor.close();
863 }
864 } else {
865 return previousNameRef.get();
866 }
867 }
868 }
869
870 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700871 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700872 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800873 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700874 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
875 account, key, callingUid, Binder.getCallingPid());
876 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800877 }
Fred Quintana382601f2010-03-25 12:25:10 -0700878 if (account == null) throw new IllegalArgumentException("account is null");
879 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000880 int userId = UserHandle.getCallingUserId();
881 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700882 String msg = String.format(
883 "uid %s cannot get user data for accounts of type: %s",
884 callingUid,
885 account.type);
886 throw new SecurityException(msg);
887 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600888 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -0700889 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
890 return null;
891 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700892 long identityToken = clearCallingIdentity();
893 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700894 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +0000895 synchronized (accounts.cacheLock) {
896 if (!accountExistsCacheLocked(accounts, account)) {
897 return null;
898 }
899 return readUserDataInternalLocked(accounts, account, key);
900 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700901 } finally {
902 restoreCallingIdentity(identityToken);
903 }
904 }
905
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800906 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100907 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700908 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800909 if (Log.isLoggable(TAG, Log.VERBOSE)) {
910 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100911 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700912 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800913 + ", pid " + Binder.getCallingPid());
914 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100915 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700916 if (isCrossUser(callingUid, userId)) {
917 throw new SecurityException(
918 String.format(
919 "User %s tying to get authenticator types for %s" ,
920 UserHandle.getCallingUserId(),
921 userId));
922 }
923
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700924 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700925 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000926 return getAuthenticatorTypesInternal(userId);
927
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700928 } finally {
929 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700930 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700931 }
932
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000933 /**
934 * Should only be called inside of a clearCallingIdentity block.
935 */
936 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
937 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
938 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
939 AuthenticatorDescription[] types =
940 new AuthenticatorDescription[authenticatorCollection.size()];
941 int i = 0;
942 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
943 : authenticatorCollection) {
944 types[i] = authenticator.type;
945 i++;
946 }
947 return types;
948 }
949
950
951
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700952 private boolean isCrossUser(int callingUid, int userId) {
953 return (userId != UserHandle.getCallingUserId()
954 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100955 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
957 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100958 }
959
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700960 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700961 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600962 Bundle.setDefusable(extras, true);
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700963 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800964 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700965 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700966 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800967 + ", pid " + Binder.getCallingPid());
968 }
Fred Quintana382601f2010-03-25 12:25:10 -0700969 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000970 int userId = UserHandle.getCallingUserId();
971 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700972 String msg = String.format(
973 "uid %s cannot explicitly add accounts of type: %s",
974 callingUid,
975 account.type);
976 throw new SecurityException(msg);
977 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700978 /*
979 * Child users are not allowed to add accounts. Only the accounts that are
980 * shared by the parent profile can be added to child profile.
981 *
982 * TODO: Only allow accounts that were shared to be added by
983 * a limited user.
984 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700985
Fred Quintana60307342009-03-24 22:48:12 -0700986 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700987 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700988 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700989 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700990 return addAccountInternal(accounts, account, password, extras, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700991 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700992 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700993 }
994 }
995
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000996 @Override
997 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700998 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700999 int callingUid = Binder.getCallingUid();
1000 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1001 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001002 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001003 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001004 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1005 final UserAccounts toAccounts = getUserAccounts(userTo);
1006 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001007 if (response != null) {
1008 Bundle result = new Bundle();
1009 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1010 try {
1011 response.onResult(result);
1012 } catch (RemoteException e) {
1013 Slog.w(TAG, "Failed to report error back to the client." + e);
1014 }
1015 }
1016 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001017 }
1018
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001019 Slog.d(TAG, "Copying account " + account.name
1020 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001021 long identityToken = clearCallingIdentity();
1022 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001023 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001024 false /* stripAuthTokenFromResult */, account.name,
1025 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001026 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001027 protected String toDebugString(long now) {
1028 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1029 + ", " + account.type;
1030 }
1031
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001032 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001033 public void run() throws RemoteException {
1034 mAuthenticator.getAccountCredentialsForCloning(this, account);
1035 }
1036
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001037 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001038 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001039 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001040 if (result != null
1041 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1042 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001043 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001044 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001045 super.onResult(result);
1046 }
1047 }
1048 }.bind();
1049 } finally {
1050 restoreCallingIdentity(identityToken);
1051 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001052 }
1053
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001054 @Override
1055 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001056 final int callingUid = Binder.getCallingUid();
1057 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1058 String msg = String.format(
1059 "accountAuthenticated( account: %s, callerUid: %s)",
1060 account,
1061 callingUid);
1062 Log.v(TAG, msg);
1063 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001064 if (account == null) {
1065 throw new IllegalArgumentException("account is null");
1066 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001067 int userId = UserHandle.getCallingUserId();
1068 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001069 String msg = String.format(
1070 "uid %s cannot notify authentication for accounts of type: %s",
1071 callingUid,
1072 account.type);
1073 throw new SecurityException(msg);
1074 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001075
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001076 if (!canUserModifyAccounts(userId, callingUid) ||
1077 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001078 return false;
1079 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001080
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001081 long identityToken = clearCallingIdentity();
1082 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001083 UserAccounts accounts = getUserAccounts(userId);
1084 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001085 } finally {
1086 restoreCallingIdentity(identityToken);
1087 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001088 }
1089
1090 private boolean updateLastAuthenticatedTime(Account account) {
1091 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001092 synchronized (accounts.cacheLock) {
1093 final ContentValues values = new ContentValues();
1094 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
1095 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1096 int i = db.update(
1097 TABLE_ACCOUNTS,
1098 values,
1099 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1100 new String[] {
1101 account.name, account.type
1102 });
1103 if (i > 0) {
1104 return true;
1105 }
1106 }
1107 return false;
1108 }
1109
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001110 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001111 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1112 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001113 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001114 long id = clearCallingIdentity();
1115 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001116 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001117 false /* stripAuthTokenFromResult */, account.name,
1118 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001119 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001120 protected String toDebugString(long now) {
1121 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1122 + ", " + account.type;
1123 }
1124
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001125 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001126 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001127 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001128 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001129 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -07001130 for (Account acc : getAccounts(parentUserId,
1131 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001132 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001133 mAuthenticator.addAccountFromCredentials(
1134 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001135 break;
1136 }
1137 }
1138 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001139 }
1140
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001141 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001142 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001143 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001144 // TODO: Anything to do if if succedded?
1145 // TODO: If it failed: Show error notification? Should we remove the shadow
1146 // account to avoid retries?
1147 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001148 }
1149
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001150 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001151 public void onError(int errorCode, String errorMessage) {
1152 super.onError(errorCode, errorMessage);
1153 // TODO: Show error notification to user
1154 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1155 }
1156
1157 }.bind();
1158 } finally {
1159 restoreCallingIdentity(id);
1160 }
1161 }
1162
Amith Yamasani04e0d262012-02-14 11:50:53 -08001163 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001164 Bundle extras, int callingUid) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001165 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001166 if (account == null) {
1167 return false;
1168 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001169 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001170 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1171 + " is locked. callingUid=" + callingUid);
1172 return false;
1173 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001174 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001175 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001176 db.beginTransaction();
1177 try {
1178 long numMatches = DatabaseUtils.longForQuery(db,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001179 "select count(*) from " + CE_TABLE_ACCOUNTS
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001180 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1181 new String[]{account.name, account.type});
1182 if (numMatches > 0) {
1183 Log.w(TAG, "insertAccountIntoDatabase: " + account
1184 + ", skipping since the account already exists");
1185 return false;
1186 }
1187 ContentValues values = new ContentValues();
1188 values.put(ACCOUNTS_NAME, account.name);
1189 values.put(ACCOUNTS_TYPE, account.type);
1190 values.put(ACCOUNTS_PASSWORD, password);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001191 long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001192 if (accountId < 0) {
1193 Log.w(TAG, "insertAccountIntoDatabase: " + account
1194 + ", skipping the DB insert failed");
1195 return false;
1196 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001197 // Insert into DE table
1198 values = new ContentValues();
1199 values.put(ACCOUNTS_ID, accountId);
1200 values.put(ACCOUNTS_NAME, account.name);
1201 values.put(ACCOUNTS_TYPE, account.type);
1202 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1203 System.currentTimeMillis());
1204 if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1205 Log.w(TAG, "insertAccountIntoDatabase: " + account
1206 + ", skipping the DB insert failed");
1207 return false;
1208 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001209 if (extras != null) {
1210 for (String key : extras.keySet()) {
1211 final String value = extras.getString(key);
1212 if (insertExtraLocked(db, accountId, key, value) < 0) {
1213 Log.w(TAG, "insertAccountIntoDatabase: " + account
1214 + ", skipping since insertExtra failed for key " + key);
1215 return false;
1216 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001217 }
1218 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001219 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001220
1221 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1222 accounts, callingUid);
1223
Amith Yamasani04e0d262012-02-14 11:50:53 -08001224 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001225 } finally {
1226 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001227 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001228 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001229 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001230 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1231 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001232 }
1233 return true;
1234 }
1235
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001236 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001237 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001238 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001239 }
1240 }
1241
Amith Yamasani5be347b2013-03-31 17:44:31 -07001242 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001243 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001244 * running, then clone the account too.
1245 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001246 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001247 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001248 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001249 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001250 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001251 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001252 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001253 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001254 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1255 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001256 }
1257 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001258 }
1259 }
1260
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001261 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -07001262 ContentValues values = new ContentValues();
1263 values.put(EXTRAS_KEY, key);
1264 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1265 values.put(EXTRAS_VALUE, value);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001266 return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
Fred Quintana60307342009-03-24 22:48:12 -07001267 }
1268
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001269 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001270 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001271 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001272 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001273 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1274 Log.v(TAG, "hasFeatures: " + account
1275 + ", response " + response
1276 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001277 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001278 + ", pid " + Binder.getCallingPid());
1279 }
Fred Quintana382601f2010-03-25 12:25:10 -07001280 if (response == null) throw new IllegalArgumentException("response is null");
1281 if (account == null) throw new IllegalArgumentException("account is null");
1282 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001283 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001284 checkReadAccountsPermitted(callingUid, account.type, userId,
1285 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001286
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001287 long identityToken = clearCallingIdentity();
1288 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001289 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001290 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001291 } finally {
1292 restoreCallingIdentity(identityToken);
1293 }
1294 }
1295
1296 private class TestFeaturesSession extends Session {
1297 private final String[] mFeatures;
1298 private final Account mAccount;
1299
Amith Yamasani04e0d262012-02-14 11:50:53 -08001300 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001301 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001302 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001303 true /* stripAuthTokenFromResult */, account.name,
1304 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001305 mFeatures = features;
1306 mAccount = account;
1307 }
1308
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001309 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001310 public void run() throws RemoteException {
1311 try {
1312 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1313 } catch (RemoteException e) {
1314 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1315 }
1316 }
1317
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001318 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001319 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001320 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001321 IAccountManagerResponse response = getResponseAndClose();
1322 if (response != null) {
1323 try {
1324 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001325 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001326 return;
1327 }
Fred Quintana56285a62010-12-02 14:20:51 -08001328 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1329 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1330 + response);
1331 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001332 final Bundle newResult = new Bundle();
1333 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1334 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1335 response.onResult(newResult);
1336 } catch (RemoteException e) {
1337 // if the caller is dead then there is no one to care about remote exceptions
1338 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1339 Log.v(TAG, "failure while notifying response", e);
1340 }
1341 }
1342 }
1343 }
1344
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001345 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001346 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001347 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001348 + ", " + mAccount
1349 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1350 }
1351 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001352
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001353 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001354 public void renameAccount(
1355 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001356 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001357 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1358 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001359 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001360 + ", pid " + Binder.getCallingPid());
1361 }
1362 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001363 int userId = UserHandle.getCallingUserId();
1364 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001365 String msg = String.format(
1366 "uid %s cannot rename accounts of type: %s",
1367 callingUid,
1368 accountToRename.type);
1369 throw new SecurityException(msg);
1370 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001371 long identityToken = clearCallingIdentity();
1372 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001373 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001374 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001375 Bundle result = new Bundle();
1376 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1377 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1378 try {
1379 response.onResult(result);
1380 } catch (RemoteException e) {
1381 Log.w(TAG, e.getMessage());
1382 }
1383 } finally {
1384 restoreCallingIdentity(identityToken);
1385 }
1386 }
1387
1388 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001389 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001390 Account resultAccount = null;
1391 /*
1392 * Cancel existing notifications. Let authenticators
1393 * re-post notifications as required. But we don't know if
1394 * the authenticators have bound their notifications to
1395 * now stale account name data.
1396 *
1397 * With a rename api, we might not need to do this anymore but it
1398 * shouldn't hurt.
1399 */
1400 cancelNotification(
1401 getSigninRequiredNotificationId(accounts, accountToRename),
1402 new UserHandle(accounts.userId));
1403 synchronized(accounts.credentialsPermissionNotificationIds) {
1404 for (Pair<Pair<Account, String>, Integer> pair:
1405 accounts.credentialsPermissionNotificationIds.keySet()) {
1406 if (accountToRename.equals(pair.first.first)) {
1407 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1408 cancelNotification(id, new UserHandle(accounts.userId));
1409 }
1410 }
1411 }
1412 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001413 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001414 db.beginTransaction();
1415 boolean isSuccessful = false;
1416 Account renamedAccount = new Account(newName, accountToRename.type);
1417 try {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001418 final long accountId = getAccountIdLocked(db, accountToRename);
1419 if (accountId >= 0) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001420 final ContentValues values = new ContentValues();
1421 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001422 final String[] argsAccountId = { String.valueOf(accountId) };
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001423 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1424 // Update NAME/PREVIOUS_NAME in DE accounts table
1425 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001426 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1427 db.setTransactionSuccessful();
1428 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001429 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1430 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001431 }
1432 } finally {
1433 db.endTransaction();
1434 if (isSuccessful) {
1435 /*
1436 * Database transaction was successful. Clean up cached
1437 * data associated with the account in the user profile.
1438 */
1439 insertAccountIntoCacheLocked(accounts, renamedAccount);
1440 /*
1441 * Extract the data and token caches before removing the
1442 * old account to preserve the user data associated with
1443 * the account.
1444 */
1445 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1446 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1447 removeAccountFromCacheLocked(accounts, accountToRename);
1448 /*
1449 * Update the cached data associated with the renamed
1450 * account.
1451 */
1452 accounts.userDataCache.put(renamedAccount, tmpData);
1453 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1454 accounts.previousNameCache.put(
1455 renamedAccount,
1456 new AtomicReference<String>(accountToRename.name));
1457 resultAccount = renamedAccount;
1458
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001459 int parentUserId = accounts.userId;
1460 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001461 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001462 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001463 * those users with which the account was shared.
1464 */
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001465 List<UserInfo> users = getUserManager().getUsers(true);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001466 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001467 if (user.isRestricted()
1468 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001469 renameSharedAccountAsUser(accountToRename, newName, user.id);
1470 }
1471 }
1472 }
1473 sendAccountsChangedBroadcast(accounts.userId);
1474 }
1475 }
1476 }
1477 return resultAccount;
1478 }
1479
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001480 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001481 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001482 return userInfo != null && userInfo.canHaveProfile();
1483 }
1484
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001485 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001486 public void removeAccount(IAccountManagerResponse response, Account account,
1487 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001488 removeAccountAsUser(
1489 response,
1490 account,
1491 expectActivityLaunch,
1492 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001493 }
1494
1495 @Override
1496 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001497 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001498 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001499 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1500 Log.v(TAG, "removeAccount: " + account
1501 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001502 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001503 + ", pid " + Binder.getCallingPid()
1504 + ", for user id " + userId);
1505 }
1506 if (response == null) throw new IllegalArgumentException("response is null");
1507 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001508 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001509 if (isCrossUser(callingUid, userId)) {
1510 throw new SecurityException(
1511 String.format(
1512 "User %s tying remove account for %s" ,
1513 UserHandle.getCallingUserId(),
1514 userId));
1515 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001516 /*
1517 * Only the system or authenticator should be allowed to remove accounts for that
1518 * authenticator. This will let users remove accounts (via Settings in the system) but not
1519 * arbitrary applications (like competing authenticators).
1520 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001521 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001522 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1523 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001524 String msg = String.format(
1525 "uid %s cannot remove accounts of type: %s",
1526 callingUid,
1527 account.type);
1528 throw new SecurityException(msg);
1529 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001530 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001531 try {
1532 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1533 "User cannot modify accounts");
1534 } catch (RemoteException re) {
1535 }
1536 return;
1537 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001538 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001539 try {
1540 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1541 "User cannot modify accounts of this type (policy).");
1542 } catch (RemoteException re) {
1543 }
1544 return;
1545 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001546 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001547 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001548 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001549 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001550 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001551 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001552 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001553 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001554 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001555 }
1556 }
1557 }
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07001558 SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
1559 final long accountId = getAccountIdLocked(db, account);
1560 logRecord(
1561 db,
1562 DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE,
1563 TABLE_ACCOUNTS,
1564 accountId,
1565 accounts,
1566 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001567 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001568 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1569 } finally {
1570 restoreCallingIdentity(identityToken);
1571 }
1572 }
1573
1574 @Override
1575 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001576 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001577 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1578 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001579 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001580 + ", pid " + Binder.getCallingPid());
1581 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001582 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001583 if (account == null) {
1584 /*
1585 * Null accounts should result in returning false, as per
1586 * AccountManage.addAccountExplicitly(...) java doc.
1587 */
1588 Log.e(TAG, "account is null");
1589 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001590 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001591 String msg = String.format(
1592 "uid %s cannot explicitly add accounts of type: %s",
1593 callingUid,
1594 account.type);
1595 throw new SecurityException(msg);
1596 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001597 UserAccounts accounts = getUserAccountsForCaller();
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07001598 SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
1599 final long accountId = getAccountIdLocked(db, account);
1600 logRecord(
1601 db,
1602 DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE,
1603 TABLE_ACCOUNTS,
1604 accountId,
1605 accounts,
1606 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001607 long identityToken = clearCallingIdentity();
1608 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001609 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001610 } finally {
1611 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001612 }
Fred Quintana60307342009-03-24 22:48:12 -07001613 }
1614
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001615 private class RemoveAccountSession extends Session {
1616 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001617 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001618 Account account, boolean expectActivityLaunch) {
1619 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001620 true /* stripAuthTokenFromResult */, account.name,
1621 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001622 mAccount = account;
1623 }
1624
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001625 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001626 protected String toDebugString(long now) {
1627 return super.toDebugString(now) + ", removeAccount"
1628 + ", account " + mAccount;
1629 }
1630
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001631 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001632 public void run() throws RemoteException {
1633 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1634 }
1635
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001636 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001637 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001638 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001639 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1640 && !result.containsKey(AccountManager.KEY_INTENT)) {
1641 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001642 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001643 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001644 }
1645 IAccountManagerResponse response = getResponseAndClose();
1646 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001647 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1648 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1649 + response);
1650 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001651 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001652 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001653 try {
1654 response.onResult(result2);
1655 } catch (RemoteException e) {
1656 // ignore
1657 }
1658 }
1659 }
1660 super.onResult(result);
1661 }
1662 }
1663
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001664 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001665 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001666 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001667 }
1668
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001669 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001670 int deleted;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001671 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001672 if (!userUnlocked) {
1673 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
1674 + " is still locked. CE data will be removed later");
1675 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001676 synchronized (accounts.cacheLock) {
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001677 final SQLiteDatabase db = userUnlocked
1678 ? accounts.openHelper.getWritableDatabaseUserIsUnlocked()
1679 : accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001680 final long accountId = getAccountIdLocked(db, account);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001681 db.beginTransaction();
1682 try {
1683 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1684 + "=?", new String[]{account.name, account.type});
1685 if (userUnlocked) {
1686 // Delete from CE table
1687 deleted = db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1688 + "=?", new String[]{account.name, account.type});
1689 }
1690 db.setTransactionSuccessful();
1691 } finally {
1692 db.endTransaction();
1693 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001694 removeAccountFromCacheLocked(accounts, account);
1695 sendAccountsChangedBroadcast(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001696 String action = userUnlocked ? DebugDbHelper.ACTION_ACCOUNT_REMOVE
1697 : DebugDbHelper.ACTION_ACCOUNT_REMOVE_DE;
1698 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001699 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001700 long id = Binder.clearCallingIdentity();
1701 try {
1702 int parentUserId = accounts.userId;
1703 if (canHaveProfile(parentUserId)) {
1704 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001705 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001706 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001707 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001708 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001709 }
1710 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001711 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001712 } finally {
1713 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001714 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001715 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001716 }
1717
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001718 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001719 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001720 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001721 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1722 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001723 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001724 + ", pid " + Binder.getCallingPid());
1725 }
Fred Quintana382601f2010-03-25 12:25:10 -07001726 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1727 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001728 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001729 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001730 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001731 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001732 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001733 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001734 db.beginTransaction();
1735 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001736 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001737 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001738 db.setTransactionSuccessful();
1739 } finally {
1740 db.endTransaction();
1741 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001742 }
Fred Quintana60307342009-03-24 22:48:12 -07001743 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001744 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001745 }
1746 }
1747
Carlos Valdivia91979be2015-05-22 14:11:35 -07001748 private void invalidateCustomTokenLocked(
1749 UserAccounts accounts,
1750 String accountType,
1751 String authToken) {
1752 if (authToken == null || accountType == null) {
1753 return;
1754 }
1755 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001756 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001757 }
1758
Amith Yamasani04e0d262012-02-14 11:50:53 -08001759 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1760 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001761 if (authToken == null || accountType == null) {
1762 return;
1763 }
Fred Quintana33269202009-04-20 16:05:10 -07001764 Cursor cursor = db.rawQuery(
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001765 "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1766 + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1767 + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1768 + " FROM " + CE_TABLE_ACCOUNTS
1769 + " JOIN " + CE_TABLE_AUTHTOKENS
1770 + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1771 + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
1772 + " WHERE " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_AUTHTOKEN
1773 + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
Fred Quintana33269202009-04-20 16:05:10 -07001774 new String[]{authToken, accountType});
1775 try {
1776 while (cursor.moveToNext()) {
1777 long authTokenId = cursor.getLong(0);
1778 String accountName = cursor.getString(1);
1779 String authTokenType = cursor.getString(2);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001780 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001781 writeAuthTokenIntoCacheLocked(
1782 accounts,
1783 db,
1784 new Account(accountName, accountType),
1785 authTokenType,
1786 null);
Fred Quintana60307342009-03-24 22:48:12 -07001787 }
Fred Quintana33269202009-04-20 16:05:10 -07001788 } finally {
1789 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001790 }
1791 }
1792
Carlos Valdivia91979be2015-05-22 14:11:35 -07001793 private void saveCachedToken(
1794 UserAccounts accounts,
1795 Account account,
1796 String callerPkg,
1797 byte[] callerSigDigest,
1798 String tokenType,
1799 String token,
1800 long expiryMillis) {
1801
1802 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1803 return;
1804 }
1805 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001806 UserHandle.of(accounts.userId));
Carlos Valdivia91979be2015-05-22 14:11:35 -07001807 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001808 accounts.accountTokenCaches.put(
1809 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001810 }
1811 }
1812
Amith Yamasani04e0d262012-02-14 11:50:53 -08001813 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1814 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001815 if (account == null || type == null) {
1816 return false;
1817 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001818 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001819 UserHandle.of(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001820 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001821 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001822 db.beginTransaction();
1823 try {
1824 long accountId = getAccountIdLocked(db, account);
1825 if (accountId < 0) {
1826 return false;
1827 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001828 db.delete(CE_TABLE_AUTHTOKENS,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001829 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1830 new String[]{type});
1831 ContentValues values = new ContentValues();
1832 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1833 values.put(AUTHTOKENS_TYPE, type);
1834 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001835 if (db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001836 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001837 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001838 return true;
1839 }
Fred Quintana33269202009-04-20 16:05:10 -07001840 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001841 } finally {
1842 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001843 }
Fred Quintana60307342009-03-24 22:48:12 -07001844 }
1845 }
1846
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001847 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001848 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001849 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001850 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1851 Log.v(TAG, "peekAuthToken: " + account
1852 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001853 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001854 + ", pid " + Binder.getCallingPid());
1855 }
Fred Quintana382601f2010-03-25 12:25:10 -07001856 if (account == null) throw new IllegalArgumentException("account is null");
1857 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001858 int userId = UserHandle.getCallingUserId();
1859 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001860 String msg = String.format(
1861 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1862 callingUid,
1863 account.type);
1864 throw new SecurityException(msg);
1865 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001866 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001867 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
1868 + callingUid);
1869 return null;
1870 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001871 long identityToken = clearCallingIdentity();
1872 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001873 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001874 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001875 } finally {
1876 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001877 }
Fred Quintana60307342009-03-24 22:48:12 -07001878 }
1879
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001880 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001881 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001882 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001883 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1884 Log.v(TAG, "setAuthToken: " + account
1885 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001886 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001887 + ", pid " + Binder.getCallingPid());
1888 }
Fred Quintana382601f2010-03-25 12:25:10 -07001889 if (account == null) throw new IllegalArgumentException("account is null");
1890 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001891 int userId = UserHandle.getCallingUserId();
1892 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001893 String msg = String.format(
1894 "uid %s cannot set auth tokens associated with accounts of type: %s",
1895 callingUid,
1896 account.type);
1897 throw new SecurityException(msg);
1898 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001899 long identityToken = clearCallingIdentity();
1900 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001901 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001902 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001903 } finally {
1904 restoreCallingIdentity(identityToken);
1905 }
Fred Quintana60307342009-03-24 22:48:12 -07001906 }
1907
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001908 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001909 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001910 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001911 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1912 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001913 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001914 + ", pid " + Binder.getCallingPid());
1915 }
Fred Quintana382601f2010-03-25 12:25:10 -07001916 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001917 int userId = UserHandle.getCallingUserId();
1918 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001919 String msg = String.format(
1920 "uid %s cannot set secrets for accounts of type: %s",
1921 callingUid,
1922 account.type);
1923 throw new SecurityException(msg);
1924 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001925 long identityToken = clearCallingIdentity();
1926 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001927 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001928 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001929 } finally {
1930 restoreCallingIdentity(identityToken);
1931 }
Fred Quintana60307342009-03-24 22:48:12 -07001932 }
1933
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001934 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1935 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001936 if (account == null) {
1937 return;
1938 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001939 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001940 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001941 db.beginTransaction();
1942 try {
1943 final ContentValues values = new ContentValues();
1944 values.put(ACCOUNTS_PASSWORD, password);
1945 final long accountId = getAccountIdLocked(db, account);
1946 if (accountId >= 0) {
1947 final String[] argsAccountId = {String.valueOf(accountId)};
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001948 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1949 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001950 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001951 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001952 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001953
1954 String action = (password == null || password.length() == 0) ?
1955 DebugDbHelper.ACTION_CLEAR_PASSWORD
1956 : DebugDbHelper.ACTION_SET_PASSWORD;
1957 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001958 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001959 } finally {
1960 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001961 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001962 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001963 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001964 }
1965
Amith Yamasani04e0d262012-02-14 11:50:53 -08001966 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001967 Log.i(TAG, "the accounts changed, sending broadcast of "
1968 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001969 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001970 }
1971
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001972 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001973 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001974 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001975 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1976 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001977 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001978 + ", pid " + Binder.getCallingPid());
1979 }
Fred Quintana382601f2010-03-25 12:25:10 -07001980 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001981 int userId = UserHandle.getCallingUserId();
1982 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001983 String msg = String.format(
1984 "uid %s cannot clear passwords for accounts of type: %s",
1985 callingUid,
1986 account.type);
1987 throw new SecurityException(msg);
1988 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001989 long identityToken = clearCallingIdentity();
1990 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001991 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001992 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001993 } finally {
1994 restoreCallingIdentity(identityToken);
1995 }
Fred Quintana60307342009-03-24 22:48:12 -07001996 }
1997
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001998 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001999 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002000 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002001 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2002 Log.v(TAG, "setUserData: " + account
2003 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002004 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002005 + ", pid " + Binder.getCallingPid());
2006 }
Fred Quintana382601f2010-03-25 12:25:10 -07002007 if (key == null) throw new IllegalArgumentException("key is null");
2008 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002009 int userId = UserHandle.getCallingUserId();
2010 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002011 String msg = String.format(
2012 "uid %s cannot set user data for accounts of type: %s",
2013 callingUid,
2014 account.type);
2015 throw new SecurityException(msg);
2016 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002017 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002018 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002019 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002020 synchronized (accounts.cacheLock) {
2021 if (!accountExistsCacheLocked(accounts, account)) {
2022 return;
2023 }
2024 setUserdataInternalLocked(accounts, account, key, value);
2025 }
Fred Quintana60307342009-03-24 22:48:12 -07002026 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002027 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002028 }
2029 }
2030
Simranjit Kohli858511c2016-03-10 18:36:11 +00002031 private boolean accountExistsCacheLocked(UserAccounts accounts, Account account) {
2032 if (accounts.accountCache.containsKey(account.type)) {
2033 for (Account acc : accounts.accountCache.get(account.type)) {
2034 if (acc.name.equals(account.name)) {
2035 return true;
2036 }
2037 }
2038 }
2039 return false;
2040 }
2041
2042 private void setUserdataInternalLocked(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002043 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07002044 if (account == null || key == null) {
2045 return;
2046 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002047 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2048 db.beginTransaction();
2049 try {
2050 long accountId = getAccountIdLocked(db, account);
2051 if (accountId < 0) {
2052 return;
2053 }
2054 long extrasId = getExtrasIdLocked(db, accountId, key);
2055 if (extrasId < 0) {
2056 extrasId = insertExtraLocked(db, accountId, key, value);
2057 if (extrasId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002058 return;
2059 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002060 } else {
2061 ContentValues values = new ContentValues();
2062 values.put(EXTRAS_VALUE, value);
2063 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
2064 return;
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00002065 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002066 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002067 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
2068 db.setTransactionSuccessful();
2069 } finally {
2070 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002071 }
2072 }
2073
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002074 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002075 if (result == null) {
2076 Log.e(TAG, "the result is unexpectedly null", new Exception());
2077 }
2078 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2079 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2080 + response);
2081 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002082 try {
2083 response.onResult(result);
2084 } catch (RemoteException e) {
2085 // if the caller is dead then there is no one to care about remote
2086 // exceptions
2087 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2088 Log.v(TAG, "failure while notifying response", e);
2089 }
2090 }
2091 }
2092
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002093 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002094 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2095 final String authTokenType)
2096 throws RemoteException {
2097 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002098 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2099
Fred Quintanad9640ec2012-05-23 12:37:00 -07002100 final int callingUid = getCallingUid();
2101 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07002102 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002103 throw new SecurityException("can only call from system");
2104 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002105 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002106 long identityToken = clearCallingIdentity();
2107 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002108 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002109 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2110 false /* stripAuthTokenFromResult */, null /* accountName */,
2111 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002112 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002113 protected String toDebugString(long now) {
2114 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002115 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002116 + ", authTokenType " + authTokenType;
2117 }
2118
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002119 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002120 public void run() throws RemoteException {
2121 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2122 }
2123
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002124 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002125 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002126 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002127 if (result != null) {
2128 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2129 Bundle bundle = new Bundle();
2130 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2131 super.onResult(bundle);
2132 return;
2133 } else {
2134 super.onResult(result);
2135 }
2136 }
2137 }.bind();
2138 } finally {
2139 restoreCallingIdentity(identityToken);
2140 }
2141 }
2142
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002143 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002144 public void getAuthToken(
2145 IAccountManagerResponse response,
2146 final Account account,
2147 final String authTokenType,
2148 final boolean notifyOnAuthFailure,
2149 final boolean expectActivityLaunch,
2150 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002151 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002152 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2153 Log.v(TAG, "getAuthToken: " + account
2154 + ", response " + response
2155 + ", authTokenType " + authTokenType
2156 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2157 + ", expectActivityLaunch " + expectActivityLaunch
2158 + ", caller's uid " + Binder.getCallingUid()
2159 + ", pid " + Binder.getCallingPid());
2160 }
Fred Quintana382601f2010-03-25 12:25:10 -07002161 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002162 try {
2163 if (account == null) {
2164 Slog.w(TAG, "getAuthToken called with null account");
2165 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2166 return;
2167 }
2168 if (authTokenType == null) {
2169 Slog.w(TAG, "getAuthToken called with null authTokenType");
2170 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2171 return;
2172 }
2173 } catch (RemoteException e) {
2174 Slog.w(TAG, "Failed to report error back to the client." + e);
2175 return;
2176 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002177 int userId = UserHandle.getCallingUserId();
2178 long ident = Binder.clearCallingIdentity();
2179 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002180 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002181 try {
2182 accounts = getUserAccounts(userId);
2183 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2184 AuthenticatorDescription.newKey(account.type), accounts.userId);
2185 } finally {
2186 Binder.restoreCallingIdentity(ident);
2187 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002188
Costin Manolachea40c6302010-12-13 14:50:45 -08002189 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002190 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002191
2192 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002193 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002194 final boolean permissionGranted =
2195 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002196
Carlos Valdivia91979be2015-05-22 14:11:35 -07002197 // Get the calling package. We will use it for the purpose of caching.
2198 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002199 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002200 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002201 try {
2202 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2203 } finally {
2204 Binder.restoreCallingIdentity(ident);
2205 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002206 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2207 String msg = String.format(
2208 "Uid %s is attempting to illegally masquerade as package %s!",
2209 callerUid,
2210 callerPkg);
2211 throw new SecurityException(msg);
2212 }
2213
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002214 // let authenticator know the identity of the caller
2215 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2216 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002217
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002218 if (notifyOnAuthFailure) {
2219 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002220 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002221
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002222 long identityToken = clearCallingIdentity();
2223 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002224 // Distill the caller's package signatures into a single digest.
2225 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2226
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002227 // if the caller has permission, do the peek. otherwise go the more expensive
2228 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002229 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002230 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002231 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002232 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002233 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2234 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2235 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002236 onResult(response, result);
2237 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002238 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002239 }
2240
Carlos Valdivia91979be2015-05-22 14:11:35 -07002241 if (customTokens) {
2242 /*
2243 * Look up tokens in the new cache only if the loginOptions don't have parameters
2244 * outside of those expected to be injected by the AccountManager, e.g.
2245 * ANDORID_PACKAGE_NAME.
2246 */
2247 String token = readCachedTokenInternal(
2248 accounts,
2249 account,
2250 authTokenType,
2251 callerPkg,
2252 callerPkgSigDigest);
2253 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002254 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2255 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2256 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002257 Bundle result = new Bundle();
2258 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2259 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2260 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2261 onResult(response, result);
2262 return;
2263 }
2264 }
2265
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002266 new Session(
2267 accounts,
2268 response,
2269 account.type,
2270 expectActivityLaunch,
2271 false /* stripAuthTokenFromResult */,
2272 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002273 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002274 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002275 protected String toDebugString(long now) {
2276 if (loginOptions != null) loginOptions.keySet();
2277 return super.toDebugString(now) + ", getAuthToken"
2278 + ", " + account
2279 + ", authTokenType " + authTokenType
2280 + ", loginOptions " + loginOptions
2281 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2282 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002283
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002284 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002285 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002286 // If the caller doesn't have permission then create and return the
2287 // "grant permission" intent instead of the "getAuthToken" intent.
2288 if (!permissionGranted) {
2289 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2290 } else {
2291 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2292 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002293 }
2294
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002295 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002296 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002297 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002298 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002299 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002300 Intent intent = newGrantCredentialsPermissionIntent(
2301 account,
2302 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002303 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002304 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002305 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002306 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002307 onResult(bundle);
2308 return;
2309 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002310 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002311 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002312 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2313 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002314 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002315 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002316 "the type and name should not be empty");
2317 return;
2318 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002319 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002320 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002321 saveAuthTokenToDatabase(
2322 mAccounts,
2323 resultAccount,
2324 authTokenType,
2325 authToken);
2326 }
2327 long expiryMillis = result.getLong(
2328 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2329 if (customTokens
2330 && expiryMillis > System.currentTimeMillis()) {
2331 saveCachedToken(
2332 mAccounts,
2333 account,
2334 callerPkg,
2335 callerPkgSigDigest,
2336 authTokenType,
2337 authToken,
2338 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002339 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002340 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002341
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002342 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002343 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002344 /*
2345 * Make sure that the supplied intent is owned by the authenticator
2346 * giving it to the system. Otherwise a malicious authenticator could
2347 * have users launching arbitrary activities by tricking users to
2348 * interact with malicious notifications.
2349 */
2350 checkKeyIntent(
2351 Binder.getCallingUid(),
2352 intent);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002353 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002354 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002355 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002356 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002357 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002358 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002359 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002360 }.bind();
2361 } finally {
2362 restoreCallingIdentity(identityToken);
2363 }
Fred Quintana60307342009-03-24 22:48:12 -07002364 }
2365
Carlos Valdivia91979be2015-05-22 14:11:35 -07002366 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2367 MessageDigest digester;
2368 try {
2369 digester = MessageDigest.getInstance("SHA-256");
2370 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2371 callerPkg, PackageManager.GET_SIGNATURES);
2372 for (Signature sig : pkgInfo.signatures) {
2373 digester.update(sig.toByteArray());
2374 }
2375 } catch (NoSuchAlgorithmException x) {
2376 Log.wtf(TAG, "SHA-256 should be available", x);
2377 digester = null;
2378 } catch (NameNotFoundException e) {
2379 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2380 digester = null;
2381 }
2382 return (digester == null) ? null : digester.digest();
2383 }
2384
Dianne Hackborn41203752012-08-31 14:05:51 -07002385 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2386 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002387 int uid = intent.getIntExtra(
2388 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2389 String authTokenType = intent.getStringExtra(
2390 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002391 final String titleAndSubtitle =
2392 mContext.getString(R.string.permission_request_notification_with_subtitle,
2393 account.name);
2394 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002395 String title = titleAndSubtitle;
2396 String subtitle = "";
2397 if (index > 0) {
2398 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002399 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002400 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002401 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002402 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002403 Notification n = new Notification.Builder(contextForUser)
2404 .setSmallIcon(android.R.drawable.stat_sys_warning)
2405 .setWhen(0)
2406 .setColor(contextForUser.getColor(
2407 com.android.internal.R.color.system_notification_accent_color))
2408 .setContentTitle(title)
2409 .setContentText(subtitle)
2410 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2411 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2412 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002413 installNotification(getCredentialPermissionNotificationId(
2414 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002415 }
2416
Costin Manolache5f383ad92010-12-02 16:44:46 -08002417 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002418 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002419
2420 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002421 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002422 // Since it was set in Eclair+ we can't change it without breaking apps using
2423 // the intent from a non-Activity context.
2424 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002425 intent.addCategory(
2426 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002427
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002428 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002429 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2430 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002431 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002432
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002433 return intent;
2434 }
2435
2436 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2437 int uid) {
2438 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002439 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002440 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002441 final Pair<Pair<Account, String>, Integer> key =
2442 new Pair<Pair<Account, String>, Integer>(
2443 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002444 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002445 if (id == null) {
2446 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002447 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002448 }
2449 }
2450 return id;
2451 }
2452
Amith Yamasani04e0d262012-02-14 11:50:53 -08002453 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002454 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002455 synchronized (accounts.signinRequiredNotificationIds) {
2456 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002457 if (id == null) {
2458 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002459 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002460 }
2461 }
2462 return id;
2463 }
2464
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002465 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002466 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002467 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002468 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002469 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002470 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2471 Log.v(TAG, "addAccount: accountType " + accountType
2472 + ", response " + response
2473 + ", authTokenType " + authTokenType
2474 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2475 + ", expectActivityLaunch " + expectActivityLaunch
2476 + ", caller's uid " + Binder.getCallingUid()
2477 + ", pid " + Binder.getCallingPid());
2478 }
Fred Quintana382601f2010-03-25 12:25:10 -07002479 if (response == null) throw new IllegalArgumentException("response is null");
2480 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002481
Amith Yamasani71e6c692013-03-24 17:39:28 -07002482 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002483 final int uid = Binder.getCallingUid();
2484 final int userId = UserHandle.getUserId(uid);
2485 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002486 try {
2487 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2488 "User is not allowed to add an account!");
2489 } catch (RemoteException re) {
2490 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002491 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002492 return;
2493 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002494 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002495 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002496 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2497 "User cannot modify accounts of this type (policy).");
2498 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002499 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002500 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2501 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002502 return;
2503 }
2504
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002505 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002506 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2507 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2508 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2509
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002510 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002511 long identityToken = clearCallingIdentity();
2512 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002513 UserAccounts accounts = getUserAccounts(usrId);
2514 logRecordWithUid(
2515 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002516 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002517 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002518 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002519 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002520 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002521 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002522 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002523 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002524
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002525 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002526 protected String toDebugString(long now) {
2527 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002528 + ", accountType " + accountType
2529 + ", requiredFeatures "
2530 + (requiredFeatures != null
2531 ? TextUtils.join(",", requiredFeatures)
2532 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002533 }
2534 }.bind();
2535 } finally {
2536 restoreCallingIdentity(identityToken);
2537 }
Fred Quintana60307342009-03-24 22:48:12 -07002538 }
2539
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002540 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002541 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2542 final String authTokenType, final String[] requiredFeatures,
2543 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002544 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002545 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002546 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2547 Log.v(TAG, "addAccount: accountType " + accountType
2548 + ", response " + response
2549 + ", authTokenType " + authTokenType
2550 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2551 + ", expectActivityLaunch " + expectActivityLaunch
2552 + ", caller's uid " + Binder.getCallingUid()
2553 + ", pid " + Binder.getCallingPid()
2554 + ", for user id " + userId);
2555 }
2556 if (response == null) throw new IllegalArgumentException("response is null");
2557 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002558 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002559 if (isCrossUser(callingUid, userId)) {
2560 throw new SecurityException(
2561 String.format(
2562 "User %s trying to add account for %s" ,
2563 UserHandle.getCallingUserId(),
2564 userId));
2565 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002566
2567 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002568 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002569 try {
2570 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2571 "User is not allowed to add an account!");
2572 } catch (RemoteException re) {
2573 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002574 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002575 return;
2576 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002577 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002578 try {
2579 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2580 "User cannot modify accounts of this type (policy).");
2581 } catch (RemoteException re) {
2582 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002583 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2584 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002585 return;
2586 }
2587
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002588 final int pid = Binder.getCallingPid();
2589 final int uid = Binder.getCallingUid();
2590 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2591 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2592 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2593
2594 long identityToken = clearCallingIdentity();
2595 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002596 UserAccounts accounts = getUserAccounts(userId);
2597 logRecordWithUid(
2598 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002599 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002600 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002601 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002602 @Override
2603 public void run() throws RemoteException {
2604 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2605 options);
2606 }
2607
2608 @Override
2609 protected String toDebugString(long now) {
2610 return super.toDebugString(now) + ", addAccount"
2611 + ", accountType " + accountType
2612 + ", requiredFeatures "
2613 + (requiredFeatures != null
2614 ? TextUtils.join(",", requiredFeatures)
2615 : null);
2616 }
2617 }.bind();
2618 } finally {
2619 restoreCallingIdentity(identityToken);
2620 }
2621 }
2622
Sandra Kwan78812282015-11-04 11:19:47 -08002623 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002624 public void startAddAccountSession(
2625 final IAccountManagerResponse response,
2626 final String accountType,
2627 final String authTokenType,
2628 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002629 final boolean expectActivityLaunch,
2630 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002631 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002632 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2633 Log.v(TAG,
2634 "startAddAccountSession: accountType " + accountType
2635 + ", response " + response
2636 + ", authTokenType " + authTokenType
2637 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2638 + ", expectActivityLaunch " + expectActivityLaunch
2639 + ", caller's uid " + Binder.getCallingUid()
2640 + ", pid " + Binder.getCallingPid());
2641 }
2642 if (response == null) {
2643 throw new IllegalArgumentException("response is null");
2644 }
2645 if (accountType == null) {
2646 throw new IllegalArgumentException("accountType is null");
2647 }
2648
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002649 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002650 // Only allow system to start session
2651 if (!isSystemUid(uid)) {
2652 String msg = String.format(
2653 "uid %s cannot stat add account session.",
2654 uid);
2655 throw new SecurityException(msg);
2656 }
2657
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002658 final int userId = UserHandle.getUserId(uid);
2659 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002660 try {
2661 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2662 "User is not allowed to add an account!");
2663 } catch (RemoteException re) {
2664 }
2665 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2666 return;
2667 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002668 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002669 try {
2670 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2671 "User cannot modify accounts of this type (policy).");
2672 } catch (RemoteException re) {
2673 }
2674 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2675 userId);
2676 return;
2677 }
Sandra Kwan78812282015-11-04 11:19:47 -08002678 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08002679 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2680 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2681 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2682
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002683 // Check to see if the Password should be included to the caller.
2684 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2685 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07002686 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002687
Sandra Kwan78812282015-11-04 11:19:47 -08002688 int usrId = UserHandle.getCallingUserId();
2689 long identityToken = clearCallingIdentity();
2690 try {
2691 UserAccounts accounts = getUserAccounts(usrId);
2692 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2693 TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002694 new StartAccountSession(
2695 accounts,
2696 response,
2697 accountType,
2698 expectActivityLaunch,
2699 null /* accountName */,
2700 false /* authDetailsRequired */,
2701 true /* updateLastAuthenticationTime */,
2702 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002703 @Override
2704 public void run() throws RemoteException {
2705 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2706 requiredFeatures, options);
2707 }
2708
2709 @Override
2710 protected String toDebugString(long now) {
2711 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2712 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2713 + accountType + ", requiredFeatures "
2714 + (requiredFeatures != null ? requiredFeaturesStr : null);
2715 }
2716 }.bind();
2717 } finally {
2718 restoreCallingIdentity(identityToken);
2719 }
2720 }
2721
2722 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2723 private abstract class StartAccountSession extends Session {
2724
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002725 private final boolean mIsPasswordForwardingAllowed;
2726
2727 public StartAccountSession(
2728 UserAccounts accounts,
2729 IAccountManagerResponse response,
2730 String accountType,
2731 boolean expectActivityLaunch,
2732 String accountName,
2733 boolean authDetailsRequired,
2734 boolean updateLastAuthenticationTime,
2735 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002736 super(accounts, response, accountType, expectActivityLaunch,
2737 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2738 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002739 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08002740 }
2741
2742 @Override
2743 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002744 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002745 mNumResults++;
2746 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08002747 if (result != null
2748 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08002749 checkKeyIntent(
2750 Binder.getCallingUid(),
2751 intent);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002752 // Omit passwords if the caller isn't permitted to see them.
2753 if (!mIsPasswordForwardingAllowed) {
2754 result.remove(AccountManager.KEY_PASSWORD);
2755 }
Sandra Kwan78812282015-11-04 11:19:47 -08002756 }
Sandra Kwan78812282015-11-04 11:19:47 -08002757 IAccountManagerResponse response;
2758 if (mExpectActivityLaunch && result != null
2759 && result.containsKey(AccountManager.KEY_INTENT)) {
2760 response = mResponse;
2761 } else {
2762 response = getResponseAndClose();
2763 }
2764 if (response == null) {
2765 return;
2766 }
2767 if (result == null) {
2768 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2769 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2770 + response);
2771 }
2772 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2773 "null bundle returned");
2774 return;
2775 }
2776
2777 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2778 // All AccountManager error codes are greater
2779 // than 0
2780 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2781 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2782 return;
2783 }
2784
2785 // Strip auth token from result.
2786 result.remove(AccountManager.KEY_AUTHTOKEN);
2787
2788 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2789 Log.v(TAG,
2790 getClass().getSimpleName() + " calling onResult() on response " + response);
2791 }
2792
2793 // Get the session bundle created by authenticator. The
2794 // bundle contains data necessary for finishing the session
2795 // later. The session bundle will be encrypted here and
2796 // decrypted later when trying to finish the session.
2797 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2798 if (sessionBundle != null) {
2799 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2800 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08002801 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002802 Log.w(TAG, "Account type in session bundle doesn't match request.");
2803 }
2804 // Add accountType info to session bundle. This will
2805 // override any value set by authenticator.
2806 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2807
2808 // Encrypt session bundle before returning to caller.
2809 try {
2810 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2811 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2812 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2813 } catch (GeneralSecurityException e) {
2814 if (Log.isLoggable(TAG, Log.DEBUG)) {
2815 Log.v(TAG, "Failed to encrypt session bundle!", e);
2816 }
2817 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2818 "failed to encrypt session bundle");
2819 return;
2820 }
2821 }
2822
2823 sendResponse(response, result);
2824 }
2825 }
2826
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002827 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08002828 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002829 @NonNull Bundle sessionBundle,
2830 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002831 Bundle appInfo,
2832 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002833 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08002834 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002835 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2836 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002837 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002838 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08002839 + ", caller's uid " + callingUid
2840 + ", caller's user id " + UserHandle.getCallingUserId()
2841 + ", pid " + Binder.getCallingPid()
2842 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002843 }
2844 if (response == null) {
2845 throw new IllegalArgumentException("response is null");
2846 }
2847
2848 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2849 // Account type is added to it before encryption.
2850 if (sessionBundle == null || sessionBundle.size() == 0) {
2851 throw new IllegalArgumentException("sessionBundle is empty");
2852 }
2853
Sandra Kwan0b84b452016-01-20 15:25:42 -08002854 // Only allow the system process to finish session for other users
2855 if (isCrossUser(callingUid, userId)) {
2856 throw new SecurityException(
2857 String.format(
2858 "User %s trying to finish session for %s without cross user permission",
2859 UserHandle.getCallingUserId(),
2860 userId));
2861 }
2862
Sandra Kwana578d112015-12-16 16:01:43 -08002863 // Only allow system to finish session
Sandra Kwan0b84b452016-01-20 15:25:42 -08002864 if (!isSystemUid(callingUid)) {
Sandra Kwana578d112015-12-16 16:01:43 -08002865 String msg = String.format(
Sandra Kwan0b84b452016-01-20 15:25:42 -08002866 "uid %s cannot finish session because it's not system uid.",
2867 callingUid);
Sandra Kwana578d112015-12-16 16:01:43 -08002868 throw new SecurityException(msg);
2869 }
2870
Sandra Kwan0b84b452016-01-20 15:25:42 -08002871 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002872 sendErrorResponse(response,
2873 AccountManager.ERROR_CODE_USER_RESTRICTED,
2874 "User is not allowed to add an account!");
2875 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2876 return;
2877 }
2878
2879 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002880 final Bundle decryptedBundle;
2881 final String accountType;
2882 // First decrypt session bundle to get account type for checking permission.
2883 try {
2884 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2885 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2886 if (decryptedBundle == null) {
2887 sendErrorResponse(
2888 response,
2889 AccountManager.ERROR_CODE_BAD_REQUEST,
2890 "failed to decrypt session bundle");
2891 return;
2892 }
2893 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2894 // Account type cannot be null. This should not happen if session bundle was created
2895 // properly by #StartAccountSession.
2896 if (TextUtils.isEmpty(accountType)) {
2897 sendErrorResponse(
2898 response,
2899 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2900 "accountType is empty");
2901 return;
2902 }
2903
2904 // If by any chances, decryptedBundle contains colliding keys with
2905 // system info
2906 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2907 // update credentials flow, we should replace with the new values of the current call.
2908 if (appInfo != null) {
2909 decryptedBundle.putAll(appInfo);
2910 }
2911
2912 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08002913 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002914 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2915 } catch (GeneralSecurityException e) {
2916 if (Log.isLoggable(TAG, Log.DEBUG)) {
2917 Log.v(TAG, "Failed to decrypt session bundle!", e);
2918 }
2919 sendErrorResponse(
2920 response,
2921 AccountManager.ERROR_CODE_BAD_REQUEST,
2922 "failed to decrypt session bundle");
2923 return;
2924 }
2925
Sandra Kwan0b84b452016-01-20 15:25:42 -08002926 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002927 sendErrorResponse(
2928 response,
2929 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2930 "User cannot modify accounts of this type (policy).");
2931 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2932 userId);
2933 return;
2934 }
2935
2936 long identityToken = clearCallingIdentity();
2937 try {
2938 UserAccounts accounts = getUserAccounts(userId);
2939 logRecordWithUid(
2940 accounts,
2941 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2942 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002943 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002944 new Session(
2945 accounts,
2946 response,
2947 accountType,
2948 expectActivityLaunch,
2949 true /* stripAuthTokenFromResult */,
2950 null /* accountName */,
2951 false /* authDetailsRequired */,
2952 true /* updateLastAuthenticationTime */) {
2953 @Override
2954 public void run() throws RemoteException {
2955 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2956 }
2957
2958 @Override
2959 protected String toDebugString(long now) {
2960 return super.toDebugString(now)
2961 + ", finishSession"
2962 + ", accountType " + accountType;
2963 }
2964 }.bind();
2965 } finally {
2966 restoreCallingIdentity(identityToken);
2967 }
2968 }
2969
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002970 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002971 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2972 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2973 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2974 long identityToken = clearCallingIdentity();
2975 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002976 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002977 } finally {
2978 restoreCallingIdentity(identityToken);
2979 }
2980 }
2981
2982 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002983 public void confirmCredentialsAsUser(
2984 IAccountManagerResponse response,
2985 final Account account,
2986 final Bundle options,
2987 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002988 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002989 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002990 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002991 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2992 Log.v(TAG, "confirmCredentials: " + account
2993 + ", response " + response
2994 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002995 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002996 + ", pid " + Binder.getCallingPid());
2997 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002998 // Only allow the system process to read accounts of other users
2999 if (isCrossUser(callingUid, userId)) {
3000 throw new SecurityException(
3001 String.format(
3002 "User %s trying to confirm account credentials for %s" ,
3003 UserHandle.getCallingUserId(),
3004 userId));
3005 }
Fred Quintana382601f2010-03-25 12:25:10 -07003006 if (response == null) throw new IllegalArgumentException("response is null");
3007 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003008 long identityToken = clearCallingIdentity();
3009 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003010 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003011 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003012 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003013 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003014 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003015 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003016 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003017 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003018 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003019 protected String toDebugString(long now) {
3020 return super.toDebugString(now) + ", confirmCredentials"
3021 + ", " + account;
3022 }
3023 }.bind();
3024 } finally {
3025 restoreCallingIdentity(identityToken);
3026 }
Fred Quintana60307342009-03-24 22:48:12 -07003027 }
3028
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003029 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003030 public void updateCredentials(IAccountManagerResponse response, final Account account,
3031 final String authTokenType, final boolean expectActivityLaunch,
3032 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003033 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003034 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3035 Log.v(TAG, "updateCredentials: " + account
3036 + ", response " + response
3037 + ", authTokenType " + authTokenType
3038 + ", expectActivityLaunch " + expectActivityLaunch
3039 + ", caller's uid " + Binder.getCallingUid()
3040 + ", pid " + Binder.getCallingPid());
3041 }
Fred Quintana382601f2010-03-25 12:25:10 -07003042 if (response == null) throw new IllegalArgumentException("response is null");
3043 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003044 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003045 long identityToken = clearCallingIdentity();
3046 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003047 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003048 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003049 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003050 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003051 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003052 public void run() throws RemoteException {
3053 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3054 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003055 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003056 protected String toDebugString(long now) {
3057 if (loginOptions != null) loginOptions.keySet();
3058 return super.toDebugString(now) + ", updateCredentials"
3059 + ", " + account
3060 + ", authTokenType " + authTokenType
3061 + ", loginOptions " + loginOptions;
3062 }
3063 }.bind();
3064 } finally {
3065 restoreCallingIdentity(identityToken);
3066 }
Fred Quintana60307342009-03-24 22:48:12 -07003067 }
3068
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003069 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003070 public void startUpdateCredentialsSession(
3071 IAccountManagerResponse response,
3072 final Account account,
3073 final String authTokenType,
3074 final boolean expectActivityLaunch,
3075 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003076 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003077 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3078 Log.v(TAG,
3079 "startUpdateCredentialsSession: " + account + ", response " + response
3080 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3081 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3082 + ", pid " + Binder.getCallingPid());
3083 }
3084 if (response == null) {
3085 throw new IllegalArgumentException("response is null");
3086 }
3087 if (account == null) {
3088 throw new IllegalArgumentException("account is null");
3089 }
Sandra Kwana578d112015-12-16 16:01:43 -08003090
3091 final int uid = Binder.getCallingUid();
3092 // Only allow system to start session
3093 if (!isSystemUid(uid)) {
3094 String msg = String.format(
3095 "uid %s cannot start update credentials session.",
3096 uid);
3097 throw new SecurityException(msg);
3098 }
3099
Sandra Kwane68c37e2015-11-12 17:11:49 -08003100 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003101
3102 // Check to see if the Password should be included to the caller.
3103 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3104 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003105 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003106
Sandra Kwane68c37e2015-11-12 17:11:49 -08003107 long identityToken = clearCallingIdentity();
3108 try {
3109 UserAccounts accounts = getUserAccounts(userId);
3110 new StartAccountSession(
3111 accounts,
3112 response,
3113 account.type,
3114 expectActivityLaunch,
3115 account.name,
3116 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003117 true /* updateLastCredentialTime */,
3118 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003119 @Override
3120 public void run() throws RemoteException {
3121 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3122 loginOptions);
3123 }
3124
3125 @Override
3126 protected String toDebugString(long now) {
3127 if (loginOptions != null)
3128 loginOptions.keySet();
3129 return super.toDebugString(now)
3130 + ", startUpdateCredentialsSession"
3131 + ", " + account
3132 + ", authTokenType " + authTokenType
3133 + ", loginOptions " + loginOptions;
3134 }
3135 }.bind();
3136 } finally {
3137 restoreCallingIdentity(identityToken);
3138 }
3139 }
3140
3141 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003142 public void isCredentialsUpdateSuggested(
3143 IAccountManagerResponse response,
3144 final Account account,
3145 final String statusToken) {
3146 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3147 Log.v(TAG,
3148 "isCredentialsUpdateSuggested: " + account + ", response " + response
3149 + ", caller's uid " + Binder.getCallingUid()
3150 + ", pid " + Binder.getCallingPid());
3151 }
3152 if (response == null) {
3153 throw new IllegalArgumentException("response is null");
3154 }
3155 if (account == null) {
3156 throw new IllegalArgumentException("account is null");
3157 }
3158 if (TextUtils.isEmpty(statusToken)) {
3159 throw new IllegalArgumentException("status token is empty");
3160 }
3161
3162 int uid = Binder.getCallingUid();
3163 // Only allow system to start session
3164 if (!isSystemUid(uid)) {
3165 String msg = String.format(
3166 "uid %s cannot stat add account session.",
3167 uid);
3168 throw new SecurityException(msg);
3169 }
3170
3171 int usrId = UserHandle.getCallingUserId();
3172 long identityToken = clearCallingIdentity();
3173 try {
3174 UserAccounts accounts = getUserAccounts(usrId);
3175 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3176 false /* stripAuthTokenFromResult */, account.name,
3177 false /* authDetailsRequired */) {
3178 @Override
3179 protected String toDebugString(long now) {
3180 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3181 + ", " + account;
3182 }
3183
3184 @Override
3185 public void run() throws RemoteException {
3186 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3187 }
3188
3189 @Override
3190 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003191 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003192 IAccountManagerResponse response = getResponseAndClose();
3193 if (response == null) {
3194 return;
3195 }
3196
3197 if (result == null) {
3198 sendErrorResponse(
3199 response,
3200 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3201 "null bundle");
3202 return;
3203 }
3204
3205 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3206 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3207 + response);
3208 }
3209 // Check to see if an error occurred. We know if an error occurred because all
3210 // error codes are greater than 0.
3211 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3212 sendErrorResponse(response,
3213 result.getInt(AccountManager.KEY_ERROR_CODE),
3214 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3215 return;
3216 }
3217 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3218 sendErrorResponse(
3219 response,
3220 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3221 "no result in response");
3222 return;
3223 }
3224 final Bundle newResult = new Bundle();
3225 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3226 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3227 sendResponse(response, newResult);
3228 }
3229 }.bind();
3230 } finally {
3231 restoreCallingIdentity(identityToken);
3232 }
3233 }
3234
3235 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003236 public void editProperties(IAccountManagerResponse response, final String accountType,
3237 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003238 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003239 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3240 Log.v(TAG, "editProperties: accountType " + accountType
3241 + ", response " + response
3242 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003243 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003244 + ", pid " + Binder.getCallingPid());
3245 }
Fred Quintana382601f2010-03-25 12:25:10 -07003246 if (response == null) throw new IllegalArgumentException("response is null");
3247 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003248 int userId = UserHandle.getCallingUserId();
3249 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003250 String msg = String.format(
3251 "uid %s cannot edit authenticator properites for account type: %s",
3252 callingUid,
3253 accountType);
3254 throw new SecurityException(msg);
3255 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003256 long identityToken = clearCallingIdentity();
3257 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003258 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003259 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003260 true /* stripAuthTokenFromResult */, null /* accountName */,
3261 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003262 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003263 public void run() throws RemoteException {
3264 mAuthenticator.editProperties(this, mAccountType);
3265 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003266 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003267 protected String toDebugString(long now) {
3268 return super.toDebugString(now) + ", editProperties"
3269 + ", accountType " + accountType;
3270 }
3271 }.bind();
3272 } finally {
3273 restoreCallingIdentity(identityToken);
3274 }
Fred Quintana60307342009-03-24 22:48:12 -07003275 }
3276
Amith Yamasani12747872015-12-07 14:19:49 -08003277 @Override
3278 public boolean someUserHasAccount(@NonNull final Account account) {
3279 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3280 throw new SecurityException("Only system can check for accounts across users");
3281 }
3282 final long token = Binder.clearCallingIdentity();
3283 try {
3284 AccountAndUser[] allAccounts = getAllAccounts();
3285 for (int i = allAccounts.length - 1; i >= 0; i--) {
3286 if (allAccounts[i].account.equals(account)) {
3287 return true;
3288 }
3289 }
3290 return false;
3291 } finally {
3292 Binder.restoreCallingIdentity(token);
3293 }
3294 }
3295
Fred Quintana33269202009-04-20 16:05:10 -07003296 private class GetAccountsByTypeAndFeatureSession extends Session {
3297 private final String[] mFeatures;
3298 private volatile Account[] mAccountsOfType = null;
3299 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3300 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003301 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003302
Amith Yamasani04e0d262012-02-14 11:50:53 -08003303 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003304 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003305 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003306 true /* stripAuthTokenFromResult */, null /* accountName */,
3307 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003308 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003309 mFeatures = features;
3310 }
3311
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003312 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003313 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003314 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003315 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3316 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003317 }
Fred Quintana33269202009-04-20 16:05:10 -07003318 // check whether each account matches the requested features
3319 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
3320 mCurrentAccount = 0;
3321
3322 checkAccount();
3323 }
3324
3325 public void checkAccount() {
3326 if (mCurrentAccount >= mAccountsOfType.length) {
3327 sendResult();
3328 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003329 }
Fred Quintana33269202009-04-20 16:05:10 -07003330
Fred Quintana29e94b82010-03-10 12:11:51 -08003331 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3332 if (accountAuthenticator == null) {
3333 // It is possible that the authenticator has died, which is indicated by
3334 // mAuthenticator being set to null. If this happens then just abort.
3335 // There is no need to send back a result or error in this case since
3336 // that already happened when mAuthenticator was cleared.
3337 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3338 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3339 + " connected to the authenticator, " + toDebugString());
3340 }
3341 return;
3342 }
Fred Quintana33269202009-04-20 16:05:10 -07003343 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003344 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003345 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003346 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003347 }
3348 }
3349
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003350 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003351 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003352 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003353 mNumResults++;
3354 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003355 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003356 return;
3357 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003358 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003359 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3360 }
3361 mCurrentAccount++;
3362 checkAccount();
3363 }
3364
3365 public void sendResult() {
3366 IAccountManagerResponse response = getResponseAndClose();
3367 if (response != null) {
3368 try {
3369 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3370 for (int i = 0; i < accounts.length; i++) {
3371 accounts[i] = mAccountsWithFeatures.get(i);
3372 }
Fred Quintana56285a62010-12-02 14:20:51 -08003373 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3374 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3375 + response);
3376 }
Fred Quintana33269202009-04-20 16:05:10 -07003377 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003378 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003379 response.onResult(result);
3380 } catch (RemoteException e) {
3381 // if the caller is dead then there is no one to care about remote exceptions
3382 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3383 Log.v(TAG, "failure while notifying response", e);
3384 }
3385 }
3386 }
3387 }
3388
3389
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003390 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003391 protected String toDebugString(long now) {
3392 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3393 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3394 }
3395 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003396
Amith Yamasani04e0d262012-02-14 11:50:53 -08003397 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003398 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003399 * @hide
3400 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003401 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003402 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003403 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003404 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3405 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003406 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003407 return new Account[0];
3408 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003409 long identityToken = clearCallingIdentity();
3410 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003411 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003412 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003413 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003414 callingUid,
3415 null, // packageName
3416 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003417 } finally {
3418 restoreCallingIdentity(identityToken);
3419 }
3420 }
3421
Amith Yamasanif29f2362012-04-05 18:29:52 -07003422 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003423 * Returns accounts for all running users.
3424 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003425 * @hide
3426 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003427 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003428 public AccountAndUser[] getRunningAccounts() {
3429 final int[] runningUserIds;
3430 try {
3431 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3432 } catch (RemoteException e) {
3433 // Running in system_server; should never happen
3434 throw new RuntimeException(e);
3435 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003436 return getAccounts(runningUserIds);
3437 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003438
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003439 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003440 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003441 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003442 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003443 final int[] userIds = new int[users.size()];
3444 for (int i = 0; i < userIds.length; i++) {
3445 userIds[i] = users.get(i).id;
3446 }
3447 return getAccounts(userIds);
3448 }
3449
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003450 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003451 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003452 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003453 for (int userId : userIds) {
3454 UserAccounts userAccounts = getUserAccounts(userId);
3455 if (userAccounts == null) continue;
3456 synchronized (userAccounts.cacheLock) {
3457 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3458 Binder.getCallingUid(), null);
3459 for (int a = 0; a < accounts.length; a++) {
3460 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003461 }
3462 }
3463 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003464
3465 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3466 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003467 }
3468
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003469 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003470 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003471 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3472 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003473 }
3474
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003475 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003476 private Account[] getAccountsAsUser(
3477 String type,
3478 int userId,
3479 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003480 int packageUid,
3481 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003482 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003483 // Only allow the system process to read accounts of other users
3484 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003485 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003486 && mContext.checkCallingOrSelfPermission(
3487 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3488 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003489 throw new SecurityException("User " + UserHandle.getCallingUserId()
3490 + " trying to get account for " + userId);
3491 }
3492
Fred Quintana56285a62010-12-02 14:20:51 -08003493 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3494 Log.v(TAG, "getAccounts: accountType " + type
3495 + ", caller's uid " + Binder.getCallingUid()
3496 + ", pid " + Binder.getCallingPid());
3497 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003498 // If the original calling app was using the framework account chooser activity, we'll
3499 // be passed in the original caller's uid here, which is what should be used for filtering.
3500 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3501 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003502 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003503 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003504
Svetoslavf3f02ac2015-09-08 14:36:35 -07003505 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3506 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003507 if (visibleAccountTypes.isEmpty()
3508 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003509 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003510 } else if (visibleAccountTypes.contains(type)) {
3511 // Prune the list down to just the requested type.
3512 visibleAccountTypes = new ArrayList<>();
3513 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003514 } // else aggregate all the visible accounts (it won't matter if the
3515 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003516
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003517 long identityToken = clearCallingIdentity();
3518 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003519 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003520 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003521 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003522 callingUid,
3523 callingPackage,
3524 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003525 } finally {
3526 restoreCallingIdentity(identityToken);
3527 }
3528 }
3529
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003530 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003531 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003532 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003533 int callingUid,
3534 String callingPackage,
3535 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003536 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003537 ArrayList<Account> visibleAccounts = new ArrayList<>();
3538 for (String visibleType : visibleAccountTypes) {
3539 Account[] accountsForType = getAccountsFromCacheLocked(
3540 userAccounts, visibleType, callingUid, callingPackage);
3541 if (accountsForType != null) {
3542 visibleAccounts.addAll(Arrays.asList(accountsForType));
3543 }
3544 }
3545 Account[] result = new Account[visibleAccounts.size()];
3546 for (int i = 0; i < visibleAccounts.size(); i++) {
3547 result[i] = visibleAccounts.get(i);
3548 }
3549 return result;
3550 }
3551 }
3552
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003553 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003554 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07003555 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003556 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3557 for (Account account : accounts) {
3558 addSharedAccountAsUser(account, userId);
3559 }
3560 }
3561
3562 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003563 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003564 UserAccounts accounts = getUserAccounts(userId);
3565 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003566 ContentValues values = new ContentValues();
3567 values.put(ACCOUNTS_NAME, account.name);
3568 values.put(ACCOUNTS_TYPE, account.type);
3569 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3570 new String[] {account.name, account.type});
3571 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3572 if (accountId < 0) {
3573 Log.w(TAG, "insertAccountIntoDatabase: " + account
3574 + ", skipping the DB insert failed");
3575 return false;
3576 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003577 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003578 return true;
3579 }
3580
3581 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003582 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3583 userId = handleIncomingUser(userId);
3584 UserAccounts accounts = getUserAccounts(userId);
3585 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003586 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003587 final ContentValues values = new ContentValues();
3588 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003589 int r = db.update(
3590 TABLE_SHARED_ACCOUNTS,
3591 values,
3592 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3593 new String[] { account.name, account.type });
3594 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003595 int callingUid = getCallingUid();
3596 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3597 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003598 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003599 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003600 }
3601 return r > 0;
3602 }
3603
3604 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003605 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003606 return removeSharedAccountAsUser(account, userId, getCallingUid());
3607 }
3608
3609 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003610 userId = handleIncomingUser(userId);
3611 UserAccounts accounts = getUserAccounts(userId);
3612 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003613 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003614 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3615 new String[] {account.name, account.type});
3616 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003617 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3618 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003619 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003620 }
3621 return r > 0;
3622 }
3623
3624 @Override
3625 public Account[] getSharedAccountsAsUser(int userId) {
3626 userId = handleIncomingUser(userId);
3627 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003628 ArrayList<Account> accountList = new ArrayList<>();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003629 Cursor cursor = null;
3630 try {
3631 cursor = accounts.openHelper.getReadableDatabase()
3632 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3633 null, null, null, null, null);
3634 if (cursor != null && cursor.moveToFirst()) {
3635 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3636 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3637 do {
3638 accountList.add(new Account(cursor.getString(nameIndex),
3639 cursor.getString(typeIndex)));
3640 } while (cursor.moveToNext());
3641 }
3642 } finally {
3643 if (cursor != null) {
3644 cursor.close();
3645 }
3646 }
3647 Account[] accountArray = new Account[accountList.size()];
3648 accountList.toArray(accountArray);
3649 return accountArray;
3650 }
3651
3652 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003653 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003654 public Account[] getAccounts(String type, String opPackageName) {
3655 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003656 }
3657
Amith Yamasani27db4682013-03-30 17:07:47 -07003658 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003659 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003660 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003661 int callingUid = Binder.getCallingUid();
3662 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3663 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3664 + callingUid + " with uid=" + uid);
3665 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003666 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3667 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003668 }
3669
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003670 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003671 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003672 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3673 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003674 int packageUid = -1;
3675 try {
3676 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07003677 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3678 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003679 } catch (RemoteException re) {
3680 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3681 return new Account[0];
3682 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003683 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3684 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003685 }
3686
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003687 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003688 public void getAccountsByFeatures(
3689 IAccountManagerResponse response,
3690 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003691 String[] features,
3692 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003693 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003694 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3695 Log.v(TAG, "getAccounts: accountType " + type
3696 + ", response " + response
3697 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003698 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003699 + ", pid " + Binder.getCallingPid());
3700 }
Fred Quintana382601f2010-03-25 12:25:10 -07003701 if (response == null) throw new IllegalArgumentException("response is null");
3702 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003703 int userId = UserHandle.getCallingUserId();
3704
Svetoslavf3f02ac2015-09-08 14:36:35 -07003705 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3706 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003707 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003708 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003709 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003710 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3711 try {
3712 response.onResult(result);
3713 } catch (RemoteException e) {
3714 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3715 }
3716 return;
3717 }
Fred Quintana33269202009-04-20 16:05:10 -07003718 long identityToken = clearCallingIdentity();
3719 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003720 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003721 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003722 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003723 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003724 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003725 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08003726 Bundle result = new Bundle();
3727 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3728 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003729 return;
3730 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003731 new GetAccountsByTypeAndFeatureSession(
3732 userAccounts,
3733 response,
3734 type,
3735 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003736 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07003737 } finally {
3738 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07003739 }
3740 }
3741
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003742 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3743 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3744 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3745 try {
3746 if (cursor.moveToNext()) {
3747 return cursor.getLong(0);
3748 }
3749 return -1;
3750 } finally {
3751 cursor.close();
3752 }
3753 }
3754
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003755 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07003756 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003757 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07003758 try {
3759 if (cursor.moveToNext()) {
3760 return cursor.getLong(0);
3761 }
3762 return -1;
3763 } finally {
3764 cursor.close();
3765 }
3766 }
3767
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003768 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003769 Cursor cursor = db.query(CE_TABLE_EXTRAS, new String[]{EXTRAS_ID},
Fred Quintana60307342009-03-24 22:48:12 -07003770 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3771 new String[]{key}, null, null, null);
3772 try {
3773 if (cursor.moveToNext()) {
3774 return cursor.getLong(0);
3775 }
3776 return -1;
3777 } finally {
3778 cursor.close();
3779 }
3780 }
3781
Fred Quintanaa698f422009-04-08 19:14:54 -07003782 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07003783 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07003784 IAccountManagerResponse mResponse;
3785 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003786 final boolean mExpectActivityLaunch;
3787 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003788 final String mAccountName;
3789 // Indicates if we need to add auth details(like last credential time)
3790 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003791 // If set, we need to update the last authenticated time. This is
3792 // currently
3793 // used on
3794 // successful confirming credentials.
3795 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07003796
Fred Quintana33269202009-04-20 16:05:10 -07003797 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07003798 private int mNumRequestContinued = 0;
3799 private int mNumErrors = 0;
3800
Fred Quintana60307342009-03-24 22:48:12 -07003801 IAccountAuthenticator mAuthenticator = null;
3802
Fred Quintana8570f742010-02-18 10:32:54 -08003803 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003804 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003805
Amith Yamasani04e0d262012-02-14 11:50:53 -08003806 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003807 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3808 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003809 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3810 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3811 }
3812
3813 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3814 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3815 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07003816 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003817 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07003818 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08003819 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003820 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07003821 mResponse = response;
3822 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003823 mExpectActivityLaunch = expectActivityLaunch;
3824 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003825 mAccountName = accountName;
3826 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003827 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003828
Fred Quintanaa698f422009-04-08 19:14:54 -07003829 synchronized (mSessions) {
3830 mSessions.put(toString(), this);
3831 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003832 if (response != null) {
3833 try {
3834 response.asBinder().linkToDeath(this, 0 /* flags */);
3835 } catch (RemoteException e) {
3836 mResponse = null;
3837 binderDied();
3838 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003839 }
Fred Quintana60307342009-03-24 22:48:12 -07003840 }
3841
Fred Quintanaa698f422009-04-08 19:14:54 -07003842 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07003843 if (mResponse == null) {
3844 // this session has already been closed
3845 return null;
3846 }
Fred Quintana60307342009-03-24 22:48:12 -07003847 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07003848 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07003849 return response;
3850 }
3851
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003852 /**
3853 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
3854 * security policy.
3855 *
3856 * In particular we want to make sure that the Authenticator doesn't try to trick users
3857 * into launching aribtrary intents on the device via by tricking to click authenticator
3858 * supplied entries in the system Settings app.
3859 */
3860 protected void checkKeyIntent(
3861 int authUid,
3862 Intent intent) throws SecurityException {
3863 long bid = Binder.clearCallingIdentity();
3864 try {
3865 PackageManager pm = mContext.getPackageManager();
3866 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3867 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
3868 int targetUid = targetActivityInfo.applicationInfo.uid;
3869 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid)) {
3870 String pkgName = targetActivityInfo.packageName;
3871 String activityName = targetActivityInfo.name;
3872 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
3873 + "does not share a signature with the supplying authenticator (%s).";
3874 throw new SecurityException(
3875 String.format(tmpl, activityName, pkgName, mAccountType));
3876 }
3877 } finally {
3878 Binder.restoreCallingIdentity(bid);
3879 }
3880 }
3881
Fred Quintanaa698f422009-04-08 19:14:54 -07003882 private void close() {
3883 synchronized (mSessions) {
3884 if (mSessions.remove(toString()) == null) {
3885 // the session was already closed, so bail out now
3886 return;
3887 }
3888 }
3889 if (mResponse != null) {
3890 // stop listening for response deaths
3891 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3892
3893 // clear this so that we don't accidentally send any further results
3894 mResponse = null;
3895 }
3896 cancelTimeout();
3897 unbind();
3898 }
3899
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003900 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003901 public void binderDied() {
3902 mResponse = null;
3903 close();
3904 }
3905
3906 protected String toDebugString() {
3907 return toDebugString(SystemClock.elapsedRealtime());
3908 }
3909
3910 protected String toDebugString(long now) {
3911 return "Session: expectLaunch " + mExpectActivityLaunch
3912 + ", connected " + (mAuthenticator != null)
3913 + ", stats (" + mNumResults + "/" + mNumRequestContinued
3914 + "/" + mNumErrors + ")"
3915 + ", lifetime " + ((now - mCreationTime) / 1000.0);
3916 }
3917
Fred Quintana60307342009-03-24 22:48:12 -07003918 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003919 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3920 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3921 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003922 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003923 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003924 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003925 }
3926 }
3927
3928 private void unbind() {
3929 if (mAuthenticator != null) {
3930 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003931 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003932 }
3933 }
3934
Fred Quintana60307342009-03-24 22:48:12 -07003935 public void cancelTimeout() {
3936 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3937 }
3938
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003939 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003940 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003941 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003942 try {
3943 run();
3944 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003945 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003946 "remote exception");
3947 }
Fred Quintana60307342009-03-24 22:48:12 -07003948 }
3949
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003950 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003951 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003952 mAuthenticator = null;
3953 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003954 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003955 try {
3956 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3957 "disconnected");
3958 } catch (RemoteException e) {
3959 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3960 Log.v(TAG, "Session.onServiceDisconnected: "
3961 + "caught RemoteException while responding", e);
3962 }
3963 }
Fred Quintana60307342009-03-24 22:48:12 -07003964 }
3965 }
3966
Fred Quintanab839afc2009-10-14 15:57:28 -07003967 public abstract void run() throws RemoteException;
3968
Fred Quintana60307342009-03-24 22:48:12 -07003969 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003970 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003971 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003972 try {
3973 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3974 "timeout");
3975 } catch (RemoteException e) {
3976 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3977 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3978 e);
3979 }
3980 }
Fred Quintana60307342009-03-24 22:48:12 -07003981 }
3982 }
3983
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003984 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003985 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003986 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07003987 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003988 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003989 if (result != null) {
3990 boolean isSuccessfulConfirmCreds = result.getBoolean(
3991 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003992 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003993 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3994 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003995 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003996 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3997 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003998 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003999 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004000 if (needUpdate || mAuthDetailsRequired) {
4001 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4002 if (needUpdate && accountPresent) {
4003 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4004 }
4005 if (mAuthDetailsRequired) {
4006 long lastAuthenticatedTime = -1;
4007 if (accountPresent) {
4008 lastAuthenticatedTime = DatabaseUtils.longForQuery(
4009 mAccounts.openHelper.getReadableDatabase(),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004010 "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4011 + " FROM " +
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004012 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
4013 + ACCOUNTS_TYPE + "=?",
4014 new String[] {
4015 mAccountName, mAccountType
4016 });
4017 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004018 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004019 lastAuthenticatedTime);
4020 }
4021 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004022 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004023 if (result != null
4024 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004025 checkKeyIntent(
4026 Binder.getCallingUid(),
4027 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004028 }
4029 if (result != null
4030 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004031 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4032 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004033 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4034 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004035 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4036 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004037 }
Fred Quintana60307342009-03-24 22:48:12 -07004038 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004039 IAccountManagerResponse response;
4040 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004041 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004042 response = mResponse;
4043 } else {
4044 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004045 }
Fred Quintana60307342009-03-24 22:48:12 -07004046 if (response != null) {
4047 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004048 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004049 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4050 Log.v(TAG, getClass().getSimpleName()
4051 + " calling onError() on response " + response);
4052 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004053 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004054 "null bundle returned");
4055 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004056 if (mStripAuthTokenFromResult) {
4057 result.remove(AccountManager.KEY_AUTHTOKEN);
4058 }
Fred Quintana56285a62010-12-02 14:20:51 -08004059 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4060 Log.v(TAG, getClass().getSimpleName()
4061 + " calling onResult() on response " + response);
4062 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004063 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4064 (intent == null)) {
4065 // All AccountManager error codes are greater than 0
4066 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4067 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4068 } else {
4069 response.onResult(result);
4070 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004071 }
Fred Quintana60307342009-03-24 22:48:12 -07004072 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004073 // if the caller is dead then there is no one to care about remote exceptions
4074 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4075 Log.v(TAG, "failure while notifying response", e);
4076 }
Fred Quintana60307342009-03-24 22:48:12 -07004077 }
4078 }
4079 }
Fred Quintana60307342009-03-24 22:48:12 -07004080
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004081 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004082 public void onRequestContinued() {
4083 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004084 }
4085
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004086 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004087 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004088 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004089 IAccountManagerResponse response = getResponseAndClose();
4090 if (response != null) {
4091 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004092 Log.v(TAG, getClass().getSimpleName()
4093 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004094 }
4095 try {
4096 response.onError(errorCode, errorMessage);
4097 } catch (RemoteException e) {
4098 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4099 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4100 }
4101 }
4102 } else {
4103 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4104 Log.v(TAG, "Session.onError: already closed");
4105 }
Fred Quintana60307342009-03-24 22:48:12 -07004106 }
4107 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004108
4109 /**
4110 * find the component name for the authenticator and initiate a bind
4111 * if no authenticator or the bind fails then return false, otherwise return true
4112 */
4113 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004114 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4115 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4116 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004117 if (authenticatorInfo == null) {
4118 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4119 Log.v(TAG, "there is no authenticator for " + authenticatorType
4120 + ", bailing out");
4121 }
4122 return false;
4123 }
4124
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004125 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004126 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004127 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4128 + " which isn't encryption aware");
4129 return false;
4130 }
4131
Fred Quintanab839afc2009-10-14 15:57:28 -07004132 Intent intent = new Intent();
4133 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4134 intent.setComponent(authenticatorInfo.componentName);
4135 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4136 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4137 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004138 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004139 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004140 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4141 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4142 }
4143 return false;
4144 }
4145
Fred Quintanab839afc2009-10-14 15:57:28 -07004146 return true;
4147 }
Fred Quintana60307342009-03-24 22:48:12 -07004148 }
4149
4150 private class MessageHandler extends Handler {
4151 MessageHandler(Looper looper) {
4152 super(looper);
4153 }
Costin Manolache3348f142009-09-29 18:58:36 -07004154
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004155 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004156 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004157 switch (msg.what) {
4158 case MESSAGE_TIMED_OUT:
4159 Session session = (Session)msg.obj;
4160 session.onTimedOut();
4161 break;
4162
Amith Yamasani5be347b2013-03-31 17:44:31 -07004163 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004164 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004165 break;
4166
Fred Quintana60307342009-03-24 22:48:12 -07004167 default:
4168 throw new IllegalStateException("unhandled message: " + msg.what);
4169 }
4170 }
4171 }
4172
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004173 @VisibleForTesting
4174 String getPreNDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07004175 File systemDir = Environment.getDataSystemDirectory();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004176 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
4177 PRE_N_DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004178 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07004179 // Migrate old file, if it exists, to the new location.
4180 // Make sure the new file doesn't already exist. A dummy file could have been
4181 // accidentally created in the old location, causing the new one to become corrupted
4182 // as well.
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004183 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07004184 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07004185 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07004186 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07004187 if (!userDir.exists()) {
4188 if (!userDir.mkdirs()) {
4189 throw new IllegalStateException("User dir cannot be created: " + userDir);
4190 }
4191 }
4192 if (!oldFile.renameTo(databaseFile)) {
4193 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
4194 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004195 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004196 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004197 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08004198 }
4199
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004200 @VisibleForTesting
4201 String getDeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004202 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
4203 DE_DATABASE_NAME);
4204 return databaseFile.getPath();
4205 }
4206
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004207 @VisibleForTesting
4208 String getCeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004209 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4210 CE_DATABASE_NAME);
4211 return databaseFile.getPath();
4212 }
4213
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004214 private static class DebugDbHelper{
4215 private DebugDbHelper() {
4216 }
4217
4218 private static String TABLE_DEBUG = "debug_table";
4219
4220 // Columns for the table
4221 private static String ACTION_TYPE = "action_type";
4222 private static String TIMESTAMP = "time";
4223 private static String CALLER_UID = "caller_uid";
4224 private static String TABLE_NAME = "table_name";
4225 private static String KEY = "primary_key";
4226
4227 // These actions correspond to the occurrence of real actions. Since
4228 // these are called by the authenticators, the uid associated will be
4229 // of the authenticator.
4230 private static String ACTION_SET_PASSWORD = "action_set_password";
4231 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4232 private static String ACTION_ACCOUNT_ADD = "action_account_add";
4233 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004234 private static String ACTION_ACCOUNT_REMOVE_DE = "action_account_remove_de";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004235 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4236 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4237
4238 // These actions don't necessarily correspond to any action on
4239 // accountDb taking place. As an example, there might be a request for
4240 // addingAccount, which might not lead to addition of account on grounds
4241 // of bad authentication. We will still be logging it to keep track of
4242 // who called.
4243 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4244 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004245 private static String ACTION_SYNC_DE_CE_ACCOUNTS = "action_sync_de_ce_accounts";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004246
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004247 //This action doesn't add account to accountdb. Account is only
4248 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08004249 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004250 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4251 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08004252
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004253 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4254
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004255 private static void createDebugTable(SQLiteDatabase db) {
4256 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4257 + ACCOUNTS_ID + " INTEGER,"
4258 + ACTION_TYPE + " TEXT NOT NULL, "
4259 + TIMESTAMP + " DATETIME,"
4260 + CALLER_UID + " INTEGER NOT NULL,"
4261 + TABLE_NAME + " TEXT NOT NULL,"
4262 + KEY + " INTEGER PRIMARY KEY)");
4263 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4264 }
4265 }
4266
4267 private void logRecord(UserAccounts accounts, String action, String tableName) {
4268 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4269 logRecord(db, action, tableName, -1, accounts);
4270 }
4271
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004272 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4273 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4274 logRecord(db, action, tableName, -1, accounts, uid);
4275 }
4276
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004277 /*
4278 * This function receives an opened writable database.
4279 */
4280 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4281 UserAccounts userAccount) {
4282 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4283 }
4284
4285 /*
4286 * This function receives an opened writable database.
4287 */
4288 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4289 UserAccounts userAccount, int callingUid) {
4290 SQLiteStatement logStatement = userAccount.statementForLogging;
4291 logStatement.bindLong(1, accountId);
4292 logStatement.bindString(2, action);
4293 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4294 logStatement.bindLong(4, callingUid);
4295 logStatement.bindString(5, tableName);
4296 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
4297 logStatement.execute();
4298 logStatement.clearBindings();
4299 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4300 % MAX_DEBUG_DB_SIZE;
4301 }
4302
4303 /*
4304 * This should only be called once to compile the sql statement for logging
4305 * and to find the insertion point.
4306 */
4307 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4308 UserAccounts userAccount) {
4309 // Initialize the count if not done earlier.
4310 int size = (int) getDebugTableRowCount(db);
4311 if (size >= MAX_DEBUG_DB_SIZE) {
4312 // Table is full, and we need to find the point where to insert.
4313 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4314 } else {
4315 userAccount.debugDbInsertionPoint = size;
4316 }
4317 compileSqlStatementForLogging(db, userAccount);
4318 }
4319
4320 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4321 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4322 + " VALUES (?,?,?,?,?,?)";
4323 userAccount.statementForLogging = db.compileStatement(sql);
4324 }
4325
4326 private long getDebugTableRowCount(SQLiteDatabase db) {
4327 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4328 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4329 }
4330
4331 /*
4332 * Finds the row key where the next insertion should take place. This should
4333 * be invoked only if the table has reached its full capacity.
4334 */
4335 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4336 // This query finds the smallest timestamp value (and if 2 records have
4337 // same timestamp, the choose the lower id).
4338 String queryCountDebugDbRows = new StringBuilder()
4339 .append("SELECT ").append(DebugDbHelper.KEY)
4340 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4341 .append(" ORDER BY ")
4342 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4343 .append(" LIMIT 1")
4344 .toString();
4345 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4346 }
4347
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004348 static class PreNDatabaseHelper extends SQLiteOpenHelper {
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004349 private final Context mContext;
4350 private final int mUserId;
4351
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004352 public PreNDatabaseHelper(Context context, int userId, String preNDatabaseName) {
4353 super(context, preNDatabaseName, null, PRE_N_DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004354 mContext = context;
4355 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004356 }
4357
4358 @Override
4359 public void onCreate(SQLiteDatabase db) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004360 // We use PreNDatabaseHelper only if pre-N db exists
4361 throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004362 }
4363
Amith Yamasani67df64b2012-12-14 12:09:36 -08004364 private void createSharedAccountsTable(SQLiteDatabase db) {
4365 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4366 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4367 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4368 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4369 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4370 }
4371
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004372 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4373 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4374 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4375 }
4376
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004377 private void addOldAccountNameColumn(SQLiteDatabase db) {
4378 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4379 }
4380
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004381 private void addDebugTable(SQLiteDatabase db) {
4382 DebugDbHelper.createDebugTable(db);
4383 }
4384
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004385 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004386 db.execSQL(""
4387 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4388 + " BEGIN"
4389 + " DELETE FROM " + TABLE_AUTHTOKENS
4390 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4391 + " DELETE FROM " + TABLE_EXTRAS
4392 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004393 + " DELETE FROM " + TABLE_GRANTS
4394 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004395 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004396 }
4397
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004398 private void createGrantsTable(SQLiteDatabase db) {
4399 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4400 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4401 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4402 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4403 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4404 + "," + GRANTS_GRANTEE_UID + "))");
4405 }
4406
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004407 private void populateMetaTableWithAuthTypeAndUID(
4408 SQLiteDatabase db,
4409 Map<String, Integer> authTypeAndUIDMap) {
4410 Iterator<Entry<String, Integer>> iterator = authTypeAndUIDMap.entrySet().iterator();
4411 while (iterator.hasNext()) {
4412 Entry<String, Integer> entry = iterator.next();
4413 ContentValues values = new ContentValues();
4414 values.put(META_KEY,
4415 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
4416 values.put(META_VALUE, entry.getValue());
4417 db.insert(TABLE_META, null, values);
4418 }
4419 }
4420
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004421 /**
4422 * Pre-N database may need an upgrade before splitting
4423 */
Fred Quintana60307342009-03-24 22:48:12 -07004424 @Override
4425 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004426 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004427
Fred Quintanaa698f422009-04-08 19:14:54 -07004428 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004429 // no longer need to do anything since the work is done
4430 // when upgrading from version 2
4431 oldVersion++;
4432 }
4433
4434 if (oldVersion == 2) {
4435 createGrantsTable(db);
4436 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4437 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004438 oldVersion++;
4439 }
Costin Manolache3348f142009-09-29 18:58:36 -07004440
4441 if (oldVersion == 3) {
4442 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4443 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4444 oldVersion++;
4445 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004446
4447 if (oldVersion == 4) {
4448 createSharedAccountsTable(db);
4449 oldVersion++;
4450 }
4451
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004452 if (oldVersion == 5) {
4453 addOldAccountNameColumn(db);
4454 oldVersion++;
4455 }
4456
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004457 if (oldVersion == 6) {
4458 addLastSuccessfullAuthenticatedTimeColumn(db);
4459 oldVersion++;
4460 }
4461
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004462 if (oldVersion == 7) {
4463 addDebugTable(db);
4464 oldVersion++;
4465 }
4466
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004467 if (oldVersion == 8) {
4468 populateMetaTableWithAuthTypeAndUID(
4469 db,
4470 AccountManagerService.getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
4471 oldVersion++;
4472 }
4473
Amith Yamasani67df64b2012-12-14 12:09:36 -08004474 if (oldVersion != newVersion) {
4475 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4476 }
Fred Quintana60307342009-03-24 22:48:12 -07004477 }
4478
4479 @Override
4480 public void onOpen(SQLiteDatabase db) {
4481 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4482 }
4483 }
4484
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004485 static class DeDatabaseHelper extends SQLiteOpenHelper {
4486
4487 private final int mUserId;
4488 private volatile boolean mCeAttached;
4489
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004490 private DeDatabaseHelper(Context context, int userId, String deDatabaseName) {
4491 super(context, deDatabaseName, null, DE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004492 mUserId = userId;
4493 }
4494
4495 /**
4496 * This call needs to be made while the mCacheLock is held. The way to
4497 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4498 * @param db The database.
4499 */
4500 @Override
4501 public void onCreate(SQLiteDatabase db) {
4502 Log.i(TAG, "Creating DE database for user " + mUserId);
4503 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4504 + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4505 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4506 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4507 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4508 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4509 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4510
4511 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4512 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4513 + META_VALUE + " TEXT)");
4514
4515 createGrantsTable(db);
4516 createSharedAccountsTable(db);
4517 createAccountsDeletionTrigger(db);
4518 DebugDbHelper.createDebugTable(db);
4519 }
4520
4521 private void createSharedAccountsTable(SQLiteDatabase db) {
4522 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4523 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4524 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4525 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4526 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4527 }
4528
4529 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4530 db.execSQL(""
4531 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4532 + " BEGIN"
4533 + " DELETE FROM " + TABLE_GRANTS
4534 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4535 + " END");
4536 }
4537
4538 private void createGrantsTable(SQLiteDatabase db) {
4539 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4540 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4541 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4542 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4543 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4544 + "," + GRANTS_GRANTEE_UID + "))");
4545 }
4546
4547 @Override
4548 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4549 Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4550
4551 if (oldVersion != newVersion) {
4552 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4553 }
4554 }
4555
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004556 public void attachCeDatabase(File ceDbFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004557 SQLiteDatabase db = getWritableDatabase();
4558 db.execSQL("ATTACH DATABASE '" + ceDbFile.getPath()+ "' AS ceDb");
4559 mCeAttached = true;
4560 }
4561
4562 public boolean isCeDatabaseAttached() {
4563 return mCeAttached;
4564 }
4565
4566
4567 public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
4568 if(!mCeAttached) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004569 Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user " + mUserId
4570 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004571 }
4572 return super.getReadableDatabase();
4573 }
4574
4575 public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
4576 if(!mCeAttached) {
4577 Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004578 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004579 }
4580 return super.getWritableDatabase();
4581 }
4582
4583 @Override
4584 public void onOpen(SQLiteDatabase db) {
4585 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
4586 }
4587
4588 private void migratePreNDbToDe(File preNDbFile) {
4589 Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
4590 SQLiteDatabase db = getWritableDatabase();
4591 db.execSQL("ATTACH DATABASE '" + preNDbFile.getPath() + "' AS preNDb");
4592 db.beginTransaction();
4593 // Copy accounts fields
4594 db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
4595 + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4596 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4597 + ") "
4598 + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4599 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4600 + " FROM preNDb." + TABLE_ACCOUNTS);
4601 // Copy SHARED_ACCOUNTS
4602 db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
4603 + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
4604 "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4605 + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
4606 // Copy DEBUG_TABLE
4607 db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
4608 + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4609 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4610 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
4611 "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4612 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4613 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
4614 + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
4615 // Copy GRANTS
4616 db.execSQL("INSERT INTO " + TABLE_GRANTS
4617 + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4618 + GRANTS_GRANTEE_UID + ") " +
4619 "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4620 + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
4621 // Copy META
4622 db.execSQL("INSERT INTO " + TABLE_META
4623 + "(" + META_KEY + "," + META_VALUE + ") "
4624 + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
4625 db.setTransactionSuccessful();
4626 db.endTransaction();
4627
4628 db.execSQL("DETACH DATABASE preNDb");
4629 }
4630
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004631 static DeDatabaseHelper create(
4632 Context context,
4633 int userId,
4634 File preNDatabaseFile,
4635 File deDatabaseFile) {
4636 boolean newDbExists = deDatabaseFile.exists();
4637 DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId,
4638 deDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004639 // If the db just created, and there is a legacy db, migrate it
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004640 if (!newDbExists && preNDatabaseFile.exists()) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004641 // Migrate legacy db to the latest version - PRE_N_DATABASE_VERSION
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004642 PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId,
4643 preNDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004644 // Open the database to force upgrade if required
4645 preNDatabaseHelper.getWritableDatabase();
4646 preNDatabaseHelper.close();
4647 // Move data without SPII to DE
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004648 deDatabaseHelper.migratePreNDbToDe(preNDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004649 }
4650 return deDatabaseHelper;
4651 }
4652 }
4653
4654 static class CeDatabaseHelper extends SQLiteOpenHelper {
4655
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004656 public CeDatabaseHelper(Context context, String ceDatabaseName) {
4657 super(context, ceDatabaseName, null, CE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004658 }
4659
4660 /**
4661 * This call needs to be made while the mCacheLock is held.
4662 * @param db The database.
4663 */
4664 @Override
4665 public void onCreate(SQLiteDatabase db) {
4666 Log.i(TAG, "Creating CE database " + getDatabaseName());
4667 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4668 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4669 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4670 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4671 + ACCOUNTS_PASSWORD + " TEXT, "
4672 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4673
4674 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
4675 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4676 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4677 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
4678 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
4679 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
4680
4681 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
4682 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4683 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
4684 + EXTRAS_KEY + " TEXT NOT NULL, "
4685 + EXTRAS_VALUE + " TEXT, "
4686 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
4687
4688 createAccountsDeletionTrigger(db);
4689 }
4690
4691 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4692 db.execSQL(""
4693 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4694 + " BEGIN"
4695 + " DELETE FROM " + TABLE_AUTHTOKENS
4696 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4697 + " DELETE FROM " + TABLE_EXTRAS
4698 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4699 + " END");
4700 }
4701
4702 @Override
4703 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4704 Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
4705
4706 if (oldVersion == 9) {
4707 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4708 Log.v(TAG, "onUpgrade upgrading to v10");
4709 }
4710 db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
4711 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
4712 // Recreate the trigger, since the old one references the table to be removed
4713 db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
4714 createAccountsDeletionTrigger(db);
4715 db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
4716 db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
4717 oldVersion ++;
4718 }
4719
4720 if (oldVersion != newVersion) {
4721 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4722 }
4723 }
4724
4725 @Override
4726 public void onOpen(SQLiteDatabase db) {
4727 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
4728 }
4729
4730 static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
4731 String type) {
4732 Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
4733 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
4734 new String[]{name, type}, null, null, null);
4735 try {
4736 if (cursor.moveToNext()) {
4737 return cursor.getString(0);
4738 }
4739 return null;
4740 } finally {
4741 cursor.close();
4742 }
4743 }
4744
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004745 static List<Account> findCeAccountsNotInDe(SQLiteDatabase db) {
4746 // Select accounts from CE that do not exist in DE
4747 Cursor cursor = db.rawQuery(
4748 "SELECT " + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4749 + " FROM " + CE_TABLE_ACCOUNTS
4750 + " WHERE NOT EXISTS "
4751 + " (SELECT " + ACCOUNTS_ID + " FROM " + TABLE_ACCOUNTS
4752 + " WHERE " + ACCOUNTS_ID + "=" + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
4753 + " )", null);
4754 try {
4755 List<Account> accounts = new ArrayList<>(cursor.getCount());
4756 while (cursor.moveToNext()) {
4757 String accountName = cursor.getString(0);
4758 String accountType = cursor.getString(1);
4759 accounts.add(new Account(accountName, accountType));
4760 }
4761 return accounts;
4762 } finally {
4763 cursor.close();
4764 }
4765 }
4766
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004767 /**
4768 * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
4769 * it also performs migration to the new CE database.
4770 * @param context
4771 * @param userId id of the user where the database is located
4772 */
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004773 static CeDatabaseHelper create(
4774 Context context,
4775 int userId,
4776 File preNDatabaseFile,
4777 File ceDatabaseFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004778 boolean newDbExists = ceDatabaseFile.exists();
4779 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4780 Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004781 + preNDatabaseFile.exists() + " newDbExists=" + newDbExists);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004782 }
4783 boolean removeOldDb = false;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004784 if (!newDbExists && preNDatabaseFile.exists()) {
4785 removeOldDb = migratePreNDbToCe(preNDatabaseFile, ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004786 }
4787 // Try to open and upgrade if necessary
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004788 CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, ceDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004789 ceHelper.getWritableDatabase();
4790 ceHelper.close();
4791 if (removeOldDb) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004792 Slog.i(TAG, "Migration complete - removing pre-N db " + preNDatabaseFile);
4793 if (!SQLiteDatabase.deleteDatabase(preNDatabaseFile)) {
4794 Slog.e(TAG, "Cannot remove pre-N db " + preNDatabaseFile);
4795 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004796 }
4797 return ceHelper;
4798 }
4799
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004800 private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004801 Slog.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004802 try {
4803 FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
4804 } catch (IOException e) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004805 Slog.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004806 // Try to remove potentially damaged file if I/O error occurred
4807 deleteDbFileWarnIfFailed(ceDbFile);
4808 return false;
4809 }
4810 return true;
4811 }
4812 }
4813
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004814 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004815 return asBinder();
4816 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004817
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004818 /**
4819 * Searches array of arguments for the specified string
4820 * @param args array of argument strings
4821 * @param value value to search for
4822 * @return true if the value is contained in the array
4823 */
4824 private static boolean scanArgs(String[] args, String value) {
4825 if (args != null) {
4826 for (String arg : args) {
4827 if (value.equals(arg)) {
4828 return true;
4829 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004830 }
4831 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004832 return false;
4833 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004834
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004835 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004836 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07004837 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4838 != PackageManager.PERMISSION_GRANTED) {
4839 fout.println("Permission Denial: can't dump AccountsManager from from pid="
4840 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4841 + " without permission " + android.Manifest.permission.DUMP);
4842 return;
4843 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004844 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004845 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004846
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004847 final List<UserInfo> users = getUserManager().getUsers();
4848 for (UserInfo user : users) {
4849 ipw.println("User " + user + ":");
4850 ipw.increaseIndent();
4851 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4852 ipw.println();
4853 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08004854 }
4855 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004856
Amith Yamasani04e0d262012-02-14 11:50:53 -08004857 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4858 String[] args, boolean isCheckinRequest) {
4859 synchronized (userAccounts.cacheLock) {
4860 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004861
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004862 if (isCheckinRequest) {
4863 // This is a checkin request. *Only* upload the account types and the count of each.
4864 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4865 null, null, ACCOUNTS_TYPE, null, null);
4866 try {
4867 while (cursor.moveToNext()) {
4868 // print type,count
4869 fout.println(cursor.getString(0) + "," + cursor.getString(1));
4870 }
4871 } finally {
4872 if (cursor != null) {
4873 cursor.close();
4874 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004875 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004876 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004877 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07004878 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004879 fout.println("Accounts: " + accounts.length);
4880 for (Account account : accounts) {
4881 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004882 }
Fred Quintana307da1a2010-01-21 14:24:20 -08004883
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004884 // Add debug information.
4885 fout.println();
4886 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4887 null, null, null, null, DebugDbHelper.TIMESTAMP);
4888 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4889 fout.println("Accounts History");
4890 try {
4891 while (cursor.moveToNext()) {
4892 // print type,count
4893 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4894 cursor.getString(2) + "," + cursor.getString(3) + ","
4895 + cursor.getString(4) + "," + cursor.getString(5));
4896 }
4897 } finally {
4898 cursor.close();
4899 }
4900
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004901 fout.println();
4902 synchronized (mSessions) {
4903 final long now = SystemClock.elapsedRealtime();
4904 fout.println("Active Sessions: " + mSessions.size());
4905 for (Session session : mSessions.values()) {
4906 fout.println(" " + session.toDebugString(now));
4907 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004908 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004909
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004910 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004911 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004912 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004913 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004914 }
4915
Amith Yamasani04e0d262012-02-14 11:50:53 -08004916 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07004917 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004918 long identityToken = clearCallingIdentity();
4919 try {
4920 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4921 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4922 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004923
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004924 if (intent.getComponent() != null &&
4925 GrantCredentialsPermissionActivity.class.getName().equals(
4926 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004927 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004928 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004929 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004930 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004931 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004932 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07004933 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004934 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004935 Notification n = new Notification.Builder(contextForUser)
4936 .setWhen(0)
4937 .setSmallIcon(android.R.drawable.stat_sys_warning)
4938 .setColor(contextForUser.getColor(
4939 com.android.internal.R.color.system_notification_accent_color))
4940 .setContentTitle(String.format(notificationTitleFormat, account.name))
4941 .setContentText(message)
4942 .setContentIntent(PendingIntent.getActivityAsUser(
4943 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4944 null, user))
4945 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004946 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004947 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004948 } finally {
4949 restoreCallingIdentity(identityToken);
4950 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004951 }
4952
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004953 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004954 protected void installNotification(final int notificationId, final Notification n,
4955 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08004956 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004957 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08004958 }
4959
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004960 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004961 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004962 long identityToken = clearCallingIdentity();
4963 try {
4964 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004965 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004966 } finally {
4967 restoreCallingIdentity(identityToken);
4968 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004969 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004970
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004971 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
4972 for (String perm : permissions) {
4973 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
4974 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4975 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
4976 }
4977 final int opCode = AppOpsManager.permissionToOpCode(perm);
4978 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
4979 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
4980 return true;
4981 }
4982 }
4983 }
4984 return false;
4985 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004986
Amith Yamasani67df64b2012-12-14 12:09:36 -08004987 private int handleIncomingUser(int userId) {
4988 try {
4989 return ActivityManagerNative.getDefault().handleIncomingUser(
4990 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
4991 } catch (RemoteException re) {
4992 // Shouldn't happen, local.
4993 }
4994 return userId;
4995 }
4996
Christopher Tateccbf84f2013-05-08 15:25:41 -07004997 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004998 final int callingUserId = UserHandle.getUserId(callingUid);
4999
5000 final PackageManager userPackageManager;
5001 try {
5002 userPackageManager = mContext.createPackageContextAsUser(
5003 "android", 0, new UserHandle(callingUserId)).getPackageManager();
5004 } catch (NameNotFoundException e) {
5005 return false;
5006 }
5007
5008 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005009 for (String name : packages) {
5010 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005011 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08005012 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08005013 && (packageInfo.applicationInfo.privateFlags
5014 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07005015 return true;
5016 }
5017 } catch (PackageManager.NameNotFoundException e) {
5018 return false;
5019 }
5020 }
5021 return false;
5022 }
5023
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005024 private boolean permissionIsGranted(
5025 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07005026 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07005027 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005028 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07005029 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08005030 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005031 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5032 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08005033 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005034 + ": is authenticator? " + fromAuthenticator
5035 + ", has explicit permission? " + hasExplicitGrants);
5036 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07005037 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005038 }
5039
Svetoslavf3f02ac2015-09-08 14:36:35 -07005040 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5041 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005042 if (accountType == null) {
5043 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005044 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005045 return getTypesVisibleToCaller(callingUid, userId,
5046 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005047 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005048 }
5049
5050 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5051 if (accountType == null) {
5052 return false;
5053 } else {
5054 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5055 }
5056 }
5057
Svetoslavf3f02ac2015-09-08 14:36:35 -07005058 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5059 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005060 boolean isPermitted =
5061 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
5062 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005063 return getTypesForCaller(callingUid, userId, isPermitted);
5064 }
5065
5066 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
5067 return getTypesForCaller(callingUid, userId, false);
5068 }
5069
5070 private List<String> getTypesForCaller(
5071 int callingUid, int userId, boolean isOtherwisePermitted) {
5072 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005073 long identityToken = Binder.clearCallingIdentity();
5074 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5075 try {
5076 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5077 } finally {
5078 Binder.restoreCallingIdentity(identityToken);
5079 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005080 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005081 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005082 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5083 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
5084 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005085 }
5086 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005087 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005088 }
5089
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005090 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5091 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5092 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5093 if (account.name.equals(accountName)) {
5094 return true;
5095 }
5096 }
5097 }
5098 return false;
5099 }
5100
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005101 private static void checkManageUsersPermission(String message) {
5102 if (ActivityManager.checkComponentPermission(
5103 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5104 != PackageManager.PERMISSION_GRANTED) {
5105 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5106 }
5107 }
5108
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005109 private static void checkManageOrCreateUsersPermission(String message) {
5110 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5111 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5112 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5113 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5114 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5115 + message);
5116 }
5117 }
5118
Amith Yamasani04e0d262012-02-14 11:50:53 -08005119 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5120 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07005121 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005122 return true;
5123 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005124 UserAccounts accounts = getUserAccountsForCaller();
5125 synchronized (accounts.cacheLock) {
5126 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
5127 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005128 account.name, account.type};
5129 final boolean permissionGranted =
5130 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
5131 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5132 // TODO: Skip this check when running automated tests. Replace this
5133 // with a more general solution.
5134 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08005135 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005136 + " but ignoring since device is in test harness.");
5137 return true;
5138 }
5139 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005140 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005141 }
5142
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005143 private boolean isSystemUid(int callingUid) {
5144 String[] packages = null;
5145 long ident = Binder.clearCallingIdentity();
5146 try {
5147 packages = mPackageManager.getPackagesForUid(callingUid);
5148 } finally {
5149 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005150 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005151 if (packages != null) {
5152 for (String name : packages) {
5153 try {
5154 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5155 if (packageInfo != null
5156 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5157 != 0) {
5158 return true;
5159 }
5160 } catch (PackageManager.NameNotFoundException e) {
5161 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5162 }
5163 }
5164 } else {
5165 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005166 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005167 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005168 }
5169
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005170 /** Succeeds if any of the specified permissions are granted. */
5171 private void checkReadAccountsPermitted(
5172 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005173 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005174 int userId,
5175 String opPackageName) {
5176 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005177 String msg = String.format(
5178 "caller uid %s cannot access %s accounts",
5179 callingUid,
5180 accountType);
5181 Log.w(TAG, " " + msg);
5182 throw new SecurityException(msg);
5183 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005184 }
5185
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005186 private boolean canUserModifyAccounts(int userId, int callingUid) {
5187 // the managing app can always modify accounts
5188 if (isProfileOwner(callingUid)) {
5189 return true;
5190 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005191 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5192 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5193 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005194 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005195 return true;
5196 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005197
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005198 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5199 // the managing app can always modify accounts
5200 if (isProfileOwner(callingUid)) {
5201 return true;
5202 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005203 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5204 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005205 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005206 if (typesArray == null) {
5207 return true;
5208 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005209 for (String forbiddenType : typesArray) {
5210 if (forbiddenType.equals(accountType)) {
5211 return false;
5212 }
5213 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005214 return true;
5215 }
5216
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005217 private boolean isProfileOwner(int uid) {
5218 final DevicePolicyManagerInternal dpmi =
5219 LocalServices.getService(DevicePolicyManagerInternal.class);
5220 return (dpmi != null)
5221 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5222 }
5223
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005224 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005225 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5226 throws RemoteException {
5227 final int callingUid = getCallingUid();
5228
Amith Yamasani27db4682013-03-30 17:07:47 -07005229 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005230 throw new SecurityException();
5231 }
5232
5233 if (value) {
5234 grantAppPermission(account, authTokenType, uid);
5235 } else {
5236 revokeAppPermission(account, authTokenType, uid);
5237 }
5238 }
5239
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005240 /**
5241 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5242 * <p>
5243 * Although this is public it can only be accessed via the AccountManagerService object
5244 * which is in the system. This means we don't need to protect it with permissions.
5245 * @hide
5246 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005247 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005248 if (account == null || authTokenType == null) {
5249 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005250 return;
5251 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005252 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005253 synchronized (accounts.cacheLock) {
5254 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005255 db.beginTransaction();
5256 try {
5257 long accountId = getAccountIdLocked(db, account);
5258 if (accountId >= 0) {
5259 ContentValues values = new ContentValues();
5260 values.put(GRANTS_ACCOUNTS_ID, accountId);
5261 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
5262 values.put(GRANTS_GRANTEE_UID, uid);
5263 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
5264 db.setTransactionSuccessful();
5265 }
5266 } finally {
5267 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005268 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005269 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005270 UserHandle.of(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005271 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005272 }
5273
5274 /**
5275 * Don't allow callers with the given uid permission to get credentials for
5276 * account/authTokenType.
5277 * <p>
5278 * Although this is public it can only be accessed via the AccountManagerService object
5279 * which is in the system. This means we don't need to protect it with permissions.
5280 * @hide
5281 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005282 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005283 if (account == null || authTokenType == null) {
5284 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005285 return;
5286 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005287 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005288 synchronized (accounts.cacheLock) {
5289 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005290 db.beginTransaction();
5291 try {
5292 long accountId = getAccountIdLocked(db, account);
5293 if (accountId >= 0) {
5294 db.delete(TABLE_GRANTS,
5295 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
5296 + GRANTS_GRANTEE_UID + "=?",
5297 new String[]{String.valueOf(accountId), authTokenType,
5298 String.valueOf(uid)});
5299 db.setTransactionSuccessful();
5300 }
5301 } finally {
5302 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005303 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005304 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5305 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005306 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005307 }
Fred Quintana56285a62010-12-02 14:20:51 -08005308
5309 static final private String stringArrayToString(String[] value) {
5310 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5311 }
5312
Amith Yamasani04e0d262012-02-14 11:50:53 -08005313 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5314 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005315 if (oldAccountsForType != null) {
5316 ArrayList<Account> newAccountsList = new ArrayList<Account>();
5317 for (Account curAccount : oldAccountsForType) {
5318 if (!curAccount.equals(account)) {
5319 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005320 }
5321 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005322 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005323 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005324 } else {
5325 Account[] newAccountsForType = new Account[newAccountsList.size()];
5326 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005327 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005328 }
Fred Quintana56285a62010-12-02 14:20:51 -08005329 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005330 accounts.userDataCache.remove(account);
5331 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005332 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005333 }
5334
5335 /**
5336 * This assumes that the caller has already checked that the account is not already present.
5337 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08005338 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5339 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005340 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5341 Account[] newAccountsForType = new Account[oldLength + 1];
5342 if (accountsForType != null) {
5343 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005344 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005345 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005346 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08005347 }
5348
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005349 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07005350 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005351 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07005352 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005353 return unfiltered;
5354 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005355 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005356 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005357 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005358 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005359 // otherwise return non-shared accounts only.
5360 // This might be a temporary way to specify a whitelist
5361 String whiteList = mContext.getResources().getString(
5362 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5363 for (String packageName : packages) {
5364 if (whiteList.contains(";" + packageName + ";")) {
5365 return unfiltered;
5366 }
5367 }
5368 ArrayList<Account> allowed = new ArrayList<Account>();
5369 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5370 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005371 String requiredAccountType = "";
5372 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005373 // If there's an explicit callingPackage specified, check if that package
5374 // opted in to see restricted accounts.
5375 if (callingPackage != null) {
5376 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005377 if (pi != null && pi.restrictedAccountType != null) {
5378 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005379 }
5380 } else {
5381 // Otherwise check if the callingUid has a package that has opted in
5382 for (String packageName : packages) {
5383 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5384 if (pi != null && pi.restrictedAccountType != null) {
5385 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005386 break;
5387 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005388 }
5389 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005390 } catch (NameNotFoundException nnfe) {
5391 }
5392 for (Account account : unfiltered) {
5393 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005394 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005395 } else {
5396 boolean found = false;
5397 for (Account shared : sharedAccounts) {
5398 if (shared.equals(account)) {
5399 found = true;
5400 break;
5401 }
5402 }
5403 if (!found) {
5404 allowed.add(account);
5405 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005406 }
5407 }
5408 Account[] filtered = new Account[allowed.size()];
5409 allowed.toArray(filtered);
5410 return filtered;
5411 } else {
5412 return unfiltered;
5413 }
5414 }
5415
Amith Yamasani27db4682013-03-30 17:07:47 -07005416 /*
5417 * packageName can be null. If not null, it should be used to filter out restricted accounts
5418 * that the package is not allowed to access.
5419 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005420 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07005421 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005422 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005423 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005424 if (accounts == null) {
5425 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005426 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005427 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07005428 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005429 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005430 } else {
5431 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005432 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005433 totalLength += accounts.length;
5434 }
5435 if (totalLength == 0) {
5436 return EMPTY_ACCOUNT_ARRAY;
5437 }
5438 Account[] accounts = new Account[totalLength];
5439 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005440 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005441 System.arraycopy(accountsOfType, 0, accounts, totalLength,
5442 accountsOfType.length);
5443 totalLength += accountsOfType.length;
5444 }
Amith Yamasani27db4682013-03-30 17:07:47 -07005445 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005446 }
5447 }
5448
Amith Yamasani04e0d262012-02-14 11:50:53 -08005449 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5450 Account account, String key, String value) {
5451 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005452 if (userDataForAccount == null) {
5453 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005454 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005455 }
5456 if (value == null) {
5457 userDataForAccount.remove(key);
5458 } else {
5459 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005460 }
5461 }
5462
Carlos Valdivia91979be2015-05-22 14:11:35 -07005463 protected String readCachedTokenInternal(
5464 UserAccounts accounts,
5465 Account account,
5466 String tokenType,
5467 String callingPackage,
5468 byte[] pkgSigDigest) {
5469 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005470 return accounts.accountTokenCaches.get(
5471 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005472 }
5473 }
5474
Amith Yamasani04e0d262012-02-14 11:50:53 -08005475 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5476 Account account, String key, String value) {
5477 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005478 if (authTokensForAccount == null) {
5479 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005480 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005481 }
5482 if (value == null) {
5483 authTokensForAccount.remove(key);
5484 } else {
5485 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005486 }
5487 }
5488
Amith Yamasani04e0d262012-02-14 11:50:53 -08005489 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5490 String authTokenType) {
5491 synchronized (accounts.cacheLock) {
5492 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005493 if (authTokensForAccount == null) {
5494 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005495 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005496 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005497 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005498 }
5499 return authTokensForAccount.get(authTokenType);
5500 }
5501 }
5502
Simranjit Kohli858511c2016-03-10 18:36:11 +00005503 protected String readUserDataInternalLocked(
5504 UserAccounts accounts, Account account, String key) {
5505 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
5506 if (userDataForAccount == null) {
5507 // need to populate the cache for this account
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005508 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Simranjit Kohli858511c2016-03-10 18:36:11 +00005509 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
5510 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005511 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005512 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005513 }
5514
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005515 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
5516 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005517 HashMap<String, String> userDataForAccount = new HashMap<>();
5518 Cursor cursor = db.query(CE_TABLE_EXTRAS,
Fred Quintana56285a62010-12-02 14:20:51 -08005519 COLUMNS_EXTRAS_KEY_AND_VALUE,
5520 SELECTION_USERDATA_BY_ACCOUNT,
5521 new String[]{account.name, account.type},
5522 null, null, null);
5523 try {
5524 while (cursor.moveToNext()) {
5525 final String tmpkey = cursor.getString(0);
5526 final String value = cursor.getString(1);
5527 userDataForAccount.put(tmpkey, value);
5528 }
5529 } finally {
5530 cursor.close();
5531 }
5532 return userDataForAccount;
5533 }
5534
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005535 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
5536 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005537 HashMap<String, String> authTokensForAccount = new HashMap<>();
5538 Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
Fred Quintana56285a62010-12-02 14:20:51 -08005539 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
5540 SELECTION_AUTHTOKENS_BY_ACCOUNT,
5541 new String[]{account.name, account.type},
5542 null, null, null);
5543 try {
5544 while (cursor.moveToNext()) {
5545 final String type = cursor.getString(0);
5546 final String authToken = cursor.getString(1);
5547 authTokensForAccount.put(type, authToken);
5548 }
5549 } finally {
5550 cursor.close();
5551 }
5552 return authTokensForAccount;
5553 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005554
5555 private Context getContextForUser(UserHandle user) {
5556 try {
5557 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5558 } catch (NameNotFoundException e) {
5559 // Default to mContext, not finding the package system is running as is unlikely.
5560 return mContext;
5561 }
5562 }
Sandra Kwan78812282015-11-04 11:19:47 -08005563
5564 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5565 try {
5566 response.onResult(result);
5567 } catch (RemoteException e) {
5568 // if the caller is dead then there is no one to care about remote
5569 // exceptions
5570 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5571 Log.v(TAG, "failure while notifying response", e);
5572 }
5573 }
5574 }
5575
5576 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5577 String errorMessage) {
5578 try {
5579 response.onError(errorCode, errorMessage);
5580 } catch (RemoteException e) {
5581 // if the caller is dead then there is no one to care about remote
5582 // exceptions
5583 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5584 Log.v(TAG, "failure while notifying response", e);
5585 }
5586 }
5587 }
Fred Quintana60307342009-03-24 22:48:12 -07005588}