blob: 4cd76ba73dd454bd3afdfd7d882ff2e8d6230efb [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;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700115import java.util.LinkedList;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700116import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800117import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800118import java.util.Map.Entry;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700119import java.util.concurrent.atomic.AtomicInteger;
120import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700121
Fred Quintana60307342009-03-24 22:48:12 -0700122/**
123 * A system service that provides account, password, and authtoken management for all
124 * accounts on the device. Some of these calls are implemented with the help of the corresponding
125 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
126 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700127 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700128 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700129 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700130public class AccountManagerService
131 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800132 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700133 private static final String TAG = "AccountManagerService";
134
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600135 public static class Lifecycle extends SystemService {
136 private AccountManagerService mService;
137
138 public Lifecycle(Context context) {
139 super(context);
140 }
141
142 @Override
143 public void onStart() {
144 mService = new AccountManagerService(getContext());
145 publishBinderService(Context.ACCOUNT_SERVICE, mService);
146 }
147
148 @Override
149 public void onBootPhase(int phase) {
150 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
151 mService.systemReady();
152 }
153 }
154
155 @Override
156 public void onUnlockUser(int userHandle) {
157 mService.onUnlockUser(userHandle);
158 }
159 }
160
Fred Quintana60307342009-03-24 22:48:12 -0700161 private static final String DATABASE_NAME = "accounts.db";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700162 private static final int PRE_N_DATABASE_VERSION = 9;
163 private static final int CE_DATABASE_VERSION = 10;
164 private static final int DE_DATABASE_VERSION = 1;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700165
166 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700167
168 private final Context mContext;
169
Fred Quintana56285a62010-12-02 14:20:51 -0800170 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700171 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800173
Fred Quintana60307342009-03-24 22:48:12 -0700174 private final MessageHandler mMessageHandler;
175
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700176 /**
177 * Used to keep data read/write operations for logging purposes in a separate thread
178 * from main thread
179 */
180 private final LinkedList<Runnable> mLogRecordRunnables = new LinkedList<Runnable>();
181 private Thread mLogRecordThread;
182
Fred Quintana60307342009-03-24 22:48:12 -0700183 // Messages that can be sent on mHandler
184 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700185 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700186
Fred Quintana56285a62010-12-02 14:20:51 -0800187 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700188
189 private static final String TABLE_ACCOUNTS = "accounts";
190 private static final String ACCOUNTS_ID = "_id";
191 private static final String ACCOUNTS_NAME = "name";
192 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700193 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700194 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700195 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800196 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
197 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700198
199 private static final String TABLE_AUTHTOKENS = "authtokens";
200 private static final String AUTHTOKENS_ID = "_id";
201 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
202 private static final String AUTHTOKENS_TYPE = "type";
203 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
204
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700205 private static final String TABLE_GRANTS = "grants";
206 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
207 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
208 private static final String GRANTS_GRANTEE_UID = "uid";
209
Fred Quintana60307342009-03-24 22:48:12 -0700210 private static final String TABLE_EXTRAS = "extras";
211 private static final String EXTRAS_ID = "_id";
212 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
213 private static final String EXTRAS_KEY = "key";
214 private static final String EXTRAS_VALUE = "value";
215
216 private static final String TABLE_META = "meta";
217 private static final String META_KEY = "key";
218 private static final String META_VALUE = "value";
219
Amith Yamasani67df64b2012-12-14 12:09:36 -0800220 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700221 private static final String SHARED_ACCOUNTS_ID = "_id";
222
223 private static final String PRE_N_DATABASE_NAME = "accounts.db";
224 private static final String CE_DATABASE_NAME = "accounts_ce.db";
225 private static final String DE_DATABASE_NAME = "accounts_de.db";
226 private static final String CE_DB_PREFIX = "ceDb.";
227 private static final String CE_TABLE_ACCOUNTS = CE_DB_PREFIX + TABLE_ACCOUNTS;
228 private static final String CE_TABLE_AUTHTOKENS = CE_DB_PREFIX + TABLE_AUTHTOKENS;
229 private static final String CE_TABLE_EXTRAS = CE_DB_PREFIX + TABLE_EXTRAS;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800230
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700231 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
232 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700233 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800234
Carlos Valdivia91979be2015-05-22 14:11:35 -0700235 static {
236 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
237 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
238 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700239
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700240 private static final String COUNT_OF_MATCHING_GRANTS = ""
241 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
242 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
243 + " AND " + GRANTS_GRANTEE_UID + "=?"
244 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
245 + " AND " + ACCOUNTS_NAME + "=?"
246 + " AND " + ACCOUNTS_TYPE + "=?";
247
Fred Quintana56285a62010-12-02 14:20:51 -0800248 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
249 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700250
Fred Quintana56285a62010-12-02 14:20:51 -0800251 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
252 AUTHTOKENS_AUTHTOKEN};
253
254 private static final String SELECTION_USERDATA_BY_ACCOUNT =
255 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
256 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
257
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800258 private static final String META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX =
259 "auth_uid_for_type:";
260 private static final String META_KEY_DELIMITER = ":";
261 private static final String SELECTION_META_BY_AUTHENTICATOR_TYPE = META_KEY + " LIKE ?";
262
Fred Quintanaa698f422009-04-08 19:14:54 -0700263 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700264 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
265
Amith Yamasani04e0d262012-02-14 11:50:53 -0800266 static class UserAccounts {
267 private final int userId;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700268 private final DeDatabaseHelper openHelper;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800269 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
270 credentialsPermissionNotificationIds =
271 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
272 private final HashMap<Account, Integer> signinRequiredNotificationIds =
273 new HashMap<Account, Integer>();
274 private final Object cacheLock = new Object();
275 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700276 private final HashMap<String, Account[]> accountCache =
277 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800278 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800279 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800280 new HashMap<Account, HashMap<String, String>>();
281 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800282 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800283 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700284
285 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700286 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700287
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700288 /**
289 * protected by the {@link #cacheLock}
290 *
291 * Caches the previous names associated with an account. Previous names
292 * should be cached because we expect that when an Account is renamed,
293 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
294 * want to know if the accounts they care about have been renamed.
295 *
296 * The previous names are wrapped in an {@link AtomicReference} so that
297 * we can distinguish between those accounts with no previous names and
298 * those whose previous names haven't been cached (yet).
299 */
300 private final HashMap<Account, AtomicReference<String>> previousNameCache =
301 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800302
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700303 private int debugDbInsertionPoint = -1;
304 private SQLiteStatement statementForLogging;
305
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700306 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800307 this.userId = userId;
308 synchronized (cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700309 openHelper = DeDatabaseHelper.create(context, userId, preNDbFile, deDbFile);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800310 }
311 }
312 }
313
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700314 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600315 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800316
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700317 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700318 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700319
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700320 /**
321 * This should only be called by system code. One should only call this after the service
322 * has started.
323 * @return a reference to the AccountManagerService instance
324 * @hide
325 */
326 public static AccountManagerService getSingleton() {
327 return sThis.get();
328 }
Fred Quintana60307342009-03-24 22:48:12 -0700329
Fred Quintana56285a62010-12-02 14:20:51 -0800330 public AccountManagerService(Context context) {
331 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700332 }
333
Fred Quintana56285a62010-12-02 14:20:51 -0800334 public AccountManagerService(Context context, PackageManager packageManager,
335 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700336 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800337 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700338 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700339
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700340 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700341
Fred Quintana56285a62010-12-02 14:20:51 -0800342 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800343 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700344
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700345 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800346
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800347 IntentFilter intentFilter = new IntentFilter();
348 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
349 intentFilter.addDataScheme("package");
350 mContext.registerReceiver(new BroadcastReceiver() {
351 @Override
352 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700353 // Don't delete accounts when updating a authenticator's
354 // package.
355 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700356 /* Purging data requires file io, don't block the main thread. This is probably
357 * less than ideal because we are introducing a race condition where old grants
358 * could be exercised until they are purged. But that race condition existed
359 * anyway with the broadcast receiver.
360 *
361 * Ideally, we would completely clear the cache, purge data from the database,
362 * and then rebuild the cache. All under the cache lock. But that change is too
363 * large at this point.
364 */
365 Runnable r = new Runnable() {
366 @Override
367 public void run() {
368 purgeOldGrantsAll();
369 }
370 };
371 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700372 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800373 }
374 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800375
Amith Yamasani13593602012-03-22 16:16:17 -0700376 IntentFilter userFilter = new IntentFilter();
377 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800378 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700379 @Override
380 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800381 String action = intent.getAction();
382 if (Intent.ACTION_USER_REMOVED.equals(action)) {
383 onUserRemoved(intent);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800384 }
Amith Yamasani13593602012-03-22 16:16:17 -0700385 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800386 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800387 }
388
Dianne Hackborn164371f2013-10-01 19:10:13 -0700389 @Override
390 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
391 throws RemoteException {
392 try {
393 return super.onTransact(code, data, reply, flags);
394 } catch (RuntimeException e) {
395 // The account manager only throws security exceptions, so let's
396 // log all others.
397 if (!(e instanceof SecurityException)) {
398 Slog.wtf(TAG, "Account Manager Crash", e);
399 }
400 throw e;
401 }
402 }
403
Kenny Root26ff6622012-07-30 12:58:03 -0700404 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700405 }
406
Amith Yamasani258848d2012-08-10 17:06:33 -0700407 private UserManager getUserManager() {
408 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700409 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700410 }
411 return mUserManager;
412 }
413
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700414 /**
415 * Validate internal set of accounts against installed authenticators for
416 * given user. Clears cached authenticators before validating.
417 */
418 public void validateAccounts(int userId) {
419 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700420 // Invalidate user-specific cache to make sure we catch any
421 // removed authenticators.
422 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
423 }
424
425 /**
426 * Validate internal set of accounts against installed authenticators for
427 * given user. Clear cached authenticators before validating when requested.
428 */
429 private void validateAccountsInternal(
430 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700431 if (Log.isLoggable(TAG, Log.DEBUG)) {
432 Log.d(TAG, "validateAccountsInternal " + accounts.userId
433 + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600434 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700435 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700436
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700437 if (invalidateAuthenticatorCache) {
438 mAuthenticatorCache.invalidateCache(accounts.userId);
439 }
440
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700441 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
442 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -0700443 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700444
Amith Yamasani04e0d262012-02-14 11:50:53 -0800445 synchronized (accounts.cacheLock) {
446 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800447 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800448
449 // Get a list of stored authenticator type and UID
450 Cursor metaCursor = db.query(
451 TABLE_META,
452 new String[] {META_KEY, META_VALUE},
453 SELECTION_META_BY_AUTHENTICATOR_TYPE,
454 new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
455 null /* groupBy */,
456 null /* having */,
457 META_KEY);
458 // Create a list of authenticator type whose previous uid no longer exists
459 HashSet<String> obsoleteAuthType = Sets.newHashSet();
460 try {
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700461 SparseBooleanArray knownUids = null;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800462 while (metaCursor.moveToNext()) {
463 String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
464 String uid = metaCursor.getString(1);
465 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uid)) {
466 // Should never happen.
467 Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
468 + ", uid empty: " + TextUtils.isEmpty(uid));
469 continue;
470 }
471 Integer knownUid = knownAuth.get(type);
472 if (knownUid != null && uid.equals(knownUid.toString())) {
473 // Remove it from the knownAuth list if it's unchanged.
474 knownAuth.remove(type);
475 } else {
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700476 /*
477 * The authenticator is presently not cached and should only be triggered
478 * when we think an authenticator has been removed (or is being updated).
479 * But we still want to check if any data with the associated uid is
480 * around. This is an (imperfect) signal that the package may be updating.
481 *
482 * A side effect of this is that an authenticator sharing a uid with
483 * multiple apps won't get its credentials wiped as long as some app with
484 * that uid is still on the device. But I suspect that this is a rare case.
485 * And it isn't clear to me how an attacker could really exploit that
486 * feature.
487 *
488 * The upshot is that we don't have to worry about accounts getting
489 * uninstalled while the authenticator's package is being updated.
490 *
491 */
492 if (knownUids == null) {
493 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
494 }
495 if (!knownUids.get(Integer.parseInt(uid))) {
496 // The authenticator is not presently available to the cache. And the
497 // package no longer has a data directory (so we surmise it isn't updating).
498 // So purge its data from the account databases.
499 obsoleteAuthType.add(type);
500 // And delete it from the TABLE_META
501 db.delete(
502 TABLE_META,
503 META_KEY + "=? AND " + META_VALUE + "=?",
504 new String[] {
505 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
506 uid}
507 );
508 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800509 }
510 }
511 } finally {
512 metaCursor.close();
513 }
514
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700515 // Add the newly registered authenticator to TABLE_META. If old authenticators have
516 // been renabled (after being updated for example), then we just overwrite the old
517 // values.
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800518 Iterator<Entry<String, Integer>> iterator = knownAuth.entrySet().iterator();
519 while (iterator.hasNext()) {
520 Entry<String, Integer> entry = iterator.next();
521 ContentValues values = new ContentValues();
522 values.put(META_KEY,
523 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
524 values.put(META_VALUE, entry.getValue());
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700525 db.insertWithOnConflict(TABLE_META, null, values, SQLiteDatabase.CONFLICT_REPLACE);
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800526 }
527
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800528 Cursor cursor = db.query(TABLE_ACCOUNTS,
529 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800530 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800531 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800532 accounts.accountCache.clear();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700533 final HashMap<String, ArrayList<String>> accountNamesByType = new LinkedHashMap<>();
Fred Quintana56285a62010-12-02 14:20:51 -0800534 while (cursor.moveToNext()) {
535 final long accountId = cursor.getLong(0);
536 final String accountType = cursor.getString(1);
537 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700538
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800539 if (obsoleteAuthType.contains(accountType)) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700540 Slog.w(TAG, "deleting account " + accountName + " because type "
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800541 + accountType + "'s registered authenticator no longer exist.");
Fyodor Kupolov627fc202016-06-03 11:03:03 -0700542 db.beginTransaction();
543 try {
544 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
545 // Also delete from CE table if user is unlocked; if user is currently
546 // locked the account will be removed later by syncDeCeAccountsLocked
547 if (userUnlocked) {
548 db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
549 }
550 db.setTransactionSuccessful();
551 } finally {
552 db.endTransaction();
553 }
Fred Quintana56285a62010-12-02 14:20:51 -0800554 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700555
556 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
557 accountId, accounts);
558
Fred Quintana56285a62010-12-02 14:20:51 -0800559 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800560 accounts.userDataCache.remove(account);
561 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700562 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800563 } else {
564 ArrayList<String> accountNames = accountNamesByType.get(accountType);
565 if (accountNames == null) {
566 accountNames = new ArrayList<String>();
567 accountNamesByType.put(accountType, accountNames);
568 }
569 accountNames.add(accountName);
570 }
571 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700572 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800573 final String accountType = cur.getKey();
574 final ArrayList<String> accountNames = cur.getValue();
575 final Account[] accountsForType = new Account[accountNames.size()];
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700576 for (int i = 0; i < accountsForType.length; i++) {
577 accountsForType[i] = new Account(accountNames.get(i), accountType);
Fred Quintana56285a62010-12-02 14:20:51 -0800578 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800579 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800580 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800581 } finally {
582 cursor.close();
583 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800584 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800585 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800586 }
587 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700588 }
589
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700590 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
591 // Get the UIDs of all apps that might have data on the device. We want
592 // to preserve user data if the app might otherwise be storing data.
593 List<PackageInfo> pkgsWithData =
594 mPackageManager.getInstalledPackagesAsUser(
595 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
596 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
597 for (PackageInfo pkgInfo : pkgsWithData) {
598 if (pkgInfo.applicationInfo != null
599 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
600 knownUids.put(pkgInfo.applicationInfo.uid, true);
601 }
602 }
603 return knownUids;
604 }
605
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800606 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
607 Context context,
608 int userId) {
609 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700610 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
611 }
612
613 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
614 IAccountAuthenticatorCache authCache,
615 int userId) {
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800616 HashMap<String, Integer> knownAuth = new HashMap<>();
617 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
618 .getAllServices(userId)) {
619 knownAuth.put(service.type.type, service.uid);
620 }
621 return knownAuth;
622 }
623
Amith Yamasani04e0d262012-02-14 11:50:53 -0800624 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700625 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800626 }
627
628 protected UserAccounts getUserAccounts(int userId) {
629 synchronized (mUsers) {
630 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700631 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800632 if (accounts == null) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700633 File preNDbFile = new File(getPreNDatabaseName(userId));
634 File deDbFile = new File(getDeDatabaseName(userId));
635 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700636 initializeDebugDbSizeAndCompileSqlStatementForLogging(
637 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800638 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700639 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700640 validateAccounts = true;
641 }
642 // open CE database if necessary
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600643 if (!accounts.openHelper.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700644 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
645 synchronized (accounts.cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700646 File preNDatabaseFile = new File(getPreNDatabaseName(userId));
647 File ceDatabaseFile = new File(getCeDatabaseName(userId));
648 CeDatabaseHelper.create(mContext, userId, preNDatabaseFile, ceDatabaseFile);
649 accounts.openHelper.attachCeDatabase(ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700650 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700651 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700652 }
653 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700654 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800655 }
656 return accounts;
657 }
658 }
659
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700660 private void syncDeCeAccountsLocked(UserAccounts accounts) {
661 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
662 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
663 List<Account> accountsToRemove = CeDatabaseHelper.findCeAccountsNotInDe(db);
664 if (!accountsToRemove.isEmpty()) {
665 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
666 + accounts.userId + " was locked. Removing accounts from CE tables");
667 logRecord(accounts, DebugDbHelper.ACTION_SYNC_DE_CE_ACCOUNTS, TABLE_ACCOUNTS);
668
669 for (Account account : accountsToRemove) {
670 removeAccountInternal(accounts, account, Process.myUid());
671 }
672 }
673 }
674
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700675 private void purgeOldGrantsAll() {
676 synchronized (mUsers) {
677 for (int i = 0; i < mUsers.size(); i++) {
678 purgeOldGrants(mUsers.valueAt(i));
679 }
680 }
681 }
682
683 private void purgeOldGrants(UserAccounts accounts) {
684 synchronized (accounts.cacheLock) {
685 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
686 final Cursor cursor = db.query(TABLE_GRANTS,
687 new String[]{GRANTS_GRANTEE_UID},
688 null, null, GRANTS_GRANTEE_UID, null, null);
689 try {
690 while (cursor.moveToNext()) {
691 final int uid = cursor.getInt(0);
692 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
693 if (packageExists) {
694 continue;
695 }
696 Log.d(TAG, "deleting grants for UID " + uid
697 + " because its package is no longer installed");
698 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
699 new String[]{Integer.toString(uid)});
700 }
701 } finally {
702 cursor.close();
703 }
704 }
705 }
706
Amith Yamasani13593602012-03-22 16:16:17 -0700707 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700708 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700709 if (userId < 1) return;
710
711 UserAccounts accounts;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700712 boolean userUnlocked;
Amith Yamasani13593602012-03-22 16:16:17 -0700713 synchronized (mUsers) {
714 accounts = mUsers.get(userId);
715 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600716 userUnlocked = mLocalUnlockedUsers.get(userId);
717 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700718 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700719 if (accounts != null) {
720 synchronized (accounts.cacheLock) {
721 accounts.openHelper.close();
722 }
Amith Yamasani13593602012-03-22 16:16:17 -0700723 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700724 Log.i(TAG, "Removing database files for user " + userId);
725 File dbFile = new File(getDeDatabaseName(userId));
Amith Yamasani13593602012-03-22 16:16:17 -0700726
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700727 deleteDbFileWarnIfFailed(dbFile);
728 // Remove CE file if user is unlocked, or FBE is not enabled
729 boolean fbeEnabled = StorageManager.isFileEncryptedNativeOrEmulated();
730 if (!fbeEnabled || userUnlocked) {
731 File ceDb = new File(getCeDatabaseName(userId));
732 if (ceDb.exists()) {
733 deleteDbFileWarnIfFailed(ceDb);
734 }
735 }
736 }
737
738 private static void deleteDbFileWarnIfFailed(File dbFile) {
739 if (!SQLiteDatabase.deleteDatabase(dbFile)) {
740 Log.w(TAG, "Database at " + dbFile + " was not deleted successfully");
Amith Yamasani13593602012-03-22 16:16:17 -0700741 }
742 }
743
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700744 @VisibleForTesting
745 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600746 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
747 }
748
749 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700750 if (Log.isLoggable(TAG, Log.VERBOSE)) {
751 Log.v(TAG, "onUserUnlocked " + userId);
752 }
753 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600754 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700755 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800756 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700757 syncSharedAccounts(userId);
758 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800759
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700760 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800761 // Check if there's a shared account that needs to be created as an account
762 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
763 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700764 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700765 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -0700766 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700767 : UserHandle.USER_SYSTEM;
768 if (parentUserId < 0) {
769 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
770 return;
771 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800772 for (Account sa : sharedAccounts) {
773 if (ArrayUtils.contains(accounts, sa)) continue;
774 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700775 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800776 }
777 }
778
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700779 @Override
780 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700781 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700782 }
783
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800784 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700785 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700786 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800787 if (Log.isLoggable(TAG, Log.VERBOSE)) {
788 Log.v(TAG, "getPassword: " + account
789 + ", caller's uid " + Binder.getCallingUid()
790 + ", pid " + Binder.getCallingPid());
791 }
Fred Quintana382601f2010-03-25 12:25:10 -0700792 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000793 int userId = UserHandle.getCallingUserId();
794 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700795 String msg = String.format(
796 "uid %s cannot get secrets for accounts of type: %s",
797 callingUid,
798 account.type);
799 throw new SecurityException(msg);
800 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700801 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700802 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700803 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800804 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700805 } finally {
806 restoreCallingIdentity(identityToken);
807 }
808 }
809
Amith Yamasani04e0d262012-02-14 11:50:53 -0800810 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700811 if (account == null) {
812 return null;
813 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600814 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700815 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
816 return null;
817 }
Fred Quintana31957f12009-10-21 13:43:10 -0700818
Amith Yamasani04e0d262012-02-14 11:50:53 -0800819 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700820 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
821 return CeDatabaseHelper.findAccountPasswordByNameAndType(db, account.name,
822 account.type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700823 }
824 }
825
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800826 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700827 public String getPreviousName(Account account) {
828 if (Log.isLoggable(TAG, Log.VERBOSE)) {
829 Log.v(TAG, "getPreviousName: " + account
830 + ", caller's uid " + Binder.getCallingUid()
831 + ", pid " + Binder.getCallingPid());
832 }
833 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700834 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700835 long identityToken = clearCallingIdentity();
836 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700837 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700838 return readPreviousNameInternal(accounts, account);
839 } finally {
840 restoreCallingIdentity(identityToken);
841 }
842 }
843
844 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
845 if (account == null) {
846 return null;
847 }
848 synchronized (accounts.cacheLock) {
849 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
850 if (previousNameRef == null) {
851 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
852 Cursor cursor = db.query(
853 TABLE_ACCOUNTS,
854 new String[]{ ACCOUNTS_PREVIOUS_NAME },
855 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
856 new String[] { account.name, account.type },
857 null,
858 null,
859 null);
860 try {
861 if (cursor.moveToNext()) {
862 String previousName = cursor.getString(0);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700863 previousNameRef = new AtomicReference<>(previousName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700864 accounts.previousNameCache.put(account, previousNameRef);
865 return previousName;
866 } else {
867 return null;
868 }
869 } finally {
870 cursor.close();
871 }
872 } else {
873 return previousNameRef.get();
874 }
875 }
876 }
877
878 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700879 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700880 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800881 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700882 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
883 account, key, callingUid, Binder.getCallingPid());
884 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800885 }
Fred Quintana382601f2010-03-25 12:25:10 -0700886 if (account == null) throw new IllegalArgumentException("account is null");
887 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000888 int userId = UserHandle.getCallingUserId();
889 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700890 String msg = String.format(
891 "uid %s cannot get user data for accounts of type: %s",
892 callingUid,
893 account.type);
894 throw new SecurityException(msg);
895 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600896 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -0700897 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
898 return null;
899 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700900 long identityToken = clearCallingIdentity();
901 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700902 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +0000903 synchronized (accounts.cacheLock) {
904 if (!accountExistsCacheLocked(accounts, account)) {
905 return null;
906 }
907 return readUserDataInternalLocked(accounts, account, key);
908 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700909 } finally {
910 restoreCallingIdentity(identityToken);
911 }
912 }
913
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800914 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100915 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700916 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800917 if (Log.isLoggable(TAG, Log.VERBOSE)) {
918 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100919 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700920 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800921 + ", pid " + Binder.getCallingPid());
922 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100923 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700924 if (isCrossUser(callingUid, userId)) {
925 throw new SecurityException(
926 String.format(
927 "User %s tying to get authenticator types for %s" ,
928 UserHandle.getCallingUserId(),
929 userId));
930 }
931
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700932 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700933 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000934 return getAuthenticatorTypesInternal(userId);
935
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700936 } finally {
937 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700938 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700939 }
940
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000941 /**
942 * Should only be called inside of a clearCallingIdentity block.
943 */
944 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
945 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
946 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
947 AuthenticatorDescription[] types =
948 new AuthenticatorDescription[authenticatorCollection.size()];
949 int i = 0;
950 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
951 : authenticatorCollection) {
952 types[i] = authenticator.type;
953 i++;
954 }
955 return types;
956 }
957
958
959
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700960 private boolean isCrossUser(int callingUid, int userId) {
961 return (userId != UserHandle.getCallingUserId()
962 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100963 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700964 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
965 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100966 }
967
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700968 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700969 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600970 Bundle.setDefusable(extras, true);
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700971 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800972 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700973 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700974 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800975 + ", pid " + Binder.getCallingPid());
976 }
Fred Quintana382601f2010-03-25 12:25:10 -0700977 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000978 int userId = UserHandle.getCallingUserId();
979 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700980 String msg = String.format(
981 "uid %s cannot explicitly add accounts of type: %s",
982 callingUid,
983 account.type);
984 throw new SecurityException(msg);
985 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700986 /*
987 * Child users are not allowed to add accounts. Only the accounts that are
988 * shared by the parent profile can be added to child profile.
989 *
990 * TODO: Only allow accounts that were shared to be added by
991 * a limited user.
992 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700993
Fred Quintana60307342009-03-24 22:48:12 -0700994 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700995 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700996 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700997 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700998 return addAccountInternal(accounts, account, password, extras, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700999 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001000 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001001 }
1002 }
1003
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001004 @Override
1005 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001006 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001007 int callingUid = Binder.getCallingUid();
1008 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1009 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001010 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001011 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001012 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1013 final UserAccounts toAccounts = getUserAccounts(userTo);
1014 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001015 if (response != null) {
1016 Bundle result = new Bundle();
1017 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1018 try {
1019 response.onResult(result);
1020 } catch (RemoteException e) {
1021 Slog.w(TAG, "Failed to report error back to the client." + e);
1022 }
1023 }
1024 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001025 }
1026
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001027 Slog.d(TAG, "Copying account " + account.name
1028 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001029 long identityToken = clearCallingIdentity();
1030 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001031 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001032 false /* stripAuthTokenFromResult */, account.name,
1033 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001034 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001035 protected String toDebugString(long now) {
1036 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1037 + ", " + account.type;
1038 }
1039
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001040 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001041 public void run() throws RemoteException {
1042 mAuthenticator.getAccountCredentialsForCloning(this, account);
1043 }
1044
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001045 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001046 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001047 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001048 if (result != null
1049 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1050 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001051 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001052 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001053 super.onResult(result);
1054 }
1055 }
1056 }.bind();
1057 } finally {
1058 restoreCallingIdentity(identityToken);
1059 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001060 }
1061
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001062 @Override
1063 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001064 final int callingUid = Binder.getCallingUid();
1065 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1066 String msg = String.format(
1067 "accountAuthenticated( account: %s, callerUid: %s)",
1068 account,
1069 callingUid);
1070 Log.v(TAG, msg);
1071 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001072 if (account == null) {
1073 throw new IllegalArgumentException("account is null");
1074 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001075 int userId = UserHandle.getCallingUserId();
1076 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001077 String msg = String.format(
1078 "uid %s cannot notify authentication for accounts of type: %s",
1079 callingUid,
1080 account.type);
1081 throw new SecurityException(msg);
1082 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001083
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001084 if (!canUserModifyAccounts(userId, callingUid) ||
1085 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001086 return false;
1087 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001088
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001089 long identityToken = clearCallingIdentity();
1090 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001091 UserAccounts accounts = getUserAccounts(userId);
1092 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001093 } finally {
1094 restoreCallingIdentity(identityToken);
1095 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001096 }
1097
1098 private boolean updateLastAuthenticatedTime(Account account) {
1099 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001100 synchronized (accounts.cacheLock) {
1101 final ContentValues values = new ContentValues();
1102 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
1103 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1104 int i = db.update(
1105 TABLE_ACCOUNTS,
1106 values,
1107 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1108 new String[] {
1109 account.name, account.type
1110 });
1111 if (i > 0) {
1112 return true;
1113 }
1114 }
1115 return false;
1116 }
1117
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001118 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001119 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1120 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001121 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001122 long id = clearCallingIdentity();
1123 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001124 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001125 false /* stripAuthTokenFromResult */, account.name,
1126 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001127 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001128 protected String toDebugString(long now) {
1129 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1130 + ", " + account.type;
1131 }
1132
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001133 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001134 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001135 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001136 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001137 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -07001138 for (Account acc : getAccounts(parentUserId,
1139 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001140 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001141 mAuthenticator.addAccountFromCredentials(
1142 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001143 break;
1144 }
1145 }
1146 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001147 }
1148
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001149 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001150 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001151 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001152 // TODO: Anything to do if if succedded?
1153 // TODO: If it failed: Show error notification? Should we remove the shadow
1154 // account to avoid retries?
1155 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001156 }
1157
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001158 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001159 public void onError(int errorCode, String errorMessage) {
1160 super.onError(errorCode, errorMessage);
1161 // TODO: Show error notification to user
1162 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1163 }
1164
1165 }.bind();
1166 } finally {
1167 restoreCallingIdentity(id);
1168 }
1169 }
1170
Amith Yamasani04e0d262012-02-14 11:50:53 -08001171 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001172 Bundle extras, int callingUid) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001173 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001174 if (account == null) {
1175 return false;
1176 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001177 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001178 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1179 + " is locked. callingUid=" + callingUid);
1180 return false;
1181 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001182 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001183 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001184 db.beginTransaction();
1185 try {
1186 long numMatches = DatabaseUtils.longForQuery(db,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001187 "select count(*) from " + CE_TABLE_ACCOUNTS
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001188 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1189 new String[]{account.name, account.type});
1190 if (numMatches > 0) {
1191 Log.w(TAG, "insertAccountIntoDatabase: " + account
1192 + ", skipping since the account already exists");
1193 return false;
1194 }
1195 ContentValues values = new ContentValues();
1196 values.put(ACCOUNTS_NAME, account.name);
1197 values.put(ACCOUNTS_TYPE, account.type);
1198 values.put(ACCOUNTS_PASSWORD, password);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001199 long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001200 if (accountId < 0) {
1201 Log.w(TAG, "insertAccountIntoDatabase: " + account
1202 + ", skipping the DB insert failed");
1203 return false;
1204 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001205 // Insert into DE table
1206 values = new ContentValues();
1207 values.put(ACCOUNTS_ID, accountId);
1208 values.put(ACCOUNTS_NAME, account.name);
1209 values.put(ACCOUNTS_TYPE, account.type);
1210 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1211 System.currentTimeMillis());
1212 if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1213 Log.w(TAG, "insertAccountIntoDatabase: " + account
1214 + ", skipping the DB insert failed");
1215 return false;
1216 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001217 if (extras != null) {
1218 for (String key : extras.keySet()) {
1219 final String value = extras.getString(key);
1220 if (insertExtraLocked(db, accountId, key, value) < 0) {
1221 Log.w(TAG, "insertAccountIntoDatabase: " + account
1222 + ", skipping since insertExtra failed for key " + key);
1223 return false;
1224 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001225 }
1226 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001227 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001228
1229 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1230 accounts, callingUid);
1231
Amith Yamasani04e0d262012-02-14 11:50:53 -08001232 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001233 } finally {
1234 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001235 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001236 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001237 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001238 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1239 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001240 }
1241 return true;
1242 }
1243
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001244 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001245 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001246 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001247 }
1248 }
1249
Amith Yamasani5be347b2013-03-31 17:44:31 -07001250 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001251 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001252 * running, then clone the account too.
1253 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001254 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001255 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001256 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001257 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001258 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001259 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001260 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001261 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001262 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1263 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001264 }
1265 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001266 }
1267 }
1268
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001269 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -07001270 ContentValues values = new ContentValues();
1271 values.put(EXTRAS_KEY, key);
1272 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1273 values.put(EXTRAS_VALUE, value);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001274 return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
Fred Quintana60307342009-03-24 22:48:12 -07001275 }
1276
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001277 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001278 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001279 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001280 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001281 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1282 Log.v(TAG, "hasFeatures: " + account
1283 + ", response " + response
1284 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001285 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001286 + ", pid " + Binder.getCallingPid());
1287 }
Fred Quintana382601f2010-03-25 12:25:10 -07001288 if (response == null) throw new IllegalArgumentException("response is null");
1289 if (account == null) throw new IllegalArgumentException("account is null");
1290 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001291 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001292 checkReadAccountsPermitted(callingUid, account.type, userId,
1293 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001294
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001295 long identityToken = clearCallingIdentity();
1296 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001297 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001298 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001299 } finally {
1300 restoreCallingIdentity(identityToken);
1301 }
1302 }
1303
1304 private class TestFeaturesSession extends Session {
1305 private final String[] mFeatures;
1306 private final Account mAccount;
1307
Amith Yamasani04e0d262012-02-14 11:50:53 -08001308 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001309 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001310 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001311 true /* stripAuthTokenFromResult */, account.name,
1312 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001313 mFeatures = features;
1314 mAccount = account;
1315 }
1316
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001317 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001318 public void run() throws RemoteException {
1319 try {
1320 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1321 } catch (RemoteException e) {
1322 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1323 }
1324 }
1325
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001326 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001327 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001328 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001329 IAccountManagerResponse response = getResponseAndClose();
1330 if (response != null) {
1331 try {
1332 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001333 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001334 return;
1335 }
Fred Quintana56285a62010-12-02 14:20:51 -08001336 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1337 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1338 + response);
1339 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001340 final Bundle newResult = new Bundle();
1341 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1342 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1343 response.onResult(newResult);
1344 } catch (RemoteException e) {
1345 // if the caller is dead then there is no one to care about remote exceptions
1346 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1347 Log.v(TAG, "failure while notifying response", e);
1348 }
1349 }
1350 }
1351 }
1352
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001353 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001354 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001355 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001356 + ", " + mAccount
1357 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1358 }
1359 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001360
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001361 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001362 public void renameAccount(
1363 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001364 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001365 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1366 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001367 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001368 + ", pid " + Binder.getCallingPid());
1369 }
1370 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001371 int userId = UserHandle.getCallingUserId();
1372 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001373 String msg = String.format(
1374 "uid %s cannot rename accounts of type: %s",
1375 callingUid,
1376 accountToRename.type);
1377 throw new SecurityException(msg);
1378 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001379 long identityToken = clearCallingIdentity();
1380 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001381 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001382 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001383 Bundle result = new Bundle();
1384 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1385 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1386 try {
1387 response.onResult(result);
1388 } catch (RemoteException e) {
1389 Log.w(TAG, e.getMessage());
1390 }
1391 } finally {
1392 restoreCallingIdentity(identityToken);
1393 }
1394 }
1395
1396 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001397 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001398 Account resultAccount = null;
1399 /*
1400 * Cancel existing notifications. Let authenticators
1401 * re-post notifications as required. But we don't know if
1402 * the authenticators have bound their notifications to
1403 * now stale account name data.
1404 *
1405 * With a rename api, we might not need to do this anymore but it
1406 * shouldn't hurt.
1407 */
1408 cancelNotification(
1409 getSigninRequiredNotificationId(accounts, accountToRename),
1410 new UserHandle(accounts.userId));
1411 synchronized(accounts.credentialsPermissionNotificationIds) {
1412 for (Pair<Pair<Account, String>, Integer> pair:
1413 accounts.credentialsPermissionNotificationIds.keySet()) {
1414 if (accountToRename.equals(pair.first.first)) {
1415 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1416 cancelNotification(id, new UserHandle(accounts.userId));
1417 }
1418 }
1419 }
1420 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001421 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001422 db.beginTransaction();
1423 boolean isSuccessful = false;
1424 Account renamedAccount = new Account(newName, accountToRename.type);
1425 try {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001426 final long accountId = getAccountIdLocked(db, accountToRename);
1427 if (accountId >= 0) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001428 final ContentValues values = new ContentValues();
1429 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001430 final String[] argsAccountId = { String.valueOf(accountId) };
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001431 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1432 // Update NAME/PREVIOUS_NAME in DE accounts table
1433 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001434 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1435 db.setTransactionSuccessful();
1436 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001437 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1438 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001439 }
1440 } finally {
1441 db.endTransaction();
1442 if (isSuccessful) {
1443 /*
1444 * Database transaction was successful. Clean up cached
1445 * data associated with the account in the user profile.
1446 */
1447 insertAccountIntoCacheLocked(accounts, renamedAccount);
1448 /*
1449 * Extract the data and token caches before removing the
1450 * old account to preserve the user data associated with
1451 * the account.
1452 */
1453 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1454 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1455 removeAccountFromCacheLocked(accounts, accountToRename);
1456 /*
1457 * Update the cached data associated with the renamed
1458 * account.
1459 */
1460 accounts.userDataCache.put(renamedAccount, tmpData);
1461 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1462 accounts.previousNameCache.put(
1463 renamedAccount,
1464 new AtomicReference<String>(accountToRename.name));
1465 resultAccount = renamedAccount;
1466
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001467 int parentUserId = accounts.userId;
1468 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001469 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001470 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001471 * those users with which the account was shared.
1472 */
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001473 List<UserInfo> users = getUserManager().getUsers(true);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001474 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001475 if (user.isRestricted()
1476 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001477 renameSharedAccountAsUser(accountToRename, newName, user.id);
1478 }
1479 }
1480 }
1481 sendAccountsChangedBroadcast(accounts.userId);
1482 }
1483 }
1484 }
1485 return resultAccount;
1486 }
1487
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001488 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001489 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001490 return userInfo != null && userInfo.canHaveProfile();
1491 }
1492
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001493 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001494 public void removeAccount(IAccountManagerResponse response, Account account,
1495 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001496 removeAccountAsUser(
1497 response,
1498 account,
1499 expectActivityLaunch,
1500 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001501 }
1502
1503 @Override
1504 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001505 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001506 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001507 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1508 Log.v(TAG, "removeAccount: " + account
1509 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001510 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001511 + ", pid " + Binder.getCallingPid()
1512 + ", for user id " + userId);
1513 }
1514 if (response == null) throw new IllegalArgumentException("response is null");
1515 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001516 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001517 if (isCrossUser(callingUid, userId)) {
1518 throw new SecurityException(
1519 String.format(
1520 "User %s tying remove account for %s" ,
1521 UserHandle.getCallingUserId(),
1522 userId));
1523 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001524 /*
1525 * Only the system or authenticator should be allowed to remove accounts for that
1526 * authenticator. This will let users remove accounts (via Settings in the system) but not
1527 * arbitrary applications (like competing authenticators).
1528 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001529 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001530 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1531 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001532 String msg = String.format(
1533 "uid %s cannot remove accounts of type: %s",
1534 callingUid,
1535 account.type);
1536 throw new SecurityException(msg);
1537 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001538 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001539 try {
1540 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1541 "User cannot modify accounts");
1542 } catch (RemoteException re) {
1543 }
1544 return;
1545 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001546 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001547 try {
1548 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1549 "User cannot modify accounts of this type (policy).");
1550 } catch (RemoteException re) {
1551 }
1552 return;
1553 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001554 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001555 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001556 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001557 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001558 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001559 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001560 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001561 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001562 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001563 }
1564 }
1565 }
1566
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001567 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1568
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001569 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001570 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1571 } finally {
1572 restoreCallingIdentity(identityToken);
1573 }
1574 }
1575
1576 @Override
1577 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001578 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001579 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1580 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001581 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001582 + ", pid " + Binder.getCallingPid());
1583 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001584 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001585 if (account == null) {
1586 /*
1587 * Null accounts should result in returning false, as per
1588 * AccountManage.addAccountExplicitly(...) java doc.
1589 */
1590 Log.e(TAG, "account is null");
1591 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001592 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001593 String msg = String.format(
1594 "uid %s cannot explicitly add accounts of type: %s",
1595 callingUid,
1596 account.type);
1597 throw new SecurityException(msg);
1598 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001599 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001600 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001601 long identityToken = clearCallingIdentity();
1602 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001603 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001604 } finally {
1605 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001606 }
Fred Quintana60307342009-03-24 22:48:12 -07001607 }
1608
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001609 private class RemoveAccountSession extends Session {
1610 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001611 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001612 Account account, boolean expectActivityLaunch) {
1613 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001614 true /* stripAuthTokenFromResult */, account.name,
1615 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001616 mAccount = account;
1617 }
1618
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001619 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001620 protected String toDebugString(long now) {
1621 return super.toDebugString(now) + ", removeAccount"
1622 + ", account " + mAccount;
1623 }
1624
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001625 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001626 public void run() throws RemoteException {
1627 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1628 }
1629
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001630 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001631 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001632 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001633 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1634 && !result.containsKey(AccountManager.KEY_INTENT)) {
1635 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001636 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001637 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001638 }
1639 IAccountManagerResponse response = getResponseAndClose();
1640 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001641 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1642 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1643 + response);
1644 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001645 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001646 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001647 try {
1648 response.onResult(result2);
1649 } catch (RemoteException e) {
1650 // ignore
1651 }
1652 }
1653 }
1654 super.onResult(result);
1655 }
1656 }
1657
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001658 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001659 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001660 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001661 }
1662
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001663 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001664 int deleted;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001665 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001666 if (!userUnlocked) {
1667 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
1668 + " is still locked. CE data will be removed later");
1669 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001670 synchronized (accounts.cacheLock) {
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001671 final SQLiteDatabase db = userUnlocked
1672 ? accounts.openHelper.getWritableDatabaseUserIsUnlocked()
1673 : accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001674 final long accountId = getAccountIdLocked(db, account);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001675 db.beginTransaction();
1676 try {
1677 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1678 + "=?", new String[]{account.name, account.type});
1679 if (userUnlocked) {
1680 // Delete from CE table
1681 deleted = db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1682 + "=?", new String[]{account.name, account.type});
1683 }
1684 db.setTransactionSuccessful();
1685 } finally {
1686 db.endTransaction();
1687 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001688 removeAccountFromCacheLocked(accounts, account);
1689 sendAccountsChangedBroadcast(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001690 String action = userUnlocked ? DebugDbHelper.ACTION_ACCOUNT_REMOVE
1691 : DebugDbHelper.ACTION_ACCOUNT_REMOVE_DE;
1692 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001693 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001694 long id = Binder.clearCallingIdentity();
1695 try {
1696 int parentUserId = accounts.userId;
1697 if (canHaveProfile(parentUserId)) {
1698 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001699 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001700 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001701 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001702 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001703 }
1704 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001705 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001706 } finally {
1707 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001708 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001709 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001710 }
1711
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001712 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001713 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001714 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001715 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1716 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001717 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001718 + ", pid " + Binder.getCallingPid());
1719 }
Fred Quintana382601f2010-03-25 12:25:10 -07001720 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1721 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001722 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001723 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001724 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001725 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001726 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001727 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001728 db.beginTransaction();
1729 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001730 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001731 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001732 db.setTransactionSuccessful();
1733 } finally {
1734 db.endTransaction();
1735 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001736 }
Fred Quintana60307342009-03-24 22:48:12 -07001737 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001738 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001739 }
1740 }
1741
Carlos Valdivia91979be2015-05-22 14:11:35 -07001742 private void invalidateCustomTokenLocked(
1743 UserAccounts accounts,
1744 String accountType,
1745 String authToken) {
1746 if (authToken == null || accountType == null) {
1747 return;
1748 }
1749 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001750 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001751 }
1752
Amith Yamasani04e0d262012-02-14 11:50:53 -08001753 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1754 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001755 if (authToken == null || accountType == null) {
1756 return;
1757 }
Fred Quintana33269202009-04-20 16:05:10 -07001758 Cursor cursor = db.rawQuery(
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001759 "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1760 + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1761 + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1762 + " FROM " + CE_TABLE_ACCOUNTS
1763 + " JOIN " + CE_TABLE_AUTHTOKENS
1764 + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1765 + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
1766 + " WHERE " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_AUTHTOKEN
1767 + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
Fred Quintana33269202009-04-20 16:05:10 -07001768 new String[]{authToken, accountType});
1769 try {
1770 while (cursor.moveToNext()) {
1771 long authTokenId = cursor.getLong(0);
1772 String accountName = cursor.getString(1);
1773 String authTokenType = cursor.getString(2);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001774 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001775 writeAuthTokenIntoCacheLocked(
1776 accounts,
1777 db,
1778 new Account(accountName, accountType),
1779 authTokenType,
1780 null);
Fred Quintana60307342009-03-24 22:48:12 -07001781 }
Fred Quintana33269202009-04-20 16:05:10 -07001782 } finally {
1783 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001784 }
1785 }
1786
Carlos Valdivia91979be2015-05-22 14:11:35 -07001787 private void saveCachedToken(
1788 UserAccounts accounts,
1789 Account account,
1790 String callerPkg,
1791 byte[] callerSigDigest,
1792 String tokenType,
1793 String token,
1794 long expiryMillis) {
1795
1796 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1797 return;
1798 }
1799 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001800 UserHandle.of(accounts.userId));
Carlos Valdivia91979be2015-05-22 14:11:35 -07001801 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001802 accounts.accountTokenCaches.put(
1803 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001804 }
1805 }
1806
Amith Yamasani04e0d262012-02-14 11:50:53 -08001807 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1808 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001809 if (account == null || type == null) {
1810 return false;
1811 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001812 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001813 UserHandle.of(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001814 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001815 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001816 db.beginTransaction();
1817 try {
1818 long accountId = getAccountIdLocked(db, account);
1819 if (accountId < 0) {
1820 return false;
1821 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001822 db.delete(CE_TABLE_AUTHTOKENS,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001823 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1824 new String[]{type});
1825 ContentValues values = new ContentValues();
1826 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1827 values.put(AUTHTOKENS_TYPE, type);
1828 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001829 if (db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001830 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001831 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001832 return true;
1833 }
Fred Quintana33269202009-04-20 16:05:10 -07001834 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001835 } finally {
1836 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001837 }
Fred Quintana60307342009-03-24 22:48:12 -07001838 }
1839 }
1840
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001841 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001842 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001843 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001844 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1845 Log.v(TAG, "peekAuthToken: " + account
1846 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001847 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001848 + ", pid " + Binder.getCallingPid());
1849 }
Fred Quintana382601f2010-03-25 12:25:10 -07001850 if (account == null) throw new IllegalArgumentException("account is null");
1851 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001852 int userId = UserHandle.getCallingUserId();
1853 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001854 String msg = String.format(
1855 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1856 callingUid,
1857 account.type);
1858 throw new SecurityException(msg);
1859 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001860 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001861 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
1862 + callingUid);
1863 return null;
1864 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001865 long identityToken = clearCallingIdentity();
1866 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001867 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001868 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001869 } finally {
1870 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001871 }
Fred Quintana60307342009-03-24 22:48:12 -07001872 }
1873
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001874 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001875 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001876 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001877 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1878 Log.v(TAG, "setAuthToken: " + account
1879 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001880 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001881 + ", pid " + Binder.getCallingPid());
1882 }
Fred Quintana382601f2010-03-25 12:25:10 -07001883 if (account == null) throw new IllegalArgumentException("account is null");
1884 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001885 int userId = UserHandle.getCallingUserId();
1886 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001887 String msg = String.format(
1888 "uid %s cannot set auth tokens associated with accounts of type: %s",
1889 callingUid,
1890 account.type);
1891 throw new SecurityException(msg);
1892 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001893 long identityToken = clearCallingIdentity();
1894 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001895 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001896 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001897 } finally {
1898 restoreCallingIdentity(identityToken);
1899 }
Fred Quintana60307342009-03-24 22:48:12 -07001900 }
1901
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001902 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001903 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001904 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001905 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1906 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001907 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001908 + ", pid " + Binder.getCallingPid());
1909 }
Fred Quintana382601f2010-03-25 12:25:10 -07001910 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001911 int userId = UserHandle.getCallingUserId();
1912 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001913 String msg = String.format(
1914 "uid %s cannot set secrets for accounts of type: %s",
1915 callingUid,
1916 account.type);
1917 throw new SecurityException(msg);
1918 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001919 long identityToken = clearCallingIdentity();
1920 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001921 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001922 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001923 } finally {
1924 restoreCallingIdentity(identityToken);
1925 }
Fred Quintana60307342009-03-24 22:48:12 -07001926 }
1927
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001928 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1929 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001930 if (account == null) {
1931 return;
1932 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001933 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001934 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001935 db.beginTransaction();
1936 try {
1937 final ContentValues values = new ContentValues();
1938 values.put(ACCOUNTS_PASSWORD, password);
1939 final long accountId = getAccountIdLocked(db, account);
1940 if (accountId >= 0) {
1941 final String[] argsAccountId = {String.valueOf(accountId)};
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001942 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1943 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001944 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001945 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001946 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001947
1948 String action = (password == null || password.length() == 0) ?
1949 DebugDbHelper.ACTION_CLEAR_PASSWORD
1950 : DebugDbHelper.ACTION_SET_PASSWORD;
1951 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001952 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001953 } finally {
1954 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001955 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001956 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001957 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001958 }
1959
Amith Yamasani04e0d262012-02-14 11:50:53 -08001960 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001961 Log.i(TAG, "the accounts changed, sending broadcast of "
1962 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001963 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001964 }
1965
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001966 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001967 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001968 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001969 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1970 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001971 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001972 + ", pid " + Binder.getCallingPid());
1973 }
Fred Quintana382601f2010-03-25 12:25:10 -07001974 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001975 int userId = UserHandle.getCallingUserId();
1976 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001977 String msg = String.format(
1978 "uid %s cannot clear passwords for accounts of type: %s",
1979 callingUid,
1980 account.type);
1981 throw new SecurityException(msg);
1982 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001983 long identityToken = clearCallingIdentity();
1984 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001985 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001986 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001987 } finally {
1988 restoreCallingIdentity(identityToken);
1989 }
Fred Quintana60307342009-03-24 22:48:12 -07001990 }
1991
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001992 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001993 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001994 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001995 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1996 Log.v(TAG, "setUserData: " + account
1997 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001998 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001999 + ", pid " + Binder.getCallingPid());
2000 }
Fred Quintana382601f2010-03-25 12:25:10 -07002001 if (key == null) throw new IllegalArgumentException("key is null");
2002 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002003 int userId = UserHandle.getCallingUserId();
2004 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002005 String msg = String.format(
2006 "uid %s cannot set user data for accounts of type: %s",
2007 callingUid,
2008 account.type);
2009 throw new SecurityException(msg);
2010 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002011 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002012 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002013 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002014 synchronized (accounts.cacheLock) {
2015 if (!accountExistsCacheLocked(accounts, account)) {
2016 return;
2017 }
2018 setUserdataInternalLocked(accounts, account, key, value);
2019 }
Fred Quintana60307342009-03-24 22:48:12 -07002020 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002021 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002022 }
2023 }
2024
Simranjit Kohli858511c2016-03-10 18:36:11 +00002025 private boolean accountExistsCacheLocked(UserAccounts accounts, Account account) {
2026 if (accounts.accountCache.containsKey(account.type)) {
2027 for (Account acc : accounts.accountCache.get(account.type)) {
2028 if (acc.name.equals(account.name)) {
2029 return true;
2030 }
2031 }
2032 }
2033 return false;
2034 }
2035
2036 private void setUserdataInternalLocked(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002037 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07002038 if (account == null || key == null) {
2039 return;
2040 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002041 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2042 db.beginTransaction();
2043 try {
2044 long accountId = getAccountIdLocked(db, account);
2045 if (accountId < 0) {
2046 return;
2047 }
2048 long extrasId = getExtrasIdLocked(db, accountId, key);
2049 if (extrasId < 0) {
2050 extrasId = insertExtraLocked(db, accountId, key, value);
2051 if (extrasId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002052 return;
2053 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002054 } else {
2055 ContentValues values = new ContentValues();
2056 values.put(EXTRAS_VALUE, value);
2057 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
2058 return;
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00002059 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002060 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002061 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
2062 db.setTransactionSuccessful();
2063 } finally {
2064 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002065 }
2066 }
2067
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002068 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002069 if (result == null) {
2070 Log.e(TAG, "the result is unexpectedly null", new Exception());
2071 }
2072 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2073 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2074 + response);
2075 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002076 try {
2077 response.onResult(result);
2078 } catch (RemoteException e) {
2079 // if the caller is dead then there is no one to care about remote
2080 // exceptions
2081 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2082 Log.v(TAG, "failure while notifying response", e);
2083 }
2084 }
2085 }
2086
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002087 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002088 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2089 final String authTokenType)
2090 throws RemoteException {
2091 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002092 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2093
Fred Quintanad9640ec2012-05-23 12:37:00 -07002094 final int callingUid = getCallingUid();
2095 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07002096 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002097 throw new SecurityException("can only call from system");
2098 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002099 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002100 long identityToken = clearCallingIdentity();
2101 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002102 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002103 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2104 false /* stripAuthTokenFromResult */, null /* accountName */,
2105 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002106 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002107 protected String toDebugString(long now) {
2108 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002109 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002110 + ", authTokenType " + authTokenType;
2111 }
2112
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002113 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002114 public void run() throws RemoteException {
2115 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2116 }
2117
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002118 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002119 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002120 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002121 if (result != null) {
2122 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2123 Bundle bundle = new Bundle();
2124 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2125 super.onResult(bundle);
2126 return;
2127 } else {
2128 super.onResult(result);
2129 }
2130 }
2131 }.bind();
2132 } finally {
2133 restoreCallingIdentity(identityToken);
2134 }
2135 }
2136
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002137 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002138 public void getAuthToken(
2139 IAccountManagerResponse response,
2140 final Account account,
2141 final String authTokenType,
2142 final boolean notifyOnAuthFailure,
2143 final boolean expectActivityLaunch,
2144 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002145 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002146 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2147 Log.v(TAG, "getAuthToken: " + account
2148 + ", response " + response
2149 + ", authTokenType " + authTokenType
2150 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2151 + ", expectActivityLaunch " + expectActivityLaunch
2152 + ", caller's uid " + Binder.getCallingUid()
2153 + ", pid " + Binder.getCallingPid());
2154 }
Fred Quintana382601f2010-03-25 12:25:10 -07002155 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002156 try {
2157 if (account == null) {
2158 Slog.w(TAG, "getAuthToken called with null account");
2159 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2160 return;
2161 }
2162 if (authTokenType == null) {
2163 Slog.w(TAG, "getAuthToken called with null authTokenType");
2164 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2165 return;
2166 }
2167 } catch (RemoteException e) {
2168 Slog.w(TAG, "Failed to report error back to the client." + e);
2169 return;
2170 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002171 int userId = UserHandle.getCallingUserId();
2172 long ident = Binder.clearCallingIdentity();
2173 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002174 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002175 try {
2176 accounts = getUserAccounts(userId);
2177 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2178 AuthenticatorDescription.newKey(account.type), accounts.userId);
2179 } finally {
2180 Binder.restoreCallingIdentity(ident);
2181 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002182
Costin Manolachea40c6302010-12-13 14:50:45 -08002183 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002184 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002185
2186 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002187 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002188 final boolean permissionGranted =
2189 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002190
Carlos Valdivia91979be2015-05-22 14:11:35 -07002191 // Get the calling package. We will use it for the purpose of caching.
2192 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002193 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002194 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002195 try {
2196 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2197 } finally {
2198 Binder.restoreCallingIdentity(ident);
2199 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002200 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2201 String msg = String.format(
2202 "Uid %s is attempting to illegally masquerade as package %s!",
2203 callerUid,
2204 callerPkg);
2205 throw new SecurityException(msg);
2206 }
2207
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002208 // let authenticator know the identity of the caller
2209 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2210 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002211
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002212 if (notifyOnAuthFailure) {
2213 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002214 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002215
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002216 long identityToken = clearCallingIdentity();
2217 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002218 // Distill the caller's package signatures into a single digest.
2219 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2220
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002221 // if the caller has permission, do the peek. otherwise go the more expensive
2222 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002223 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002224 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002225 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002226 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002227 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2228 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2229 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002230 onResult(response, result);
2231 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002232 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002233 }
2234
Carlos Valdivia91979be2015-05-22 14:11:35 -07002235 if (customTokens) {
2236 /*
2237 * Look up tokens in the new cache only if the loginOptions don't have parameters
2238 * outside of those expected to be injected by the AccountManager, e.g.
2239 * ANDORID_PACKAGE_NAME.
2240 */
2241 String token = readCachedTokenInternal(
2242 accounts,
2243 account,
2244 authTokenType,
2245 callerPkg,
2246 callerPkgSigDigest);
2247 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002248 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2249 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2250 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002251 Bundle result = new Bundle();
2252 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2253 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2254 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2255 onResult(response, result);
2256 return;
2257 }
2258 }
2259
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002260 new Session(
2261 accounts,
2262 response,
2263 account.type,
2264 expectActivityLaunch,
2265 false /* stripAuthTokenFromResult */,
2266 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002267 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002268 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002269 protected String toDebugString(long now) {
2270 if (loginOptions != null) loginOptions.keySet();
2271 return super.toDebugString(now) + ", getAuthToken"
2272 + ", " + account
2273 + ", authTokenType " + authTokenType
2274 + ", loginOptions " + loginOptions
2275 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2276 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002277
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002278 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002279 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002280 // If the caller doesn't have permission then create and return the
2281 // "grant permission" intent instead of the "getAuthToken" intent.
2282 if (!permissionGranted) {
2283 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2284 } else {
2285 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2286 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002287 }
2288
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002289 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002290 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002291 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002292 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002293 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002294 Intent intent = newGrantCredentialsPermissionIntent(
2295 account,
2296 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002297 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002298 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002299 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002300 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002301 onResult(bundle);
2302 return;
2303 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002304 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002305 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002306 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2307 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002308 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002309 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002310 "the type and name should not be empty");
2311 return;
2312 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002313 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002314 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002315 saveAuthTokenToDatabase(
2316 mAccounts,
2317 resultAccount,
2318 authTokenType,
2319 authToken);
2320 }
2321 long expiryMillis = result.getLong(
2322 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2323 if (customTokens
2324 && expiryMillis > System.currentTimeMillis()) {
2325 saveCachedToken(
2326 mAccounts,
2327 account,
2328 callerPkg,
2329 callerPkgSigDigest,
2330 authTokenType,
2331 authToken,
2332 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002333 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002334 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002335
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002336 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002337 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002338 /*
2339 * Make sure that the supplied intent is owned by the authenticator
2340 * giving it to the system. Otherwise a malicious authenticator could
2341 * have users launching arbitrary activities by tricking users to
2342 * interact with malicious notifications.
2343 */
2344 checkKeyIntent(
2345 Binder.getCallingUid(),
2346 intent);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002347 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002348 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002349 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002350 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002351 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002352 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002353 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002354 }.bind();
2355 } finally {
2356 restoreCallingIdentity(identityToken);
2357 }
Fred Quintana60307342009-03-24 22:48:12 -07002358 }
2359
Carlos Valdivia91979be2015-05-22 14:11:35 -07002360 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2361 MessageDigest digester;
2362 try {
2363 digester = MessageDigest.getInstance("SHA-256");
2364 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2365 callerPkg, PackageManager.GET_SIGNATURES);
2366 for (Signature sig : pkgInfo.signatures) {
2367 digester.update(sig.toByteArray());
2368 }
2369 } catch (NoSuchAlgorithmException x) {
2370 Log.wtf(TAG, "SHA-256 should be available", x);
2371 digester = null;
2372 } catch (NameNotFoundException e) {
2373 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2374 digester = null;
2375 }
2376 return (digester == null) ? null : digester.digest();
2377 }
2378
Dianne Hackborn41203752012-08-31 14:05:51 -07002379 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2380 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002381 int uid = intent.getIntExtra(
2382 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2383 String authTokenType = intent.getStringExtra(
2384 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002385 final String titleAndSubtitle =
2386 mContext.getString(R.string.permission_request_notification_with_subtitle,
2387 account.name);
2388 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002389 String title = titleAndSubtitle;
2390 String subtitle = "";
2391 if (index > 0) {
2392 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002393 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002394 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002395 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002396 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002397 Notification n = new Notification.Builder(contextForUser)
2398 .setSmallIcon(android.R.drawable.stat_sys_warning)
2399 .setWhen(0)
2400 .setColor(contextForUser.getColor(
2401 com.android.internal.R.color.system_notification_accent_color))
2402 .setContentTitle(title)
2403 .setContentText(subtitle)
2404 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2405 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2406 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002407 installNotification(getCredentialPermissionNotificationId(
2408 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002409 }
2410
Costin Manolache5f383ad92010-12-02 16:44:46 -08002411 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002412 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002413
2414 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002415 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002416 // Since it was set in Eclair+ we can't change it without breaking apps using
2417 // the intent from a non-Activity context.
2418 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002419 intent.addCategory(
2420 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002421
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002422 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002423 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2424 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002425 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002426
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002427 return intent;
2428 }
2429
2430 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2431 int uid) {
2432 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002433 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002434 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002435 final Pair<Pair<Account, String>, Integer> key =
2436 new Pair<Pair<Account, String>, Integer>(
2437 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002438 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002439 if (id == null) {
2440 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002441 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002442 }
2443 }
2444 return id;
2445 }
2446
Amith Yamasani04e0d262012-02-14 11:50:53 -08002447 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002448 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002449 synchronized (accounts.signinRequiredNotificationIds) {
2450 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002451 if (id == null) {
2452 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002453 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002454 }
2455 }
2456 return id;
2457 }
2458
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002459 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002460 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002461 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002462 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002463 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002464 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2465 Log.v(TAG, "addAccount: accountType " + accountType
2466 + ", response " + response
2467 + ", authTokenType " + authTokenType
2468 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2469 + ", expectActivityLaunch " + expectActivityLaunch
2470 + ", caller's uid " + Binder.getCallingUid()
2471 + ", pid " + Binder.getCallingPid());
2472 }
Fred Quintana382601f2010-03-25 12:25:10 -07002473 if (response == null) throw new IllegalArgumentException("response is null");
2474 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002475
Amith Yamasani71e6c692013-03-24 17:39:28 -07002476 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002477 final int uid = Binder.getCallingUid();
2478 final int userId = UserHandle.getUserId(uid);
2479 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002480 try {
2481 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2482 "User is not allowed to add an account!");
2483 } catch (RemoteException re) {
2484 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002485 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002486 return;
2487 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002488 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002489 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002490 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2491 "User cannot modify accounts of this type (policy).");
2492 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002493 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002494 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2495 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002496 return;
2497 }
2498
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002499 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002500 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2501 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2502 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2503
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002504 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002505 long identityToken = clearCallingIdentity();
2506 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002507 UserAccounts accounts = getUserAccounts(usrId);
2508 logRecordWithUid(
2509 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002510 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002511 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002512 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002513 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002514 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002515 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002516 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002517 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002518
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002519 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002520 protected String toDebugString(long now) {
2521 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002522 + ", accountType " + accountType
2523 + ", requiredFeatures "
2524 + (requiredFeatures != null
2525 ? TextUtils.join(",", requiredFeatures)
2526 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002527 }
2528 }.bind();
2529 } finally {
2530 restoreCallingIdentity(identityToken);
2531 }
Fred Quintana60307342009-03-24 22:48:12 -07002532 }
2533
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002534 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002535 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2536 final String authTokenType, final String[] requiredFeatures,
2537 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002538 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002539 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2541 Log.v(TAG, "addAccount: accountType " + accountType
2542 + ", response " + response
2543 + ", authTokenType " + authTokenType
2544 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2545 + ", expectActivityLaunch " + expectActivityLaunch
2546 + ", caller's uid " + Binder.getCallingUid()
2547 + ", pid " + Binder.getCallingPid()
2548 + ", for user id " + userId);
2549 }
2550 if (response == null) throw new IllegalArgumentException("response is null");
2551 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002552 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002553 if (isCrossUser(callingUid, userId)) {
2554 throw new SecurityException(
2555 String.format(
2556 "User %s trying to add account for %s" ,
2557 UserHandle.getCallingUserId(),
2558 userId));
2559 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002560
2561 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002562 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002563 try {
2564 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2565 "User is not allowed to add an account!");
2566 } catch (RemoteException re) {
2567 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002568 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002569 return;
2570 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002571 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002572 try {
2573 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2574 "User cannot modify accounts of this type (policy).");
2575 } catch (RemoteException re) {
2576 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002577 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2578 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002579 return;
2580 }
2581
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002582 final int pid = Binder.getCallingPid();
2583 final int uid = Binder.getCallingUid();
2584 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2585 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2586 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2587
2588 long identityToken = clearCallingIdentity();
2589 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002590 UserAccounts accounts = getUserAccounts(userId);
2591 logRecordWithUid(
2592 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002593 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002594 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002595 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002596 @Override
2597 public void run() throws RemoteException {
2598 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2599 options);
2600 }
2601
2602 @Override
2603 protected String toDebugString(long now) {
2604 return super.toDebugString(now) + ", addAccount"
2605 + ", accountType " + accountType
2606 + ", requiredFeatures "
2607 + (requiredFeatures != null
2608 ? TextUtils.join(",", requiredFeatures)
2609 : null);
2610 }
2611 }.bind();
2612 } finally {
2613 restoreCallingIdentity(identityToken);
2614 }
2615 }
2616
Sandra Kwan78812282015-11-04 11:19:47 -08002617 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002618 public void startAddAccountSession(
2619 final IAccountManagerResponse response,
2620 final String accountType,
2621 final String authTokenType,
2622 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002623 final boolean expectActivityLaunch,
2624 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002625 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002626 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2627 Log.v(TAG,
2628 "startAddAccountSession: accountType " + accountType
2629 + ", response " + response
2630 + ", authTokenType " + authTokenType
2631 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2632 + ", expectActivityLaunch " + expectActivityLaunch
2633 + ", caller's uid " + Binder.getCallingUid()
2634 + ", pid " + Binder.getCallingPid());
2635 }
2636 if (response == null) {
2637 throw new IllegalArgumentException("response is null");
2638 }
2639 if (accountType == null) {
2640 throw new IllegalArgumentException("accountType is null");
2641 }
2642
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002643 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002644 // Only allow system to start session
2645 if (!isSystemUid(uid)) {
2646 String msg = String.format(
2647 "uid %s cannot stat add account session.",
2648 uid);
2649 throw new SecurityException(msg);
2650 }
2651
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002652 final int userId = UserHandle.getUserId(uid);
2653 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002654 try {
2655 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2656 "User is not allowed to add an account!");
2657 } catch (RemoteException re) {
2658 }
2659 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2660 return;
2661 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002662 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002663 try {
2664 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2665 "User cannot modify accounts of this type (policy).");
2666 } catch (RemoteException re) {
2667 }
2668 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2669 userId);
2670 return;
2671 }
Sandra Kwan78812282015-11-04 11:19:47 -08002672 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08002673 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2674 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2675 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2676
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002677 // Check to see if the Password should be included to the caller.
2678 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2679 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07002680 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002681
Sandra Kwan78812282015-11-04 11:19:47 -08002682 int usrId = UserHandle.getCallingUserId();
2683 long identityToken = clearCallingIdentity();
2684 try {
2685 UserAccounts accounts = getUserAccounts(usrId);
2686 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2687 TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002688 new StartAccountSession(
2689 accounts,
2690 response,
2691 accountType,
2692 expectActivityLaunch,
2693 null /* accountName */,
2694 false /* authDetailsRequired */,
2695 true /* updateLastAuthenticationTime */,
2696 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002697 @Override
2698 public void run() throws RemoteException {
2699 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2700 requiredFeatures, options);
2701 }
2702
2703 @Override
2704 protected String toDebugString(long now) {
2705 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2706 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2707 + accountType + ", requiredFeatures "
2708 + (requiredFeatures != null ? requiredFeaturesStr : null);
2709 }
2710 }.bind();
2711 } finally {
2712 restoreCallingIdentity(identityToken);
2713 }
2714 }
2715
2716 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2717 private abstract class StartAccountSession extends Session {
2718
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002719 private final boolean mIsPasswordForwardingAllowed;
2720
2721 public StartAccountSession(
2722 UserAccounts accounts,
2723 IAccountManagerResponse response,
2724 String accountType,
2725 boolean expectActivityLaunch,
2726 String accountName,
2727 boolean authDetailsRequired,
2728 boolean updateLastAuthenticationTime,
2729 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002730 super(accounts, response, accountType, expectActivityLaunch,
2731 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2732 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002733 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08002734 }
2735
2736 @Override
2737 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002738 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002739 mNumResults++;
2740 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08002741 if (result != null
2742 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08002743 checkKeyIntent(
2744 Binder.getCallingUid(),
2745 intent);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002746 // Omit passwords if the caller isn't permitted to see them.
2747 if (!mIsPasswordForwardingAllowed) {
2748 result.remove(AccountManager.KEY_PASSWORD);
2749 }
Sandra Kwan78812282015-11-04 11:19:47 -08002750 }
Sandra Kwan78812282015-11-04 11:19:47 -08002751 IAccountManagerResponse response;
2752 if (mExpectActivityLaunch && result != null
2753 && result.containsKey(AccountManager.KEY_INTENT)) {
2754 response = mResponse;
2755 } else {
2756 response = getResponseAndClose();
2757 }
2758 if (response == null) {
2759 return;
2760 }
2761 if (result == null) {
2762 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2763 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2764 + response);
2765 }
2766 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2767 "null bundle returned");
2768 return;
2769 }
2770
2771 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2772 // All AccountManager error codes are greater
2773 // than 0
2774 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2775 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2776 return;
2777 }
2778
2779 // Strip auth token from result.
2780 result.remove(AccountManager.KEY_AUTHTOKEN);
2781
2782 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2783 Log.v(TAG,
2784 getClass().getSimpleName() + " calling onResult() on response " + response);
2785 }
2786
2787 // Get the session bundle created by authenticator. The
2788 // bundle contains data necessary for finishing the session
2789 // later. The session bundle will be encrypted here and
2790 // decrypted later when trying to finish the session.
2791 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2792 if (sessionBundle != null) {
2793 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2794 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08002795 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002796 Log.w(TAG, "Account type in session bundle doesn't match request.");
2797 }
2798 // Add accountType info to session bundle. This will
2799 // override any value set by authenticator.
2800 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2801
2802 // Encrypt session bundle before returning to caller.
2803 try {
2804 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2805 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2806 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2807 } catch (GeneralSecurityException e) {
2808 if (Log.isLoggable(TAG, Log.DEBUG)) {
2809 Log.v(TAG, "Failed to encrypt session bundle!", e);
2810 }
2811 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2812 "failed to encrypt session bundle");
2813 return;
2814 }
2815 }
2816
2817 sendResponse(response, result);
2818 }
2819 }
2820
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002821 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08002822 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002823 @NonNull Bundle sessionBundle,
2824 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002825 Bundle appInfo,
2826 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002827 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08002828 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002829 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2830 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002831 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002832 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08002833 + ", caller's uid " + callingUid
2834 + ", caller's user id " + UserHandle.getCallingUserId()
2835 + ", pid " + Binder.getCallingPid()
2836 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002837 }
2838 if (response == null) {
2839 throw new IllegalArgumentException("response is null");
2840 }
2841
2842 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2843 // Account type is added to it before encryption.
2844 if (sessionBundle == null || sessionBundle.size() == 0) {
2845 throw new IllegalArgumentException("sessionBundle is empty");
2846 }
2847
Sandra Kwan0b84b452016-01-20 15:25:42 -08002848 // Only allow the system process to finish session for other users
2849 if (isCrossUser(callingUid, userId)) {
2850 throw new SecurityException(
2851 String.format(
2852 "User %s trying to finish session for %s without cross user permission",
2853 UserHandle.getCallingUserId(),
2854 userId));
2855 }
2856
Sandra Kwana578d112015-12-16 16:01:43 -08002857 // Only allow system to finish session
Sandra Kwan0b84b452016-01-20 15:25:42 -08002858 if (!isSystemUid(callingUid)) {
Sandra Kwana578d112015-12-16 16:01:43 -08002859 String msg = String.format(
Sandra Kwan0b84b452016-01-20 15:25:42 -08002860 "uid %s cannot finish session because it's not system uid.",
2861 callingUid);
Sandra Kwana578d112015-12-16 16:01:43 -08002862 throw new SecurityException(msg);
2863 }
2864
Sandra Kwan0b84b452016-01-20 15:25:42 -08002865 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002866 sendErrorResponse(response,
2867 AccountManager.ERROR_CODE_USER_RESTRICTED,
2868 "User is not allowed to add an account!");
2869 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2870 return;
2871 }
2872
2873 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002874 final Bundle decryptedBundle;
2875 final String accountType;
2876 // First decrypt session bundle to get account type for checking permission.
2877 try {
2878 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2879 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2880 if (decryptedBundle == null) {
2881 sendErrorResponse(
2882 response,
2883 AccountManager.ERROR_CODE_BAD_REQUEST,
2884 "failed to decrypt session bundle");
2885 return;
2886 }
2887 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2888 // Account type cannot be null. This should not happen if session bundle was created
2889 // properly by #StartAccountSession.
2890 if (TextUtils.isEmpty(accountType)) {
2891 sendErrorResponse(
2892 response,
2893 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2894 "accountType is empty");
2895 return;
2896 }
2897
2898 // If by any chances, decryptedBundle contains colliding keys with
2899 // system info
2900 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2901 // update credentials flow, we should replace with the new values of the current call.
2902 if (appInfo != null) {
2903 decryptedBundle.putAll(appInfo);
2904 }
2905
2906 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08002907 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002908 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2909 } catch (GeneralSecurityException e) {
2910 if (Log.isLoggable(TAG, Log.DEBUG)) {
2911 Log.v(TAG, "Failed to decrypt session bundle!", e);
2912 }
2913 sendErrorResponse(
2914 response,
2915 AccountManager.ERROR_CODE_BAD_REQUEST,
2916 "failed to decrypt session bundle");
2917 return;
2918 }
2919
Sandra Kwan0b84b452016-01-20 15:25:42 -08002920 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002921 sendErrorResponse(
2922 response,
2923 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2924 "User cannot modify accounts of this type (policy).");
2925 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2926 userId);
2927 return;
2928 }
2929
2930 long identityToken = clearCallingIdentity();
2931 try {
2932 UserAccounts accounts = getUserAccounts(userId);
2933 logRecordWithUid(
2934 accounts,
2935 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2936 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002937 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002938 new Session(
2939 accounts,
2940 response,
2941 accountType,
2942 expectActivityLaunch,
2943 true /* stripAuthTokenFromResult */,
2944 null /* accountName */,
2945 false /* authDetailsRequired */,
2946 true /* updateLastAuthenticationTime */) {
2947 @Override
2948 public void run() throws RemoteException {
2949 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2950 }
2951
2952 @Override
2953 protected String toDebugString(long now) {
2954 return super.toDebugString(now)
2955 + ", finishSession"
2956 + ", accountType " + accountType;
2957 }
2958 }.bind();
2959 } finally {
2960 restoreCallingIdentity(identityToken);
2961 }
2962 }
2963
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002964 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002965 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2966 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2967 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2968 long identityToken = clearCallingIdentity();
2969 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002970 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002971 } finally {
2972 restoreCallingIdentity(identityToken);
2973 }
2974 }
2975
2976 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002977 public void confirmCredentialsAsUser(
2978 IAccountManagerResponse response,
2979 final Account account,
2980 final Bundle options,
2981 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002982 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002983 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002984 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002985 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2986 Log.v(TAG, "confirmCredentials: " + account
2987 + ", response " + response
2988 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002989 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002990 + ", pid " + Binder.getCallingPid());
2991 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002992 // Only allow the system process to read accounts of other users
2993 if (isCrossUser(callingUid, userId)) {
2994 throw new SecurityException(
2995 String.format(
2996 "User %s trying to confirm account credentials for %s" ,
2997 UserHandle.getCallingUserId(),
2998 userId));
2999 }
Fred Quintana382601f2010-03-25 12:25:10 -07003000 if (response == null) throw new IllegalArgumentException("response is null");
3001 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003002 long identityToken = clearCallingIdentity();
3003 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003004 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003005 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003006 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003007 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003008 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003009 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003010 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003011 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003012 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003013 protected String toDebugString(long now) {
3014 return super.toDebugString(now) + ", confirmCredentials"
3015 + ", " + account;
3016 }
3017 }.bind();
3018 } finally {
3019 restoreCallingIdentity(identityToken);
3020 }
Fred Quintana60307342009-03-24 22:48:12 -07003021 }
3022
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003023 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003024 public void updateCredentials(IAccountManagerResponse response, final Account account,
3025 final String authTokenType, final boolean expectActivityLaunch,
3026 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003027 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003028 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3029 Log.v(TAG, "updateCredentials: " + account
3030 + ", response " + response
3031 + ", authTokenType " + authTokenType
3032 + ", expectActivityLaunch " + expectActivityLaunch
3033 + ", caller's uid " + Binder.getCallingUid()
3034 + ", pid " + Binder.getCallingPid());
3035 }
Fred Quintana382601f2010-03-25 12:25:10 -07003036 if (response == null) throw new IllegalArgumentException("response is null");
3037 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003038 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003039 long identityToken = clearCallingIdentity();
3040 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003041 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003042 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003043 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003044 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003045 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003046 public void run() throws RemoteException {
3047 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3048 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003049 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003050 protected String toDebugString(long now) {
3051 if (loginOptions != null) loginOptions.keySet();
3052 return super.toDebugString(now) + ", updateCredentials"
3053 + ", " + account
3054 + ", authTokenType " + authTokenType
3055 + ", loginOptions " + loginOptions;
3056 }
3057 }.bind();
3058 } finally {
3059 restoreCallingIdentity(identityToken);
3060 }
Fred Quintana60307342009-03-24 22:48:12 -07003061 }
3062
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003063 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003064 public void startUpdateCredentialsSession(
3065 IAccountManagerResponse response,
3066 final Account account,
3067 final String authTokenType,
3068 final boolean expectActivityLaunch,
3069 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003070 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003071 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3072 Log.v(TAG,
3073 "startUpdateCredentialsSession: " + account + ", response " + response
3074 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3075 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3076 + ", pid " + Binder.getCallingPid());
3077 }
3078 if (response == null) {
3079 throw new IllegalArgumentException("response is null");
3080 }
3081 if (account == null) {
3082 throw new IllegalArgumentException("account is null");
3083 }
Sandra Kwana578d112015-12-16 16:01:43 -08003084
3085 final int uid = Binder.getCallingUid();
3086 // Only allow system to start session
3087 if (!isSystemUid(uid)) {
3088 String msg = String.format(
3089 "uid %s cannot start update credentials session.",
3090 uid);
3091 throw new SecurityException(msg);
3092 }
3093
Sandra Kwane68c37e2015-11-12 17:11:49 -08003094 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003095
3096 // Check to see if the Password should be included to the caller.
3097 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3098 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003099 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003100
Sandra Kwane68c37e2015-11-12 17:11:49 -08003101 long identityToken = clearCallingIdentity();
3102 try {
3103 UserAccounts accounts = getUserAccounts(userId);
3104 new StartAccountSession(
3105 accounts,
3106 response,
3107 account.type,
3108 expectActivityLaunch,
3109 account.name,
3110 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003111 true /* updateLastCredentialTime */,
3112 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003113 @Override
3114 public void run() throws RemoteException {
3115 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3116 loginOptions);
3117 }
3118
3119 @Override
3120 protected String toDebugString(long now) {
3121 if (loginOptions != null)
3122 loginOptions.keySet();
3123 return super.toDebugString(now)
3124 + ", startUpdateCredentialsSession"
3125 + ", " + account
3126 + ", authTokenType " + authTokenType
3127 + ", loginOptions " + loginOptions;
3128 }
3129 }.bind();
3130 } finally {
3131 restoreCallingIdentity(identityToken);
3132 }
3133 }
3134
3135 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003136 public void isCredentialsUpdateSuggested(
3137 IAccountManagerResponse response,
3138 final Account account,
3139 final String statusToken) {
3140 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3141 Log.v(TAG,
3142 "isCredentialsUpdateSuggested: " + account + ", response " + response
3143 + ", caller's uid " + Binder.getCallingUid()
3144 + ", pid " + Binder.getCallingPid());
3145 }
3146 if (response == null) {
3147 throw new IllegalArgumentException("response is null");
3148 }
3149 if (account == null) {
3150 throw new IllegalArgumentException("account is null");
3151 }
3152 if (TextUtils.isEmpty(statusToken)) {
3153 throw new IllegalArgumentException("status token is empty");
3154 }
3155
3156 int uid = Binder.getCallingUid();
3157 // Only allow system to start session
3158 if (!isSystemUid(uid)) {
3159 String msg = String.format(
3160 "uid %s cannot stat add account session.",
3161 uid);
3162 throw new SecurityException(msg);
3163 }
3164
3165 int usrId = UserHandle.getCallingUserId();
3166 long identityToken = clearCallingIdentity();
3167 try {
3168 UserAccounts accounts = getUserAccounts(usrId);
3169 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3170 false /* stripAuthTokenFromResult */, account.name,
3171 false /* authDetailsRequired */) {
3172 @Override
3173 protected String toDebugString(long now) {
3174 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3175 + ", " + account;
3176 }
3177
3178 @Override
3179 public void run() throws RemoteException {
3180 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3181 }
3182
3183 @Override
3184 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003185 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003186 IAccountManagerResponse response = getResponseAndClose();
3187 if (response == null) {
3188 return;
3189 }
3190
3191 if (result == null) {
3192 sendErrorResponse(
3193 response,
3194 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3195 "null bundle");
3196 return;
3197 }
3198
3199 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3200 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3201 + response);
3202 }
3203 // Check to see if an error occurred. We know if an error occurred because all
3204 // error codes are greater than 0.
3205 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3206 sendErrorResponse(response,
3207 result.getInt(AccountManager.KEY_ERROR_CODE),
3208 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3209 return;
3210 }
3211 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3212 sendErrorResponse(
3213 response,
3214 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3215 "no result in response");
3216 return;
3217 }
3218 final Bundle newResult = new Bundle();
3219 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3220 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3221 sendResponse(response, newResult);
3222 }
3223 }.bind();
3224 } finally {
3225 restoreCallingIdentity(identityToken);
3226 }
3227 }
3228
3229 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003230 public void editProperties(IAccountManagerResponse response, final String accountType,
3231 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003232 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003233 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3234 Log.v(TAG, "editProperties: accountType " + accountType
3235 + ", response " + response
3236 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003237 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003238 + ", pid " + Binder.getCallingPid());
3239 }
Fred Quintana382601f2010-03-25 12:25:10 -07003240 if (response == null) throw new IllegalArgumentException("response is null");
3241 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003242 int userId = UserHandle.getCallingUserId();
3243 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003244 String msg = String.format(
3245 "uid %s cannot edit authenticator properites for account type: %s",
3246 callingUid,
3247 accountType);
3248 throw new SecurityException(msg);
3249 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003250 long identityToken = clearCallingIdentity();
3251 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003252 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003253 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003254 true /* stripAuthTokenFromResult */, null /* accountName */,
3255 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003256 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003257 public void run() throws RemoteException {
3258 mAuthenticator.editProperties(this, mAccountType);
3259 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003260 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003261 protected String toDebugString(long now) {
3262 return super.toDebugString(now) + ", editProperties"
3263 + ", accountType " + accountType;
3264 }
3265 }.bind();
3266 } finally {
3267 restoreCallingIdentity(identityToken);
3268 }
Fred Quintana60307342009-03-24 22:48:12 -07003269 }
3270
Amith Yamasani12747872015-12-07 14:19:49 -08003271 @Override
3272 public boolean someUserHasAccount(@NonNull final Account account) {
3273 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3274 throw new SecurityException("Only system can check for accounts across users");
3275 }
3276 final long token = Binder.clearCallingIdentity();
3277 try {
3278 AccountAndUser[] allAccounts = getAllAccounts();
3279 for (int i = allAccounts.length - 1; i >= 0; i--) {
3280 if (allAccounts[i].account.equals(account)) {
3281 return true;
3282 }
3283 }
3284 return false;
3285 } finally {
3286 Binder.restoreCallingIdentity(token);
3287 }
3288 }
3289
Fred Quintana33269202009-04-20 16:05:10 -07003290 private class GetAccountsByTypeAndFeatureSession extends Session {
3291 private final String[] mFeatures;
3292 private volatile Account[] mAccountsOfType = null;
3293 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3294 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003295 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003296
Amith Yamasani04e0d262012-02-14 11:50:53 -08003297 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003298 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003299 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003300 true /* stripAuthTokenFromResult */, null /* accountName */,
3301 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003302 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003303 mFeatures = features;
3304 }
3305
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003306 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003307 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003308 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003309 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3310 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003311 }
Fred Quintana33269202009-04-20 16:05:10 -07003312 // check whether each account matches the requested features
3313 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
3314 mCurrentAccount = 0;
3315
3316 checkAccount();
3317 }
3318
3319 public void checkAccount() {
3320 if (mCurrentAccount >= mAccountsOfType.length) {
3321 sendResult();
3322 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003323 }
Fred Quintana33269202009-04-20 16:05:10 -07003324
Fred Quintana29e94b82010-03-10 12:11:51 -08003325 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3326 if (accountAuthenticator == null) {
3327 // It is possible that the authenticator has died, which is indicated by
3328 // mAuthenticator being set to null. If this happens then just abort.
3329 // There is no need to send back a result or error in this case since
3330 // that already happened when mAuthenticator was cleared.
3331 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3332 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3333 + " connected to the authenticator, " + toDebugString());
3334 }
3335 return;
3336 }
Fred Quintana33269202009-04-20 16:05:10 -07003337 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003338 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003339 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003340 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003341 }
3342 }
3343
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003344 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003345 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003346 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003347 mNumResults++;
3348 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003349 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003350 return;
3351 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003352 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003353 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3354 }
3355 mCurrentAccount++;
3356 checkAccount();
3357 }
3358
3359 public void sendResult() {
3360 IAccountManagerResponse response = getResponseAndClose();
3361 if (response != null) {
3362 try {
3363 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3364 for (int i = 0; i < accounts.length; i++) {
3365 accounts[i] = mAccountsWithFeatures.get(i);
3366 }
Fred Quintana56285a62010-12-02 14:20:51 -08003367 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3368 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3369 + response);
3370 }
Fred Quintana33269202009-04-20 16:05:10 -07003371 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003372 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003373 response.onResult(result);
3374 } catch (RemoteException e) {
3375 // if the caller is dead then there is no one to care about remote exceptions
3376 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3377 Log.v(TAG, "failure while notifying response", e);
3378 }
3379 }
3380 }
3381 }
3382
3383
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003384 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003385 protected String toDebugString(long now) {
3386 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3387 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3388 }
3389 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003390
Amith Yamasani04e0d262012-02-14 11:50:53 -08003391 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003392 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003393 * @hide
3394 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003395 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003396 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003397 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003398 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3399 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003400 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003401 return new Account[0];
3402 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003403 long identityToken = clearCallingIdentity();
3404 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003405 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003406 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003407 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003408 callingUid,
3409 null, // packageName
3410 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003411 } finally {
3412 restoreCallingIdentity(identityToken);
3413 }
3414 }
3415
Amith Yamasanif29f2362012-04-05 18:29:52 -07003416 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003417 * Returns accounts for all running users.
3418 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003419 * @hide
3420 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003421 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003422 public AccountAndUser[] getRunningAccounts() {
3423 final int[] runningUserIds;
3424 try {
3425 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3426 } catch (RemoteException e) {
3427 // Running in system_server; should never happen
3428 throw new RuntimeException(e);
3429 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003430 return getAccounts(runningUserIds);
3431 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003432
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003433 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003434 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003435 public AccountAndUser[] getAllAccounts() {
3436 final List<UserInfo> users = getUserManager().getUsers();
3437 final int[] userIds = new int[users.size()];
3438 for (int i = 0; i < userIds.length; i++) {
3439 userIds[i] = users.get(i).id;
3440 }
3441 return getAccounts(userIds);
3442 }
3443
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003444 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003445 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003446 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003447 for (int userId : userIds) {
3448 UserAccounts userAccounts = getUserAccounts(userId);
3449 if (userAccounts == null) continue;
3450 synchronized (userAccounts.cacheLock) {
3451 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3452 Binder.getCallingUid(), null);
3453 for (int a = 0; a < accounts.length; a++) {
3454 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003455 }
3456 }
3457 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003458
3459 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3460 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003461 }
3462
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003463 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003464 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003465 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3466 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003467 }
3468
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003469 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003470 private Account[] getAccountsAsUser(
3471 String type,
3472 int userId,
3473 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003474 int packageUid,
3475 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003476 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003477 // Only allow the system process to read accounts of other users
3478 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003479 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003480 && mContext.checkCallingOrSelfPermission(
3481 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3482 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003483 throw new SecurityException("User " + UserHandle.getCallingUserId()
3484 + " trying to get account for " + userId);
3485 }
3486
Fred Quintana56285a62010-12-02 14:20:51 -08003487 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3488 Log.v(TAG, "getAccounts: accountType " + type
3489 + ", caller's uid " + Binder.getCallingUid()
3490 + ", pid " + Binder.getCallingPid());
3491 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003492 // If the original calling app was using the framework account chooser activity, we'll
3493 // be passed in the original caller's uid here, which is what should be used for filtering.
3494 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3495 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003496 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003497 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003498
Svetoslavf3f02ac2015-09-08 14:36:35 -07003499 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3500 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003501 if (visibleAccountTypes.isEmpty()
3502 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003503 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003504 } else if (visibleAccountTypes.contains(type)) {
3505 // Prune the list down to just the requested type.
3506 visibleAccountTypes = new ArrayList<>();
3507 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003508 } // else aggregate all the visible accounts (it won't matter if the
3509 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003510
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003511 long identityToken = clearCallingIdentity();
3512 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003513 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003514 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003515 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003516 callingUid,
3517 callingPackage,
3518 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003519 } finally {
3520 restoreCallingIdentity(identityToken);
3521 }
3522 }
3523
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003524 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003525 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003526 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003527 int callingUid,
3528 String callingPackage,
3529 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003530 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003531 ArrayList<Account> visibleAccounts = new ArrayList<>();
3532 for (String visibleType : visibleAccountTypes) {
3533 Account[] accountsForType = getAccountsFromCacheLocked(
3534 userAccounts, visibleType, callingUid, callingPackage);
3535 if (accountsForType != null) {
3536 visibleAccounts.addAll(Arrays.asList(accountsForType));
3537 }
3538 }
3539 Account[] result = new Account[visibleAccounts.size()];
3540 for (int i = 0; i < visibleAccounts.size(); i++) {
3541 result[i] = visibleAccounts.get(i);
3542 }
3543 return result;
3544 }
3545 }
3546
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003547 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003548 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
3549 checkManageUsersPermission("addSharedAccountsFromParentUser");
3550 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3551 for (Account account : accounts) {
3552 addSharedAccountAsUser(account, userId);
3553 }
3554 }
3555
3556 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003557 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003558 UserAccounts accounts = getUserAccounts(userId);
3559 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003560 ContentValues values = new ContentValues();
3561 values.put(ACCOUNTS_NAME, account.name);
3562 values.put(ACCOUNTS_TYPE, account.type);
3563 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3564 new String[] {account.name, account.type});
3565 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3566 if (accountId < 0) {
3567 Log.w(TAG, "insertAccountIntoDatabase: " + account
3568 + ", skipping the DB insert failed");
3569 return false;
3570 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003571 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003572 return true;
3573 }
3574
3575 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003576 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3577 userId = handleIncomingUser(userId);
3578 UserAccounts accounts = getUserAccounts(userId);
3579 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003580 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003581 final ContentValues values = new ContentValues();
3582 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003583 int r = db.update(
3584 TABLE_SHARED_ACCOUNTS,
3585 values,
3586 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3587 new String[] { account.name, account.type });
3588 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003589 int callingUid = getCallingUid();
3590 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3591 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003592 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003593 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003594 }
3595 return r > 0;
3596 }
3597
3598 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003599 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003600 return removeSharedAccountAsUser(account, userId, getCallingUid());
3601 }
3602
3603 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003604 userId = handleIncomingUser(userId);
3605 UserAccounts accounts = getUserAccounts(userId);
3606 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003607 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003608 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3609 new String[] {account.name, account.type});
3610 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003611 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3612 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003613 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003614 }
3615 return r > 0;
3616 }
3617
3618 @Override
3619 public Account[] getSharedAccountsAsUser(int userId) {
3620 userId = handleIncomingUser(userId);
3621 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003622 ArrayList<Account> accountList = new ArrayList<>();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003623 Cursor cursor = null;
3624 try {
3625 cursor = accounts.openHelper.getReadableDatabase()
3626 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3627 null, null, null, null, null);
3628 if (cursor != null && cursor.moveToFirst()) {
3629 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3630 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3631 do {
3632 accountList.add(new Account(cursor.getString(nameIndex),
3633 cursor.getString(typeIndex)));
3634 } while (cursor.moveToNext());
3635 }
3636 } finally {
3637 if (cursor != null) {
3638 cursor.close();
3639 }
3640 }
3641 Account[] accountArray = new Account[accountList.size()];
3642 accountList.toArray(accountArray);
3643 return accountArray;
3644 }
3645
3646 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003647 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003648 public Account[] getAccounts(String type, String opPackageName) {
3649 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003650 }
3651
Amith Yamasani27db4682013-03-30 17:07:47 -07003652 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003653 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003654 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003655 int callingUid = Binder.getCallingUid();
3656 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3657 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3658 + callingUid + " with uid=" + uid);
3659 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003660 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3661 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003662 }
3663
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003664 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003665 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003666 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3667 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003668 int packageUid = -1;
3669 try {
3670 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07003671 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3672 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003673 } catch (RemoteException re) {
3674 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3675 return new Account[0];
3676 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003677 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3678 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003679 }
3680
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003681 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003682 public void getAccountsByFeatures(
3683 IAccountManagerResponse response,
3684 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003685 String[] features,
3686 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003687 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003688 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3689 Log.v(TAG, "getAccounts: accountType " + type
3690 + ", response " + response
3691 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003692 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003693 + ", pid " + Binder.getCallingPid());
3694 }
Fred Quintana382601f2010-03-25 12:25:10 -07003695 if (response == null) throw new IllegalArgumentException("response is null");
3696 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003697 int userId = UserHandle.getCallingUserId();
3698
Svetoslavf3f02ac2015-09-08 14:36:35 -07003699 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3700 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003701 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003702 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003703 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003704 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3705 try {
3706 response.onResult(result);
3707 } catch (RemoteException e) {
3708 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3709 }
3710 return;
3711 }
Fred Quintana33269202009-04-20 16:05:10 -07003712 long identityToken = clearCallingIdentity();
3713 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003714 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003715 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003716 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003717 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003718 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003719 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08003720 Bundle result = new Bundle();
3721 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3722 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003723 return;
3724 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003725 new GetAccountsByTypeAndFeatureSession(
3726 userAccounts,
3727 response,
3728 type,
3729 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003730 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07003731 } finally {
3732 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07003733 }
3734 }
3735
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003736 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3737 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3738 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3739 try {
3740 if (cursor.moveToNext()) {
3741 return cursor.getLong(0);
3742 }
3743 return -1;
3744 } finally {
3745 cursor.close();
3746 }
3747 }
3748
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003749 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07003750 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003751 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07003752 try {
3753 if (cursor.moveToNext()) {
3754 return cursor.getLong(0);
3755 }
3756 return -1;
3757 } finally {
3758 cursor.close();
3759 }
3760 }
3761
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003762 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003763 Cursor cursor = db.query(CE_TABLE_EXTRAS, new String[]{EXTRAS_ID},
Fred Quintana60307342009-03-24 22:48:12 -07003764 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3765 new String[]{key}, null, null, null);
3766 try {
3767 if (cursor.moveToNext()) {
3768 return cursor.getLong(0);
3769 }
3770 return -1;
3771 } finally {
3772 cursor.close();
3773 }
3774 }
3775
Fred Quintanaa698f422009-04-08 19:14:54 -07003776 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07003777 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07003778 IAccountManagerResponse mResponse;
3779 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003780 final boolean mExpectActivityLaunch;
3781 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003782 final String mAccountName;
3783 // Indicates if we need to add auth details(like last credential time)
3784 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003785 // If set, we need to update the last authenticated time. This is
3786 // currently
3787 // used on
3788 // successful confirming credentials.
3789 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07003790
Fred Quintana33269202009-04-20 16:05:10 -07003791 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07003792 private int mNumRequestContinued = 0;
3793 private int mNumErrors = 0;
3794
Fred Quintana60307342009-03-24 22:48:12 -07003795 IAccountAuthenticator mAuthenticator = null;
3796
Fred Quintana8570f742010-02-18 10:32:54 -08003797 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003798 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003799
Amith Yamasani04e0d262012-02-14 11:50:53 -08003800 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003801 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3802 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003803 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3804 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3805 }
3806
3807 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3808 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3809 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07003810 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003811 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07003812 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08003813 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003814 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07003815 mResponse = response;
3816 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003817 mExpectActivityLaunch = expectActivityLaunch;
3818 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003819 mAccountName = accountName;
3820 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003821 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003822
Fred Quintanaa698f422009-04-08 19:14:54 -07003823 synchronized (mSessions) {
3824 mSessions.put(toString(), this);
3825 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003826 if (response != null) {
3827 try {
3828 response.asBinder().linkToDeath(this, 0 /* flags */);
3829 } catch (RemoteException e) {
3830 mResponse = null;
3831 binderDied();
3832 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003833 }
Fred Quintana60307342009-03-24 22:48:12 -07003834 }
3835
Fred Quintanaa698f422009-04-08 19:14:54 -07003836 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07003837 if (mResponse == null) {
3838 // this session has already been closed
3839 return null;
3840 }
Fred Quintana60307342009-03-24 22:48:12 -07003841 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07003842 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07003843 return response;
3844 }
3845
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003846 /**
3847 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
3848 * security policy.
3849 *
3850 * In particular we want to make sure that the Authenticator doesn't try to trick users
3851 * into launching aribtrary intents on the device via by tricking to click authenticator
3852 * supplied entries in the system Settings app.
3853 */
3854 protected void checkKeyIntent(
3855 int authUid,
3856 Intent intent) throws SecurityException {
3857 long bid = Binder.clearCallingIdentity();
3858 try {
3859 PackageManager pm = mContext.getPackageManager();
3860 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3861 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
3862 int targetUid = targetActivityInfo.applicationInfo.uid;
3863 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid)) {
3864 String pkgName = targetActivityInfo.packageName;
3865 String activityName = targetActivityInfo.name;
3866 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
3867 + "does not share a signature with the supplying authenticator (%s).";
3868 throw new SecurityException(
3869 String.format(tmpl, activityName, pkgName, mAccountType));
3870 }
3871 } finally {
3872 Binder.restoreCallingIdentity(bid);
3873 }
3874 }
3875
Fred Quintanaa698f422009-04-08 19:14:54 -07003876 private void close() {
3877 synchronized (mSessions) {
3878 if (mSessions.remove(toString()) == null) {
3879 // the session was already closed, so bail out now
3880 return;
3881 }
3882 }
3883 if (mResponse != null) {
3884 // stop listening for response deaths
3885 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3886
3887 // clear this so that we don't accidentally send any further results
3888 mResponse = null;
3889 }
3890 cancelTimeout();
3891 unbind();
3892 }
3893
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003894 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003895 public void binderDied() {
3896 mResponse = null;
3897 close();
3898 }
3899
3900 protected String toDebugString() {
3901 return toDebugString(SystemClock.elapsedRealtime());
3902 }
3903
3904 protected String toDebugString(long now) {
3905 return "Session: expectLaunch " + mExpectActivityLaunch
3906 + ", connected " + (mAuthenticator != null)
3907 + ", stats (" + mNumResults + "/" + mNumRequestContinued
3908 + "/" + mNumErrors + ")"
3909 + ", lifetime " + ((now - mCreationTime) / 1000.0);
3910 }
3911
Fred Quintana60307342009-03-24 22:48:12 -07003912 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003913 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3914 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3915 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003916 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003917 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003918 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003919 }
3920 }
3921
3922 private void unbind() {
3923 if (mAuthenticator != null) {
3924 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003925 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003926 }
3927 }
3928
Fred Quintana60307342009-03-24 22:48:12 -07003929 public void cancelTimeout() {
3930 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3931 }
3932
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003933 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003934 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003935 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003936 try {
3937 run();
3938 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003939 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003940 "remote exception");
3941 }
Fred Quintana60307342009-03-24 22:48:12 -07003942 }
3943
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003944 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003945 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003946 mAuthenticator = null;
3947 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003948 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003949 try {
3950 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3951 "disconnected");
3952 } catch (RemoteException e) {
3953 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3954 Log.v(TAG, "Session.onServiceDisconnected: "
3955 + "caught RemoteException while responding", e);
3956 }
3957 }
Fred Quintana60307342009-03-24 22:48:12 -07003958 }
3959 }
3960
Fred Quintanab839afc2009-10-14 15:57:28 -07003961 public abstract void run() throws RemoteException;
3962
Fred Quintana60307342009-03-24 22:48:12 -07003963 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003964 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003965 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003966 try {
3967 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3968 "timeout");
3969 } catch (RemoteException e) {
3970 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3971 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3972 e);
3973 }
3974 }
Fred Quintana60307342009-03-24 22:48:12 -07003975 }
3976 }
3977
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003978 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003979 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003980 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07003981 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003982 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003983 if (result != null) {
3984 boolean isSuccessfulConfirmCreds = result.getBoolean(
3985 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003986 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003987 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3988 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003989 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003990 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3991 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003992 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003993 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003994 if (needUpdate || mAuthDetailsRequired) {
3995 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3996 if (needUpdate && accountPresent) {
3997 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3998 }
3999 if (mAuthDetailsRequired) {
4000 long lastAuthenticatedTime = -1;
4001 if (accountPresent) {
4002 lastAuthenticatedTime = DatabaseUtils.longForQuery(
4003 mAccounts.openHelper.getReadableDatabase(),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004004 "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4005 + " FROM " +
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004006 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
4007 + ACCOUNTS_TYPE + "=?",
4008 new String[] {
4009 mAccountName, mAccountType
4010 });
4011 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004012 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004013 lastAuthenticatedTime);
4014 }
4015 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004016 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004017 if (result != null
4018 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004019 checkKeyIntent(
4020 Binder.getCallingUid(),
4021 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004022 }
4023 if (result != null
4024 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004025 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4026 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004027 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4028 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004029 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4030 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004031 }
Fred Quintana60307342009-03-24 22:48:12 -07004032 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004033 IAccountManagerResponse response;
4034 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004035 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004036 response = mResponse;
4037 } else {
4038 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004039 }
Fred Quintana60307342009-03-24 22:48:12 -07004040 if (response != null) {
4041 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004042 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004043 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4044 Log.v(TAG, getClass().getSimpleName()
4045 + " calling onError() on response " + response);
4046 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004047 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004048 "null bundle returned");
4049 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004050 if (mStripAuthTokenFromResult) {
4051 result.remove(AccountManager.KEY_AUTHTOKEN);
4052 }
Fred Quintana56285a62010-12-02 14:20:51 -08004053 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4054 Log.v(TAG, getClass().getSimpleName()
4055 + " calling onResult() on response " + response);
4056 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004057 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4058 (intent == null)) {
4059 // All AccountManager error codes are greater than 0
4060 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4061 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4062 } else {
4063 response.onResult(result);
4064 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004065 }
Fred Quintana60307342009-03-24 22:48:12 -07004066 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004067 // if the caller is dead then there is no one to care about remote exceptions
4068 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4069 Log.v(TAG, "failure while notifying response", e);
4070 }
Fred Quintana60307342009-03-24 22:48:12 -07004071 }
4072 }
4073 }
Fred Quintana60307342009-03-24 22:48:12 -07004074
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004075 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004076 public void onRequestContinued() {
4077 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004078 }
4079
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004080 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004081 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004082 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004083 IAccountManagerResponse response = getResponseAndClose();
4084 if (response != null) {
4085 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004086 Log.v(TAG, getClass().getSimpleName()
4087 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004088 }
4089 try {
4090 response.onError(errorCode, errorMessage);
4091 } catch (RemoteException e) {
4092 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4093 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4094 }
4095 }
4096 } else {
4097 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4098 Log.v(TAG, "Session.onError: already closed");
4099 }
Fred Quintana60307342009-03-24 22:48:12 -07004100 }
4101 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004102
4103 /**
4104 * find the component name for the authenticator and initiate a bind
4105 * if no authenticator or the bind fails then return false, otherwise return true
4106 */
4107 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004108 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4109 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4110 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004111 if (authenticatorInfo == null) {
4112 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4113 Log.v(TAG, "there is no authenticator for " + authenticatorType
4114 + ", bailing out");
4115 }
4116 return false;
4117 }
4118
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004119 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004120 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004121 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4122 + " which isn't encryption aware");
4123 return false;
4124 }
4125
Fred Quintanab839afc2009-10-14 15:57:28 -07004126 Intent intent = new Intent();
4127 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4128 intent.setComponent(authenticatorInfo.componentName);
4129 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4130 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4131 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004132 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004133 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004134 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4135 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4136 }
4137 return false;
4138 }
4139
Fred Quintanab839afc2009-10-14 15:57:28 -07004140 return true;
4141 }
Fred Quintana60307342009-03-24 22:48:12 -07004142 }
4143
4144 private class MessageHandler extends Handler {
4145 MessageHandler(Looper looper) {
4146 super(looper);
4147 }
Costin Manolache3348f142009-09-29 18:58:36 -07004148
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004149 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004150 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004151 switch (msg.what) {
4152 case MESSAGE_TIMED_OUT:
4153 Session session = (Session)msg.obj;
4154 session.onTimedOut();
4155 break;
4156
Amith Yamasani5be347b2013-03-31 17:44:31 -07004157 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004158 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004159 break;
4160
Fred Quintana60307342009-03-24 22:48:12 -07004161 default:
4162 throw new IllegalStateException("unhandled message: " + msg.what);
4163 }
4164 }
4165 }
4166
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004167 @VisibleForTesting
4168 String getPreNDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07004169 File systemDir = Environment.getDataSystemDirectory();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004170 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
4171 PRE_N_DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004172 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07004173 // Migrate old file, if it exists, to the new location.
4174 // Make sure the new file doesn't already exist. A dummy file could have been
4175 // accidentally created in the old location, causing the new one to become corrupted
4176 // as well.
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004177 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07004178 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07004179 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07004180 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07004181 if (!userDir.exists()) {
4182 if (!userDir.mkdirs()) {
4183 throw new IllegalStateException("User dir cannot be created: " + userDir);
4184 }
4185 }
4186 if (!oldFile.renameTo(databaseFile)) {
4187 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
4188 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004189 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004190 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004191 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08004192 }
4193
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004194 @VisibleForTesting
4195 String getDeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004196 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
4197 DE_DATABASE_NAME);
4198 return databaseFile.getPath();
4199 }
4200
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004201 @VisibleForTesting
4202 String getCeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004203 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4204 CE_DATABASE_NAME);
4205 return databaseFile.getPath();
4206 }
4207
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004208 private static class DebugDbHelper{
4209 private DebugDbHelper() {
4210 }
4211
4212 private static String TABLE_DEBUG = "debug_table";
4213
4214 // Columns for the table
4215 private static String ACTION_TYPE = "action_type";
4216 private static String TIMESTAMP = "time";
4217 private static String CALLER_UID = "caller_uid";
4218 private static String TABLE_NAME = "table_name";
4219 private static String KEY = "primary_key";
4220
4221 // These actions correspond to the occurrence of real actions. Since
4222 // these are called by the authenticators, the uid associated will be
4223 // of the authenticator.
4224 private static String ACTION_SET_PASSWORD = "action_set_password";
4225 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4226 private static String ACTION_ACCOUNT_ADD = "action_account_add";
4227 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004228 private static String ACTION_ACCOUNT_REMOVE_DE = "action_account_remove_de";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004229 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4230 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4231
4232 // These actions don't necessarily correspond to any action on
4233 // accountDb taking place. As an example, there might be a request for
4234 // addingAccount, which might not lead to addition of account on grounds
4235 // of bad authentication. We will still be logging it to keep track of
4236 // who called.
4237 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4238 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004239 private static String ACTION_SYNC_DE_CE_ACCOUNTS = "action_sync_de_ce_accounts";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004240
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004241 //This action doesn't add account to accountdb. Account is only
4242 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08004243 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004244 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4245 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08004246
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004247 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4248
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004249 private static void createDebugTable(SQLiteDatabase db) {
4250 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4251 + ACCOUNTS_ID + " INTEGER,"
4252 + ACTION_TYPE + " TEXT NOT NULL, "
4253 + TIMESTAMP + " DATETIME,"
4254 + CALLER_UID + " INTEGER NOT NULL,"
4255 + TABLE_NAME + " TEXT NOT NULL,"
4256 + KEY + " INTEGER PRIMARY KEY)");
4257 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4258 }
4259 }
4260
4261 private void logRecord(UserAccounts accounts, String action, String tableName) {
4262 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4263 logRecord(db, action, tableName, -1, accounts);
4264 }
4265
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004266 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4267 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4268 logRecord(db, action, tableName, -1, accounts, uid);
4269 }
4270
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004271 /*
4272 * This function receives an opened writable database.
4273 */
4274 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4275 UserAccounts userAccount) {
4276 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4277 }
4278
4279 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004280 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004281 */
4282 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4283 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004284
4285 class LogRecordTask implements Runnable {
4286 private final String action;
4287 private final String tableName;
4288 private final long accountId;
4289 private final UserAccounts userAccount;
4290 private final int callingUid;
4291 private final long userDebugDbInsertionPoint;
4292
4293 LogRecordTask(final String action,
4294 final String tableName,
4295 final long accountId,
4296 final UserAccounts userAccount,
4297 final int callingUid,
4298 final long userDebugDbInsertionPoint) {
4299 this.action = action;
4300 this.tableName = tableName;
4301 this.accountId = accountId;
4302 this.userAccount = userAccount;
4303 this.callingUid = callingUid;
4304 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
4305 }
4306
4307 public void run() {
4308 SQLiteStatement logStatement = userAccount.statementForLogging;
4309 logStatement.bindLong(1, accountId);
4310 logStatement.bindString(2, action);
4311 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4312 logStatement.bindLong(4, callingUid);
4313 logStatement.bindString(5, tableName);
4314 logStatement.bindLong(6, userDebugDbInsertionPoint);
4315 logStatement.execute();
4316 logStatement.clearBindings();
4317 }
4318 }
4319
4320 mLogRecordRunnables.add(new LogRecordTask(action, tableName, accountId, userAccount,
4321 callingUid, userAccount.debugDbInsertionPoint));
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004322 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4323 % MAX_DEBUG_DB_SIZE;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004324
4325
4326 if(mLogRecordThread == null || !mLogRecordThread.isAlive()) {
4327 mLogRecordThread = new Thread(new Runnable() {
4328 public void run() {
4329 while(mLogRecordRunnables.size() > 0) {
4330 mLogRecordRunnables.pollFirst().run();
4331 }
4332 }
4333 });
4334 mLogRecordThread.start();
4335 }
4336
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004337 }
4338
4339 /*
4340 * This should only be called once to compile the sql statement for logging
4341 * and to find the insertion point.
4342 */
4343 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4344 UserAccounts userAccount) {
4345 // Initialize the count if not done earlier.
4346 int size = (int) getDebugTableRowCount(db);
4347 if (size >= MAX_DEBUG_DB_SIZE) {
4348 // Table is full, and we need to find the point where to insert.
4349 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4350 } else {
4351 userAccount.debugDbInsertionPoint = size;
4352 }
4353 compileSqlStatementForLogging(db, userAccount);
4354 }
4355
4356 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4357 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4358 + " VALUES (?,?,?,?,?,?)";
4359 userAccount.statementForLogging = db.compileStatement(sql);
4360 }
4361
4362 private long getDebugTableRowCount(SQLiteDatabase db) {
4363 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4364 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4365 }
4366
4367 /*
4368 * Finds the row key where the next insertion should take place. This should
4369 * be invoked only if the table has reached its full capacity.
4370 */
4371 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4372 // This query finds the smallest timestamp value (and if 2 records have
4373 // same timestamp, the choose the lower id).
4374 String queryCountDebugDbRows = new StringBuilder()
4375 .append("SELECT ").append(DebugDbHelper.KEY)
4376 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4377 .append(" ORDER BY ")
4378 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4379 .append(" LIMIT 1")
4380 .toString();
4381 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4382 }
4383
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004384 static class PreNDatabaseHelper extends SQLiteOpenHelper {
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004385 private final Context mContext;
4386 private final int mUserId;
4387
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004388 public PreNDatabaseHelper(Context context, int userId, String preNDatabaseName) {
4389 super(context, preNDatabaseName, null, PRE_N_DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004390 mContext = context;
4391 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004392 }
4393
4394 @Override
4395 public void onCreate(SQLiteDatabase db) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004396 // We use PreNDatabaseHelper only if pre-N db exists
4397 throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004398 }
4399
Amith Yamasani67df64b2012-12-14 12:09:36 -08004400 private void createSharedAccountsTable(SQLiteDatabase db) {
4401 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4402 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4403 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4404 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4405 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4406 }
4407
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004408 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4409 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4410 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4411 }
4412
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004413 private void addOldAccountNameColumn(SQLiteDatabase db) {
4414 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4415 }
4416
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004417 private void addDebugTable(SQLiteDatabase db) {
4418 DebugDbHelper.createDebugTable(db);
4419 }
4420
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004421 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004422 db.execSQL(""
4423 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4424 + " BEGIN"
4425 + " DELETE FROM " + TABLE_AUTHTOKENS
4426 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4427 + " DELETE FROM " + TABLE_EXTRAS
4428 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004429 + " DELETE FROM " + TABLE_GRANTS
4430 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004431 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004432 }
4433
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004434 private void createGrantsTable(SQLiteDatabase db) {
4435 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4436 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4437 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4438 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4439 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4440 + "," + GRANTS_GRANTEE_UID + "))");
4441 }
4442
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004443 private void populateMetaTableWithAuthTypeAndUID(
4444 SQLiteDatabase db,
4445 Map<String, Integer> authTypeAndUIDMap) {
4446 Iterator<Entry<String, Integer>> iterator = authTypeAndUIDMap.entrySet().iterator();
4447 while (iterator.hasNext()) {
4448 Entry<String, Integer> entry = iterator.next();
4449 ContentValues values = new ContentValues();
4450 values.put(META_KEY,
4451 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
4452 values.put(META_VALUE, entry.getValue());
4453 db.insert(TABLE_META, null, values);
4454 }
4455 }
4456
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004457 /**
4458 * Pre-N database may need an upgrade before splitting
4459 */
Fred Quintana60307342009-03-24 22:48:12 -07004460 @Override
4461 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004462 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004463
Fred Quintanaa698f422009-04-08 19:14:54 -07004464 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004465 // no longer need to do anything since the work is done
4466 // when upgrading from version 2
4467 oldVersion++;
4468 }
4469
4470 if (oldVersion == 2) {
4471 createGrantsTable(db);
4472 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4473 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004474 oldVersion++;
4475 }
Costin Manolache3348f142009-09-29 18:58:36 -07004476
4477 if (oldVersion == 3) {
4478 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4479 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4480 oldVersion++;
4481 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004482
4483 if (oldVersion == 4) {
4484 createSharedAccountsTable(db);
4485 oldVersion++;
4486 }
4487
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004488 if (oldVersion == 5) {
4489 addOldAccountNameColumn(db);
4490 oldVersion++;
4491 }
4492
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004493 if (oldVersion == 6) {
4494 addLastSuccessfullAuthenticatedTimeColumn(db);
4495 oldVersion++;
4496 }
4497
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004498 if (oldVersion == 7) {
4499 addDebugTable(db);
4500 oldVersion++;
4501 }
4502
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004503 if (oldVersion == 8) {
4504 populateMetaTableWithAuthTypeAndUID(
4505 db,
4506 AccountManagerService.getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
4507 oldVersion++;
4508 }
4509
Amith Yamasani67df64b2012-12-14 12:09:36 -08004510 if (oldVersion != newVersion) {
4511 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4512 }
Fred Quintana60307342009-03-24 22:48:12 -07004513 }
4514
4515 @Override
4516 public void onOpen(SQLiteDatabase db) {
4517 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4518 }
4519 }
4520
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004521 static class DeDatabaseHelper extends SQLiteOpenHelper {
4522
4523 private final int mUserId;
4524 private volatile boolean mCeAttached;
4525
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004526 private DeDatabaseHelper(Context context, int userId, String deDatabaseName) {
4527 super(context, deDatabaseName, null, DE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004528 mUserId = userId;
4529 }
4530
4531 /**
4532 * This call needs to be made while the mCacheLock is held. The way to
4533 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4534 * @param db The database.
4535 */
4536 @Override
4537 public void onCreate(SQLiteDatabase db) {
4538 Log.i(TAG, "Creating DE database for user " + mUserId);
4539 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4540 + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4541 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4542 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4543 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4544 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4545 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4546
4547 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4548 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4549 + META_VALUE + " TEXT)");
4550
4551 createGrantsTable(db);
4552 createSharedAccountsTable(db);
4553 createAccountsDeletionTrigger(db);
4554 DebugDbHelper.createDebugTable(db);
4555 }
4556
4557 private void createSharedAccountsTable(SQLiteDatabase db) {
4558 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4559 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4560 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4561 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4562 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4563 }
4564
4565 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4566 db.execSQL(""
4567 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4568 + " BEGIN"
4569 + " DELETE FROM " + TABLE_GRANTS
4570 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4571 + " END");
4572 }
4573
4574 private void createGrantsTable(SQLiteDatabase db) {
4575 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4576 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4577 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4578 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4579 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4580 + "," + GRANTS_GRANTEE_UID + "))");
4581 }
4582
4583 @Override
4584 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4585 Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4586
4587 if (oldVersion != newVersion) {
4588 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4589 }
4590 }
4591
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004592 public void attachCeDatabase(File ceDbFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004593 SQLiteDatabase db = getWritableDatabase();
4594 db.execSQL("ATTACH DATABASE '" + ceDbFile.getPath()+ "' AS ceDb");
4595 mCeAttached = true;
4596 }
4597
4598 public boolean isCeDatabaseAttached() {
4599 return mCeAttached;
4600 }
4601
4602
4603 public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
4604 if(!mCeAttached) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004605 Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user " + mUserId
4606 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004607 }
4608 return super.getReadableDatabase();
4609 }
4610
4611 public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
4612 if(!mCeAttached) {
4613 Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004614 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004615 }
4616 return super.getWritableDatabase();
4617 }
4618
4619 @Override
4620 public void onOpen(SQLiteDatabase db) {
4621 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
4622 }
4623
4624 private void migratePreNDbToDe(File preNDbFile) {
4625 Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
4626 SQLiteDatabase db = getWritableDatabase();
4627 db.execSQL("ATTACH DATABASE '" + preNDbFile.getPath() + "' AS preNDb");
4628 db.beginTransaction();
4629 // Copy accounts fields
4630 db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
4631 + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4632 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4633 + ") "
4634 + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4635 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4636 + " FROM preNDb." + TABLE_ACCOUNTS);
4637 // Copy SHARED_ACCOUNTS
4638 db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
4639 + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
4640 "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4641 + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
4642 // Copy DEBUG_TABLE
4643 db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
4644 + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4645 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4646 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
4647 "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4648 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4649 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
4650 + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
4651 // Copy GRANTS
4652 db.execSQL("INSERT INTO " + TABLE_GRANTS
4653 + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4654 + GRANTS_GRANTEE_UID + ") " +
4655 "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4656 + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
4657 // Copy META
4658 db.execSQL("INSERT INTO " + TABLE_META
4659 + "(" + META_KEY + "," + META_VALUE + ") "
4660 + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
4661 db.setTransactionSuccessful();
4662 db.endTransaction();
4663
4664 db.execSQL("DETACH DATABASE preNDb");
4665 }
4666
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004667 static DeDatabaseHelper create(
4668 Context context,
4669 int userId,
4670 File preNDatabaseFile,
4671 File deDatabaseFile) {
4672 boolean newDbExists = deDatabaseFile.exists();
4673 DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId,
4674 deDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004675 // If the db just created, and there is a legacy db, migrate it
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004676 if (!newDbExists && preNDatabaseFile.exists()) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004677 // Migrate legacy db to the latest version - PRE_N_DATABASE_VERSION
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004678 PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId,
4679 preNDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004680 // Open the database to force upgrade if required
4681 preNDatabaseHelper.getWritableDatabase();
4682 preNDatabaseHelper.close();
4683 // Move data without SPII to DE
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004684 deDatabaseHelper.migratePreNDbToDe(preNDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004685 }
4686 return deDatabaseHelper;
4687 }
4688 }
4689
4690 static class CeDatabaseHelper extends SQLiteOpenHelper {
4691
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004692 public CeDatabaseHelper(Context context, String ceDatabaseName) {
4693 super(context, ceDatabaseName, null, CE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004694 }
4695
4696 /**
4697 * This call needs to be made while the mCacheLock is held.
4698 * @param db The database.
4699 */
4700 @Override
4701 public void onCreate(SQLiteDatabase db) {
4702 Log.i(TAG, "Creating CE database " + getDatabaseName());
4703 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4704 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4705 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4706 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4707 + ACCOUNTS_PASSWORD + " TEXT, "
4708 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4709
4710 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
4711 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4712 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4713 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
4714 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
4715 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
4716
4717 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
4718 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4719 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
4720 + EXTRAS_KEY + " TEXT NOT NULL, "
4721 + EXTRAS_VALUE + " TEXT, "
4722 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
4723
4724 createAccountsDeletionTrigger(db);
4725 }
4726
4727 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4728 db.execSQL(""
4729 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4730 + " BEGIN"
4731 + " DELETE FROM " + TABLE_AUTHTOKENS
4732 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4733 + " DELETE FROM " + TABLE_EXTRAS
4734 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4735 + " END");
4736 }
4737
4738 @Override
4739 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4740 Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
4741
4742 if (oldVersion == 9) {
4743 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4744 Log.v(TAG, "onUpgrade upgrading to v10");
4745 }
4746 db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
4747 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
4748 // Recreate the trigger, since the old one references the table to be removed
4749 db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
4750 createAccountsDeletionTrigger(db);
4751 db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
4752 db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
4753 oldVersion ++;
4754 }
4755
4756 if (oldVersion != newVersion) {
4757 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4758 }
4759 }
4760
4761 @Override
4762 public void onOpen(SQLiteDatabase db) {
4763 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
4764 }
4765
4766 static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
4767 String type) {
4768 Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
4769 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
4770 new String[]{name, type}, null, null, null);
4771 try {
4772 if (cursor.moveToNext()) {
4773 return cursor.getString(0);
4774 }
4775 return null;
4776 } finally {
4777 cursor.close();
4778 }
4779 }
4780
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004781 static List<Account> findCeAccountsNotInDe(SQLiteDatabase db) {
4782 // Select accounts from CE that do not exist in DE
4783 Cursor cursor = db.rawQuery(
4784 "SELECT " + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4785 + " FROM " + CE_TABLE_ACCOUNTS
4786 + " WHERE NOT EXISTS "
4787 + " (SELECT " + ACCOUNTS_ID + " FROM " + TABLE_ACCOUNTS
4788 + " WHERE " + ACCOUNTS_ID + "=" + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
4789 + " )", null);
4790 try {
4791 List<Account> accounts = new ArrayList<>(cursor.getCount());
4792 while (cursor.moveToNext()) {
4793 String accountName = cursor.getString(0);
4794 String accountType = cursor.getString(1);
4795 accounts.add(new Account(accountName, accountType));
4796 }
4797 return accounts;
4798 } finally {
4799 cursor.close();
4800 }
4801 }
4802
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004803 /**
4804 * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
4805 * it also performs migration to the new CE database.
4806 * @param context
4807 * @param userId id of the user where the database is located
4808 */
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004809 static CeDatabaseHelper create(
4810 Context context,
4811 int userId,
4812 File preNDatabaseFile,
4813 File ceDatabaseFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004814 boolean newDbExists = ceDatabaseFile.exists();
4815 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4816 Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004817 + preNDatabaseFile.exists() + " newDbExists=" + newDbExists);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004818 }
4819 boolean removeOldDb = false;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004820 if (!newDbExists && preNDatabaseFile.exists()) {
4821 removeOldDb = migratePreNDbToCe(preNDatabaseFile, ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004822 }
4823 // Try to open and upgrade if necessary
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004824 CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, ceDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004825 ceHelper.getWritableDatabase();
4826 ceHelper.close();
4827 if (removeOldDb) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004828 Slog.i(TAG, "Migration complete - removing pre-N db " + preNDatabaseFile);
4829 if (!SQLiteDatabase.deleteDatabase(preNDatabaseFile)) {
4830 Slog.e(TAG, "Cannot remove pre-N db " + preNDatabaseFile);
4831 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004832 }
4833 return ceHelper;
4834 }
4835
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004836 private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004837 Slog.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004838 try {
4839 FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
4840 } catch (IOException e) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004841 Slog.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004842 // Try to remove potentially damaged file if I/O error occurred
4843 deleteDbFileWarnIfFailed(ceDbFile);
4844 return false;
4845 }
4846 return true;
4847 }
4848 }
4849
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004850 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004851 return asBinder();
4852 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004853
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004854 /**
4855 * Searches array of arguments for the specified string
4856 * @param args array of argument strings
4857 * @param value value to search for
4858 * @return true if the value is contained in the array
4859 */
4860 private static boolean scanArgs(String[] args, String value) {
4861 if (args != null) {
4862 for (String arg : args) {
4863 if (value.equals(arg)) {
4864 return true;
4865 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004866 }
4867 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004868 return false;
4869 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004870
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004871 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004872 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07004873 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4874 != PackageManager.PERMISSION_GRANTED) {
4875 fout.println("Permission Denial: can't dump AccountsManager from from pid="
4876 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4877 + " without permission " + android.Manifest.permission.DUMP);
4878 return;
4879 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004880 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004881 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004882
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004883 final List<UserInfo> users = getUserManager().getUsers();
4884 for (UserInfo user : users) {
4885 ipw.println("User " + user + ":");
4886 ipw.increaseIndent();
4887 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4888 ipw.println();
4889 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08004890 }
4891 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004892
Amith Yamasani04e0d262012-02-14 11:50:53 -08004893 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4894 String[] args, boolean isCheckinRequest) {
4895 synchronized (userAccounts.cacheLock) {
4896 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004897
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004898 if (isCheckinRequest) {
4899 // This is a checkin request. *Only* upload the account types and the count of each.
4900 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4901 null, null, ACCOUNTS_TYPE, null, null);
4902 try {
4903 while (cursor.moveToNext()) {
4904 // print type,count
4905 fout.println(cursor.getString(0) + "," + cursor.getString(1));
4906 }
4907 } finally {
4908 if (cursor != null) {
4909 cursor.close();
4910 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004911 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004912 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004913 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07004914 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004915 fout.println("Accounts: " + accounts.length);
4916 for (Account account : accounts) {
4917 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004918 }
Fred Quintana307da1a2010-01-21 14:24:20 -08004919
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004920 // Add debug information.
4921 fout.println();
4922 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4923 null, null, null, null, DebugDbHelper.TIMESTAMP);
4924 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4925 fout.println("Accounts History");
4926 try {
4927 while (cursor.moveToNext()) {
4928 // print type,count
4929 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4930 cursor.getString(2) + "," + cursor.getString(3) + ","
4931 + cursor.getString(4) + "," + cursor.getString(5));
4932 }
4933 } finally {
4934 cursor.close();
4935 }
4936
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004937 fout.println();
4938 synchronized (mSessions) {
4939 final long now = SystemClock.elapsedRealtime();
4940 fout.println("Active Sessions: " + mSessions.size());
4941 for (Session session : mSessions.values()) {
4942 fout.println(" " + session.toDebugString(now));
4943 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004944 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004945
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004946 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004947 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004948 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004949 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004950 }
4951
Amith Yamasani04e0d262012-02-14 11:50:53 -08004952 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07004953 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004954 long identityToken = clearCallingIdentity();
4955 try {
4956 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4957 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4958 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004959
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004960 if (intent.getComponent() != null &&
4961 GrantCredentialsPermissionActivity.class.getName().equals(
4962 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004963 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004964 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004965 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004966 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004967 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004968 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07004969 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004970 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004971 Notification n = new Notification.Builder(contextForUser)
4972 .setWhen(0)
4973 .setSmallIcon(android.R.drawable.stat_sys_warning)
4974 .setColor(contextForUser.getColor(
4975 com.android.internal.R.color.system_notification_accent_color))
4976 .setContentTitle(String.format(notificationTitleFormat, account.name))
4977 .setContentText(message)
4978 .setContentIntent(PendingIntent.getActivityAsUser(
4979 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4980 null, user))
4981 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004982 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004983 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004984 } finally {
4985 restoreCallingIdentity(identityToken);
4986 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004987 }
4988
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004989 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004990 protected void installNotification(final int notificationId, final Notification n,
4991 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08004992 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004993 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08004994 }
4995
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004996 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004997 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004998 long identityToken = clearCallingIdentity();
4999 try {
5000 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005001 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005002 } finally {
5003 restoreCallingIdentity(identityToken);
5004 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005005 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005006
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005007 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5008 for (String perm : permissions) {
5009 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5010 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5011 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5012 }
5013 final int opCode = AppOpsManager.permissionToOpCode(perm);
5014 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5015 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5016 return true;
5017 }
5018 }
5019 }
5020 return false;
5021 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005022
Amith Yamasani67df64b2012-12-14 12:09:36 -08005023 private int handleIncomingUser(int userId) {
5024 try {
5025 return ActivityManagerNative.getDefault().handleIncomingUser(
5026 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5027 } catch (RemoteException re) {
5028 // Shouldn't happen, local.
5029 }
5030 return userId;
5031 }
5032
Christopher Tateccbf84f2013-05-08 15:25:41 -07005033 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005034 final int callingUserId = UserHandle.getUserId(callingUid);
5035
5036 final PackageManager userPackageManager;
5037 try {
5038 userPackageManager = mContext.createPackageContextAsUser(
5039 "android", 0, new UserHandle(callingUserId)).getPackageManager();
5040 } catch (NameNotFoundException e) {
5041 return false;
5042 }
5043
5044 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005045 for (String name : packages) {
5046 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005047 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08005048 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08005049 && (packageInfo.applicationInfo.privateFlags
5050 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07005051 return true;
5052 }
5053 } catch (PackageManager.NameNotFoundException e) {
5054 return false;
5055 }
5056 }
5057 return false;
5058 }
5059
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005060 private boolean permissionIsGranted(
5061 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07005062 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07005063 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005064 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07005065 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08005066 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005067 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5068 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08005069 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005070 + ": is authenticator? " + fromAuthenticator
5071 + ", has explicit permission? " + hasExplicitGrants);
5072 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07005073 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005074 }
5075
Svetoslavf3f02ac2015-09-08 14:36:35 -07005076 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5077 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005078 if (accountType == null) {
5079 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005080 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005081 return getTypesVisibleToCaller(callingUid, userId,
5082 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005083 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005084 }
5085
5086 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5087 if (accountType == null) {
5088 return false;
5089 } else {
5090 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5091 }
5092 }
5093
Svetoslavf3f02ac2015-09-08 14:36:35 -07005094 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5095 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005096 boolean isPermitted =
5097 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
5098 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005099 return getTypesForCaller(callingUid, userId, isPermitted);
5100 }
5101
5102 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
5103 return getTypesForCaller(callingUid, userId, false);
5104 }
5105
5106 private List<String> getTypesForCaller(
5107 int callingUid, int userId, boolean isOtherwisePermitted) {
5108 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005109 long identityToken = Binder.clearCallingIdentity();
5110 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5111 try {
5112 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5113 } finally {
5114 Binder.restoreCallingIdentity(identityToken);
5115 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005116 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005117 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005118 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5119 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
5120 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005121 }
5122 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005123 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005124 }
5125
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005126 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5127 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5128 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5129 if (account.name.equals(accountName)) {
5130 return true;
5131 }
5132 }
5133 }
5134 return false;
5135 }
5136
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005137 private static void checkManageUsersPermission(String message) {
5138 if (ActivityManager.checkComponentPermission(
5139 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5140 != PackageManager.PERMISSION_GRANTED) {
5141 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5142 }
5143 }
5144
Amith Yamasani04e0d262012-02-14 11:50:53 -08005145 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5146 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07005147 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005148 return true;
5149 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005150 UserAccounts accounts = getUserAccountsForCaller();
5151 synchronized (accounts.cacheLock) {
5152 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
5153 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005154 account.name, account.type};
5155 final boolean permissionGranted =
5156 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
5157 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5158 // TODO: Skip this check when running automated tests. Replace this
5159 // with a more general solution.
5160 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08005161 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005162 + " but ignoring since device is in test harness.");
5163 return true;
5164 }
5165 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005166 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005167 }
5168
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005169 private boolean isSystemUid(int callingUid) {
5170 String[] packages = null;
5171 long ident = Binder.clearCallingIdentity();
5172 try {
5173 packages = mPackageManager.getPackagesForUid(callingUid);
5174 } finally {
5175 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005176 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005177 if (packages != null) {
5178 for (String name : packages) {
5179 try {
5180 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5181 if (packageInfo != null
5182 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5183 != 0) {
5184 return true;
5185 }
5186 } catch (PackageManager.NameNotFoundException e) {
5187 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5188 }
5189 }
5190 } else {
5191 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005192 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005193 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005194 }
5195
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005196 /** Succeeds if any of the specified permissions are granted. */
5197 private void checkReadAccountsPermitted(
5198 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005199 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005200 int userId,
5201 String opPackageName) {
5202 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005203 String msg = String.format(
5204 "caller uid %s cannot access %s accounts",
5205 callingUid,
5206 accountType);
5207 Log.w(TAG, " " + msg);
5208 throw new SecurityException(msg);
5209 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005210 }
5211
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005212 private boolean canUserModifyAccounts(int userId, int callingUid) {
5213 // the managing app can always modify accounts
5214 if (isProfileOwner(callingUid)) {
5215 return true;
5216 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005217 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5218 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5219 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005220 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005221 return true;
5222 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005223
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005224 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5225 // the managing app can always modify accounts
5226 if (isProfileOwner(callingUid)) {
5227 return true;
5228 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005229 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5230 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005231 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005232 if (typesArray == null) {
5233 return true;
5234 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005235 for (String forbiddenType : typesArray) {
5236 if (forbiddenType.equals(accountType)) {
5237 return false;
5238 }
5239 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005240 return true;
5241 }
5242
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005243 private boolean isProfileOwner(int uid) {
5244 final DevicePolicyManagerInternal dpmi =
5245 LocalServices.getService(DevicePolicyManagerInternal.class);
5246 return (dpmi != null)
5247 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5248 }
5249
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005250 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005251 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5252 throws RemoteException {
5253 final int callingUid = getCallingUid();
5254
Amith Yamasani27db4682013-03-30 17:07:47 -07005255 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005256 throw new SecurityException();
5257 }
5258
5259 if (value) {
5260 grantAppPermission(account, authTokenType, uid);
5261 } else {
5262 revokeAppPermission(account, authTokenType, uid);
5263 }
5264 }
5265
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005266 /**
5267 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5268 * <p>
5269 * Although this is public it can only be accessed via the AccountManagerService object
5270 * which is in the system. This means we don't need to protect it with permissions.
5271 * @hide
5272 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005273 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005274 if (account == null || authTokenType == null) {
5275 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005276 return;
5277 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005278 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005279 synchronized (accounts.cacheLock) {
5280 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005281 db.beginTransaction();
5282 try {
5283 long accountId = getAccountIdLocked(db, account);
5284 if (accountId >= 0) {
5285 ContentValues values = new ContentValues();
5286 values.put(GRANTS_ACCOUNTS_ID, accountId);
5287 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
5288 values.put(GRANTS_GRANTEE_UID, uid);
5289 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
5290 db.setTransactionSuccessful();
5291 }
5292 } finally {
5293 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005294 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005295 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005296 UserHandle.of(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005297 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005298 }
5299
5300 /**
5301 * Don't allow callers with the given uid permission to get credentials for
5302 * account/authTokenType.
5303 * <p>
5304 * Although this is public it can only be accessed via the AccountManagerService object
5305 * which is in the system. This means we don't need to protect it with permissions.
5306 * @hide
5307 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005308 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005309 if (account == null || authTokenType == null) {
5310 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005311 return;
5312 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005313 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005314 synchronized (accounts.cacheLock) {
5315 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005316 db.beginTransaction();
5317 try {
5318 long accountId = getAccountIdLocked(db, account);
5319 if (accountId >= 0) {
5320 db.delete(TABLE_GRANTS,
5321 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
5322 + GRANTS_GRANTEE_UID + "=?",
5323 new String[]{String.valueOf(accountId), authTokenType,
5324 String.valueOf(uid)});
5325 db.setTransactionSuccessful();
5326 }
5327 } finally {
5328 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005329 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005330 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5331 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005332 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005333 }
Fred Quintana56285a62010-12-02 14:20:51 -08005334
5335 static final private String stringArrayToString(String[] value) {
5336 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5337 }
5338
Amith Yamasani04e0d262012-02-14 11:50:53 -08005339 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5340 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005341 if (oldAccountsForType != null) {
5342 ArrayList<Account> newAccountsList = new ArrayList<Account>();
5343 for (Account curAccount : oldAccountsForType) {
5344 if (!curAccount.equals(account)) {
5345 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005346 }
5347 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005348 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005349 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005350 } else {
5351 Account[] newAccountsForType = new Account[newAccountsList.size()];
5352 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005353 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005354 }
Fred Quintana56285a62010-12-02 14:20:51 -08005355 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005356 accounts.userDataCache.remove(account);
5357 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005358 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005359 }
5360
5361 /**
5362 * This assumes that the caller has already checked that the account is not already present.
5363 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08005364 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5365 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005366 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5367 Account[] newAccountsForType = new Account[oldLength + 1];
5368 if (accountsForType != null) {
5369 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005370 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005371 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005372 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08005373 }
5374
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005375 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07005376 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005377 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07005378 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005379 return unfiltered;
5380 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005381 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005382 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005383 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005384 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005385 // otherwise return non-shared accounts only.
5386 // This might be a temporary way to specify a whitelist
5387 String whiteList = mContext.getResources().getString(
5388 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5389 for (String packageName : packages) {
5390 if (whiteList.contains(";" + packageName + ";")) {
5391 return unfiltered;
5392 }
5393 }
5394 ArrayList<Account> allowed = new ArrayList<Account>();
5395 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5396 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005397 String requiredAccountType = "";
5398 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005399 // If there's an explicit callingPackage specified, check if that package
5400 // opted in to see restricted accounts.
5401 if (callingPackage != null) {
5402 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005403 if (pi != null && pi.restrictedAccountType != null) {
5404 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005405 }
5406 } else {
5407 // Otherwise check if the callingUid has a package that has opted in
5408 for (String packageName : packages) {
5409 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5410 if (pi != null && pi.restrictedAccountType != null) {
5411 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005412 break;
5413 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005414 }
5415 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005416 } catch (NameNotFoundException nnfe) {
5417 }
5418 for (Account account : unfiltered) {
5419 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005420 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005421 } else {
5422 boolean found = false;
5423 for (Account shared : sharedAccounts) {
5424 if (shared.equals(account)) {
5425 found = true;
5426 break;
5427 }
5428 }
5429 if (!found) {
5430 allowed.add(account);
5431 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005432 }
5433 }
5434 Account[] filtered = new Account[allowed.size()];
5435 allowed.toArray(filtered);
5436 return filtered;
5437 } else {
5438 return unfiltered;
5439 }
5440 }
5441
Amith Yamasani27db4682013-03-30 17:07:47 -07005442 /*
5443 * packageName can be null. If not null, it should be used to filter out restricted accounts
5444 * that the package is not allowed to access.
5445 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005446 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07005447 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005448 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005449 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005450 if (accounts == null) {
5451 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005452 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005453 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07005454 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005455 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005456 } else {
5457 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005458 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005459 totalLength += accounts.length;
5460 }
5461 if (totalLength == 0) {
5462 return EMPTY_ACCOUNT_ARRAY;
5463 }
5464 Account[] accounts = new Account[totalLength];
5465 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005466 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005467 System.arraycopy(accountsOfType, 0, accounts, totalLength,
5468 accountsOfType.length);
5469 totalLength += accountsOfType.length;
5470 }
Amith Yamasani27db4682013-03-30 17:07:47 -07005471 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005472 }
5473 }
5474
Amith Yamasani04e0d262012-02-14 11:50:53 -08005475 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5476 Account account, String key, String value) {
5477 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005478 if (userDataForAccount == null) {
5479 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005480 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005481 }
5482 if (value == null) {
5483 userDataForAccount.remove(key);
5484 } else {
5485 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005486 }
5487 }
5488
Carlos Valdivia91979be2015-05-22 14:11:35 -07005489 protected String readCachedTokenInternal(
5490 UserAccounts accounts,
5491 Account account,
5492 String tokenType,
5493 String callingPackage,
5494 byte[] pkgSigDigest) {
5495 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005496 return accounts.accountTokenCaches.get(
5497 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005498 }
5499 }
5500
Amith Yamasani04e0d262012-02-14 11:50:53 -08005501 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5502 Account account, String key, String value) {
5503 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005504 if (authTokensForAccount == null) {
5505 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005506 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005507 }
5508 if (value == null) {
5509 authTokensForAccount.remove(key);
5510 } else {
5511 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005512 }
5513 }
5514
Amith Yamasani04e0d262012-02-14 11:50:53 -08005515 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5516 String authTokenType) {
5517 synchronized (accounts.cacheLock) {
5518 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005519 if (authTokensForAccount == null) {
5520 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005521 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005522 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005523 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005524 }
5525 return authTokensForAccount.get(authTokenType);
5526 }
5527 }
5528
Simranjit Kohli858511c2016-03-10 18:36:11 +00005529 protected String readUserDataInternalLocked(
5530 UserAccounts accounts, Account account, String key) {
5531 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
5532 if (userDataForAccount == null) {
5533 // need to populate the cache for this account
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005534 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Simranjit Kohli858511c2016-03-10 18:36:11 +00005535 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
5536 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005537 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005538 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005539 }
5540
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005541 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
5542 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005543 HashMap<String, String> userDataForAccount = new HashMap<>();
5544 Cursor cursor = db.query(CE_TABLE_EXTRAS,
Fred Quintana56285a62010-12-02 14:20:51 -08005545 COLUMNS_EXTRAS_KEY_AND_VALUE,
5546 SELECTION_USERDATA_BY_ACCOUNT,
5547 new String[]{account.name, account.type},
5548 null, null, null);
5549 try {
5550 while (cursor.moveToNext()) {
5551 final String tmpkey = cursor.getString(0);
5552 final String value = cursor.getString(1);
5553 userDataForAccount.put(tmpkey, value);
5554 }
5555 } finally {
5556 cursor.close();
5557 }
5558 return userDataForAccount;
5559 }
5560
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005561 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
5562 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005563 HashMap<String, String> authTokensForAccount = new HashMap<>();
5564 Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
Fred Quintana56285a62010-12-02 14:20:51 -08005565 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
5566 SELECTION_AUTHTOKENS_BY_ACCOUNT,
5567 new String[]{account.name, account.type},
5568 null, null, null);
5569 try {
5570 while (cursor.moveToNext()) {
5571 final String type = cursor.getString(0);
5572 final String authToken = cursor.getString(1);
5573 authTokensForAccount.put(type, authToken);
5574 }
5575 } finally {
5576 cursor.close();
5577 }
5578 return authTokensForAccount;
5579 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005580
5581 private Context getContextForUser(UserHandle user) {
5582 try {
5583 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5584 } catch (NameNotFoundException e) {
5585 // Default to mContext, not finding the package system is running as is unlikely.
5586 return mContext;
5587 }
5588 }
Sandra Kwan78812282015-11-04 11:19:47 -08005589
5590 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5591 try {
5592 response.onResult(result);
5593 } catch (RemoteException e) {
5594 // if the caller is dead then there is no one to care about remote
5595 // exceptions
5596 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5597 Log.v(TAG, "failure while notifying response", e);
5598 }
5599 }
5600 }
5601
5602 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5603 String errorMessage) {
5604 try {
5605 response.onError(errorCode, errorMessage);
5606 } catch (RemoteException e) {
5607 // if the caller is dead then there is no one to care about remote
5608 // exceptions
5609 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5610 Log.v(TAG, "failure while notifying response", e);
5611 }
5612 }
5613 }
Fred Quintana60307342009-03-24 22:48:12 -07005614}