blob: a9a53a2ccee15a761d93a81c0addb856373c0889 [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Carlos Valdivia91979be2015-05-22 14:11:35 -070020import android.accounts.AbstractAccountAuthenticator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
25import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070026import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.accounts.GrantCredentialsPermissionActivity;
28import android.accounts.IAccountAuthenticator;
29import android.accounts.IAccountAuthenticatorResponse;
30import android.accounts.IAccountManager;
31import android.accounts.IAccountManagerResponse;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070032import android.annotation.NonNull;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080033import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070034import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070035import android.app.AppGlobals;
Svetoslavf3f02ac2015-09-08 14:36:35 -070036import android.app.AppOpsManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000040import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010041import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000042import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070043import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070044import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070045import android.content.ContentValues;
46import android.content.Context;
47import android.content.Intent;
48import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070049import android.content.ServiceConnection;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -080050import android.content.pm.ActivityInfo;
Doug Zongker885cfc232009-10-21 16:52:44 -070051import android.content.pm.ApplicationInfo;
52import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070053import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070054import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070055import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070056import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070057import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070058import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070059import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070060import android.database.Cursor;
61import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import android.database.sqlite.SQLiteDatabase;
63import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070064import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070065import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080067import android.os.Environment;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070068import android.os.FileUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.os.IBinder;
71import android.os.Looper;
72import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070073import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070074import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070075import android.os.RemoteException;
76import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070077import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070078import android.os.UserManager;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070079import android.os.storage.StorageManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070080import android.text.TextUtils;
81import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070082import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070083import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080084import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070085import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070086
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070087import com.android.internal.R;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070088import com.android.internal.annotations.VisibleForTesting;
Amith Yamasani67df64b2012-12-14 12:09:36 -080089import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080090import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -070091import com.android.internal.util.Preconditions;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070092import com.android.server.FgThread;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000093import com.android.server.LocalServices;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -060094import com.android.server.SystemService;
95
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070096import com.google.android.collect.Lists;
97import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070098
Oscar Montemayora8529f62009-11-18 10:14:20 -080099import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700100import java.io.FileDescriptor;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700101import java.io.IOException;
Fred Quintanaa698f422009-04-08 19:14:54 -0700102import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800103import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700104import java.security.MessageDigest;
105import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700106import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700107import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800108import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700109import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700110import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700111import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700112import java.util.HashSet;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800113import java.util.Iterator;
Fred Quintana56285a62010-12-02 14:20:51 -0800114import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700115import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800116import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800117import java.util.Map.Entry;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700118import java.util.concurrent.atomic.AtomicInteger;
119import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700120
Fred Quintana60307342009-03-24 22:48:12 -0700121/**
122 * A system service that provides account, password, and authtoken management for all
123 * accounts on the device. Some of these calls are implemented with the help of the corresponding
124 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
125 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700126 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700127 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700128 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700129public class AccountManagerService
130 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800131 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700132 private static final String TAG = "AccountManagerService";
133
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600134 public static class Lifecycle extends SystemService {
135 private AccountManagerService mService;
136
137 public Lifecycle(Context context) {
138 super(context);
139 }
140
141 @Override
142 public void onStart() {
143 mService = new AccountManagerService(getContext());
144 publishBinderService(Context.ACCOUNT_SERVICE, mService);
145 }
146
147 @Override
148 public void onBootPhase(int phase) {
149 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
150 mService.systemReady();
151 }
152 }
153
154 @Override
155 public void onUnlockUser(int userHandle) {
156 mService.onUnlockUser(userHandle);
157 }
158 }
159
Fred Quintana60307342009-03-24 22:48:12 -0700160 private static final String DATABASE_NAME = "accounts.db";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700161 private static final int PRE_N_DATABASE_VERSION = 9;
162 private static final int CE_DATABASE_VERSION = 10;
163 private static final int DE_DATABASE_VERSION = 1;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700164
165 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700166
167 private final Context mContext;
168
Fred Quintana56285a62010-12-02 14:20:51 -0800169 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700170 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700171 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800172
Fred Quintana60307342009-03-24 22:48:12 -0700173 private final MessageHandler mMessageHandler;
174
175 // Messages that can be sent on mHandler
176 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700177 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700178
Fred Quintana56285a62010-12-02 14:20:51 -0800179 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700180
181 private static final String TABLE_ACCOUNTS = "accounts";
182 private static final String ACCOUNTS_ID = "_id";
183 private static final String ACCOUNTS_NAME = "name";
184 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700185 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700186 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700187 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800188 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
189 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700190
191 private static final String TABLE_AUTHTOKENS = "authtokens";
192 private static final String AUTHTOKENS_ID = "_id";
193 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
194 private static final String AUTHTOKENS_TYPE = "type";
195 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
196
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700197 private static final String TABLE_GRANTS = "grants";
198 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
199 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
200 private static final String GRANTS_GRANTEE_UID = "uid";
201
Fred Quintana60307342009-03-24 22:48:12 -0700202 private static final String TABLE_EXTRAS = "extras";
203 private static final String EXTRAS_ID = "_id";
204 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
205 private static final String EXTRAS_KEY = "key";
206 private static final String EXTRAS_VALUE = "value";
207
208 private static final String TABLE_META = "meta";
209 private static final String META_KEY = "key";
210 private static final String META_VALUE = "value";
211
Amith Yamasani67df64b2012-12-14 12:09:36 -0800212 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700213 private static final String SHARED_ACCOUNTS_ID = "_id";
214
215 private static final String PRE_N_DATABASE_NAME = "accounts.db";
216 private static final String CE_DATABASE_NAME = "accounts_ce.db";
217 private static final String DE_DATABASE_NAME = "accounts_de.db";
218 private static final String CE_DB_PREFIX = "ceDb.";
219 private static final String CE_TABLE_ACCOUNTS = CE_DB_PREFIX + TABLE_ACCOUNTS;
220 private static final String CE_TABLE_AUTHTOKENS = CE_DB_PREFIX + TABLE_AUTHTOKENS;
221 private static final String CE_TABLE_EXTRAS = CE_DB_PREFIX + TABLE_EXTRAS;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800222
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700223 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
224 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700225 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800226
Carlos Valdivia91979be2015-05-22 14:11:35 -0700227 static {
228 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
229 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
230 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700231
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700232 private static final String COUNT_OF_MATCHING_GRANTS = ""
233 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
234 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
235 + " AND " + GRANTS_GRANTEE_UID + "=?"
236 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
237 + " AND " + ACCOUNTS_NAME + "=?"
238 + " AND " + ACCOUNTS_TYPE + "=?";
239
Fred Quintana56285a62010-12-02 14:20:51 -0800240 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
241 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700242
Fred Quintana56285a62010-12-02 14:20:51 -0800243 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
244 AUTHTOKENS_AUTHTOKEN};
245
246 private static final String SELECTION_USERDATA_BY_ACCOUNT =
247 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
248 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
249
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800250 private static final String META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX =
251 "auth_uid_for_type:";
252 private static final String META_KEY_DELIMITER = ":";
253 private static final String SELECTION_META_BY_AUTHENTICATOR_TYPE = META_KEY + " LIKE ?";
254
Fred Quintanaa698f422009-04-08 19:14:54 -0700255 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700256 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
257
Amith Yamasani04e0d262012-02-14 11:50:53 -0800258 static class UserAccounts {
259 private final int userId;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700260 private final DeDatabaseHelper openHelper;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800261 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
262 credentialsPermissionNotificationIds =
263 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
264 private final HashMap<Account, Integer> signinRequiredNotificationIds =
265 new HashMap<Account, Integer>();
266 private final Object cacheLock = new Object();
267 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700268 private final HashMap<String, Account[]> accountCache =
269 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800270 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800271 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800272 new HashMap<Account, HashMap<String, String>>();
273 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800274 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800275 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700276
277 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700278 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700279
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700280 /**
281 * protected by the {@link #cacheLock}
282 *
283 * Caches the previous names associated with an account. Previous names
284 * should be cached because we expect that when an Account is renamed,
285 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
286 * want to know if the accounts they care about have been renamed.
287 *
288 * The previous names are wrapped in an {@link AtomicReference} so that
289 * we can distinguish between those accounts with no previous names and
290 * those whose previous names haven't been cached (yet).
291 */
292 private final HashMap<Account, AtomicReference<String>> previousNameCache =
293 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800294
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700295 private int debugDbInsertionPoint = -1;
296 private SQLiteStatement statementForLogging;
297
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700298 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800299 this.userId = userId;
300 synchronized (cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700301 openHelper = DeDatabaseHelper.create(context, userId, preNDbFile, deDbFile);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800302 }
303 }
304 }
305
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700306 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600307 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800308
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700309 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700310 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700311
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700312 /**
313 * This should only be called by system code. One should only call this after the service
314 * has started.
315 * @return a reference to the AccountManagerService instance
316 * @hide
317 */
318 public static AccountManagerService getSingleton() {
319 return sThis.get();
320 }
Fred Quintana60307342009-03-24 22:48:12 -0700321
Fred Quintana56285a62010-12-02 14:20:51 -0800322 public AccountManagerService(Context context) {
323 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700324 }
325
Fred Quintana56285a62010-12-02 14:20:51 -0800326 public AccountManagerService(Context context, PackageManager packageManager,
327 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700328 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800329 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700330 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700331
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700332 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700333
Fred Quintana56285a62010-12-02 14:20:51 -0800334 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800335 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700336
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700337 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800338
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800339 IntentFilter intentFilter = new IntentFilter();
340 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
341 intentFilter.addDataScheme("package");
342 mContext.registerReceiver(new BroadcastReceiver() {
343 @Override
344 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700345 // Don't delete accounts when updating a authenticator's
346 // package.
347 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700348 /* Purging data requires file io, don't block the main thread. This is probably
349 * less than ideal because we are introducing a race condition where old grants
350 * could be exercised until they are purged. But that race condition existed
351 * anyway with the broadcast receiver.
352 *
353 * Ideally, we would completely clear the cache, purge data from the database,
354 * and then rebuild the cache. All under the cache lock. But that change is too
355 * large at this point.
356 */
357 Runnable r = new Runnable() {
358 @Override
359 public void run() {
360 purgeOldGrantsAll();
361 }
362 };
363 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700364 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800365 }
366 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800367
Amith Yamasani13593602012-03-22 16:16:17 -0700368 IntentFilter userFilter = new IntentFilter();
369 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800370 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700371 @Override
372 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800373 String action = intent.getAction();
374 if (Intent.ACTION_USER_REMOVED.equals(action)) {
375 onUserRemoved(intent);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800376 }
Amith Yamasani13593602012-03-22 16:16:17 -0700377 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800378 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800379 }
380
Dianne Hackborn164371f2013-10-01 19:10:13 -0700381 @Override
382 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
383 throws RemoteException {
384 try {
385 return super.onTransact(code, data, reply, flags);
386 } catch (RuntimeException e) {
387 // The account manager only throws security exceptions, so let's
388 // log all others.
389 if (!(e instanceof SecurityException)) {
390 Slog.wtf(TAG, "Account Manager Crash", e);
391 }
392 throw e;
393 }
394 }
395
Kenny Root26ff6622012-07-30 12:58:03 -0700396 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700397 }
398
Amith Yamasani258848d2012-08-10 17:06:33 -0700399 private UserManager getUserManager() {
400 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700401 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700402 }
403 return mUserManager;
404 }
405
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700406 /**
407 * Validate internal set of accounts against installed authenticators for
408 * given user. Clears cached authenticators before validating.
409 */
410 public void validateAccounts(int userId) {
411 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700412 // Invalidate user-specific cache to make sure we catch any
413 // removed authenticators.
414 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
415 }
416
417 /**
418 * Validate internal set of accounts against installed authenticators for
419 * given user. Clear cached authenticators before validating when requested.
420 */
421 private void validateAccountsInternal(
422 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700423 if (Log.isLoggable(TAG, Log.DEBUG)) {
424 Log.d(TAG, "validateAccountsInternal " + accounts.userId
425 + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600426 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700427 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700428
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700429 if (invalidateAuthenticatorCache) {
430 mAuthenticatorCache.invalidateCache(accounts.userId);
431 }
432
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700433 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
434 mAuthenticatorCache, accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700435
Amith Yamasani04e0d262012-02-14 11:50:53 -0800436 synchronized (accounts.cacheLock) {
437 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800438 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800439
440 // Get a list of stored authenticator type and UID
441 Cursor metaCursor = db.query(
442 TABLE_META,
443 new String[] {META_KEY, META_VALUE},
444 SELECTION_META_BY_AUTHENTICATOR_TYPE,
445 new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
446 null /* groupBy */,
447 null /* having */,
448 META_KEY);
449 // Create a list of authenticator type whose previous uid no longer exists
450 HashSet<String> obsoleteAuthType = Sets.newHashSet();
451 try {
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700452 SparseBooleanArray knownUids = null;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800453 while (metaCursor.moveToNext()) {
454 String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
455 String uid = metaCursor.getString(1);
456 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uid)) {
457 // Should never happen.
458 Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
459 + ", uid empty: " + TextUtils.isEmpty(uid));
460 continue;
461 }
462 Integer knownUid = knownAuth.get(type);
463 if (knownUid != null && uid.equals(knownUid.toString())) {
464 // Remove it from the knownAuth list if it's unchanged.
465 knownAuth.remove(type);
466 } else {
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700467 /*
468 * The authenticator is presently not cached and should only be triggered
469 * when we think an authenticator has been removed (or is being updated).
470 * But we still want to check if any data with the associated uid is
471 * around. This is an (imperfect) signal that the package may be updating.
472 *
473 * A side effect of this is that an authenticator sharing a uid with
474 * multiple apps won't get its credentials wiped as long as some app with
475 * that uid is still on the device. But I suspect that this is a rare case.
476 * And it isn't clear to me how an attacker could really exploit that
477 * feature.
478 *
479 * The upshot is that we don't have to worry about accounts getting
480 * uninstalled while the authenticator's package is being updated.
481 *
482 */
483 if (knownUids == null) {
484 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
485 }
486 if (!knownUids.get(Integer.parseInt(uid))) {
487 // The authenticator is not presently available to the cache. And the
488 // package no longer has a data directory (so we surmise it isn't updating).
489 // So purge its data from the account databases.
490 obsoleteAuthType.add(type);
491 // And delete it from the TABLE_META
492 db.delete(
493 TABLE_META,
494 META_KEY + "=? AND " + META_VALUE + "=?",
495 new String[] {
496 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
497 uid}
498 );
499 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800500 }
501 }
502 } finally {
503 metaCursor.close();
504 }
505
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700506 // Add the newly registered authenticator to TABLE_META. If old authenticators have
507 // been renabled (after being updated for example), then we just overwrite the old
508 // values.
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800509 Iterator<Entry<String, Integer>> iterator = knownAuth.entrySet().iterator();
510 while (iterator.hasNext()) {
511 Entry<String, Integer> entry = iterator.next();
512 ContentValues values = new ContentValues();
513 values.put(META_KEY,
514 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
515 values.put(META_VALUE, entry.getValue());
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700516 db.insertWithOnConflict(TABLE_META, null, values, SQLiteDatabase.CONFLICT_REPLACE);
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800517 }
518
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800519 Cursor cursor = db.query(TABLE_ACCOUNTS,
520 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800521 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800522 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800523 accounts.accountCache.clear();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700524 final HashMap<String, ArrayList<String>> accountNamesByType = new LinkedHashMap<>();
Fred Quintana56285a62010-12-02 14:20:51 -0800525 while (cursor.moveToNext()) {
526 final long accountId = cursor.getLong(0);
527 final String accountType = cursor.getString(1);
528 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700529
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800530 if (obsoleteAuthType.contains(accountType)) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700531 Slog.w(TAG, "deleting account " + accountName + " because type "
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800532 + accountType + "'s registered authenticator no longer exist.");
Fred Quintana56285a62010-12-02 14:20:51 -0800533 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
534 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700535
536 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
537 accountId, accounts);
538
Fred Quintana56285a62010-12-02 14:20:51 -0800539 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800540 accounts.userDataCache.remove(account);
541 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700542 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800543 } else {
544 ArrayList<String> accountNames = accountNamesByType.get(accountType);
545 if (accountNames == null) {
546 accountNames = new ArrayList<String>();
547 accountNamesByType.put(accountType, accountNames);
548 }
549 accountNames.add(accountName);
550 }
551 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700552 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800553 final String accountType = cur.getKey();
554 final ArrayList<String> accountNames = cur.getValue();
555 final Account[] accountsForType = new Account[accountNames.size()];
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700556 for (int i = 0; i < accountsForType.length; i++) {
557 accountsForType[i] = new Account(accountNames.get(i), accountType);
Fred Quintana56285a62010-12-02 14:20:51 -0800558 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800559 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800560 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800561 } finally {
562 cursor.close();
563 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800564 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800565 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800566 }
567 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700568 }
569
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700570 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
571 // Get the UIDs of all apps that might have data on the device. We want
572 // to preserve user data if the app might otherwise be storing data.
573 List<PackageInfo> pkgsWithData =
574 mPackageManager.getInstalledPackagesAsUser(
575 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
576 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
577 for (PackageInfo pkgInfo : pkgsWithData) {
578 if (pkgInfo.applicationInfo != null
579 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
580 knownUids.put(pkgInfo.applicationInfo.uid, true);
581 }
582 }
583 return knownUids;
584 }
585
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800586 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
587 Context context,
588 int userId) {
589 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700590 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
591 }
592
593 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
594 IAccountAuthenticatorCache authCache,
595 int userId) {
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800596 HashMap<String, Integer> knownAuth = new HashMap<>();
597 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
598 .getAllServices(userId)) {
599 knownAuth.put(service.type.type, service.uid);
600 }
601 return knownAuth;
602 }
603
Amith Yamasani04e0d262012-02-14 11:50:53 -0800604 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700605 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800606 }
607
608 protected UserAccounts getUserAccounts(int userId) {
609 synchronized (mUsers) {
610 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700611 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800612 if (accounts == null) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700613 File preNDbFile = new File(getPreNDatabaseName(userId));
614 File deDbFile = new File(getDeDatabaseName(userId));
615 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700616 initializeDebugDbSizeAndCompileSqlStatementForLogging(
617 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800618 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700619 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700620 validateAccounts = true;
621 }
622 // open CE database if necessary
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600623 if (!accounts.openHelper.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700624 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
625 synchronized (accounts.cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700626 File preNDatabaseFile = new File(getPreNDatabaseName(userId));
627 File ceDatabaseFile = new File(getCeDatabaseName(userId));
628 CeDatabaseHelper.create(mContext, userId, preNDatabaseFile, ceDatabaseFile);
629 accounts.openHelper.attachCeDatabase(ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700630 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700631 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700632 }
633 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700634 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800635 }
636 return accounts;
637 }
638 }
639
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700640 private void syncDeCeAccountsLocked(UserAccounts accounts) {
641 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
642 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
643 List<Account> accountsToRemove = CeDatabaseHelper.findCeAccountsNotInDe(db);
644 if (!accountsToRemove.isEmpty()) {
645 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
646 + accounts.userId + " was locked. Removing accounts from CE tables");
647 logRecord(accounts, DebugDbHelper.ACTION_SYNC_DE_CE_ACCOUNTS, TABLE_ACCOUNTS);
648
649 for (Account account : accountsToRemove) {
650 removeAccountInternal(accounts, account, Process.myUid());
651 }
652 }
653 }
654
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700655 private void purgeOldGrantsAll() {
656 synchronized (mUsers) {
657 for (int i = 0; i < mUsers.size(); i++) {
658 purgeOldGrants(mUsers.valueAt(i));
659 }
660 }
661 }
662
663 private void purgeOldGrants(UserAccounts accounts) {
664 synchronized (accounts.cacheLock) {
665 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
666 final Cursor cursor = db.query(TABLE_GRANTS,
667 new String[]{GRANTS_GRANTEE_UID},
668 null, null, GRANTS_GRANTEE_UID, null, null);
669 try {
670 while (cursor.moveToNext()) {
671 final int uid = cursor.getInt(0);
672 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
673 if (packageExists) {
674 continue;
675 }
676 Log.d(TAG, "deleting grants for UID " + uid
677 + " because its package is no longer installed");
678 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
679 new String[]{Integer.toString(uid)});
680 }
681 } finally {
682 cursor.close();
683 }
684 }
685 }
686
Amith Yamasani13593602012-03-22 16:16:17 -0700687 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700688 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700689 if (userId < 1) return;
690
691 UserAccounts accounts;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700692 boolean userUnlocked;
Amith Yamasani13593602012-03-22 16:16:17 -0700693 synchronized (mUsers) {
694 accounts = mUsers.get(userId);
695 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600696 userUnlocked = mLocalUnlockedUsers.get(userId);
697 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700698 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700699 if (accounts != null) {
700 synchronized (accounts.cacheLock) {
701 accounts.openHelper.close();
702 }
Amith Yamasani13593602012-03-22 16:16:17 -0700703 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700704 Log.i(TAG, "Removing database files for user " + userId);
705 File dbFile = new File(getDeDatabaseName(userId));
Amith Yamasani13593602012-03-22 16:16:17 -0700706
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700707 deleteDbFileWarnIfFailed(dbFile);
708 // Remove CE file if user is unlocked, or FBE is not enabled
709 boolean fbeEnabled = StorageManager.isFileEncryptedNativeOrEmulated();
710 if (!fbeEnabled || userUnlocked) {
711 File ceDb = new File(getCeDatabaseName(userId));
712 if (ceDb.exists()) {
713 deleteDbFileWarnIfFailed(ceDb);
714 }
715 }
716 }
717
718 private static void deleteDbFileWarnIfFailed(File dbFile) {
719 if (!SQLiteDatabase.deleteDatabase(dbFile)) {
720 Log.w(TAG, "Database at " + dbFile + " was not deleted successfully");
Amith Yamasani13593602012-03-22 16:16:17 -0700721 }
722 }
723
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700724 @VisibleForTesting
725 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600726 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
727 }
728
729 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700730 if (Log.isLoggable(TAG, Log.VERBOSE)) {
731 Log.v(TAG, "onUserUnlocked " + userId);
732 }
733 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600734 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700735 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800736 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700737 syncSharedAccounts(userId);
738 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800739
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700740 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800741 // Check if there's a shared account that needs to be created as an account
742 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
743 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700744 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700745 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -0700746 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700747 : UserHandle.USER_SYSTEM;
748 if (parentUserId < 0) {
749 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
750 return;
751 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800752 for (Account sa : sharedAccounts) {
753 if (ArrayUtils.contains(accounts, sa)) continue;
754 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700755 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800756 }
757 }
758
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700759 @Override
760 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700761 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700762 }
763
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800764 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700765 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700766 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800767 if (Log.isLoggable(TAG, Log.VERBOSE)) {
768 Log.v(TAG, "getPassword: " + account
769 + ", caller's uid " + Binder.getCallingUid()
770 + ", pid " + Binder.getCallingPid());
771 }
Fred Quintana382601f2010-03-25 12:25:10 -0700772 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000773 int userId = UserHandle.getCallingUserId();
774 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700775 String msg = String.format(
776 "uid %s cannot get secrets for accounts of type: %s",
777 callingUid,
778 account.type);
779 throw new SecurityException(msg);
780 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700781 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700782 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700783 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800784 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700785 } finally {
786 restoreCallingIdentity(identityToken);
787 }
788 }
789
Amith Yamasani04e0d262012-02-14 11:50:53 -0800790 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700791 if (account == null) {
792 return null;
793 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600794 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700795 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
796 return null;
797 }
Fred Quintana31957f12009-10-21 13:43:10 -0700798
Amith Yamasani04e0d262012-02-14 11:50:53 -0800799 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700800 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
801 return CeDatabaseHelper.findAccountPasswordByNameAndType(db, account.name,
802 account.type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700803 }
804 }
805
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800806 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700807 public String getPreviousName(Account account) {
808 if (Log.isLoggable(TAG, Log.VERBOSE)) {
809 Log.v(TAG, "getPreviousName: " + account
810 + ", caller's uid " + Binder.getCallingUid()
811 + ", pid " + Binder.getCallingPid());
812 }
813 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700814 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700815 long identityToken = clearCallingIdentity();
816 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700817 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700818 return readPreviousNameInternal(accounts, account);
819 } finally {
820 restoreCallingIdentity(identityToken);
821 }
822 }
823
824 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
825 if (account == null) {
826 return null;
827 }
828 synchronized (accounts.cacheLock) {
829 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
830 if (previousNameRef == null) {
831 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
832 Cursor cursor = db.query(
833 TABLE_ACCOUNTS,
834 new String[]{ ACCOUNTS_PREVIOUS_NAME },
835 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
836 new String[] { account.name, account.type },
837 null,
838 null,
839 null);
840 try {
841 if (cursor.moveToNext()) {
842 String previousName = cursor.getString(0);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700843 previousNameRef = new AtomicReference<>(previousName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700844 accounts.previousNameCache.put(account, previousNameRef);
845 return previousName;
846 } else {
847 return null;
848 }
849 } finally {
850 cursor.close();
851 }
852 } else {
853 return previousNameRef.get();
854 }
855 }
856 }
857
858 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700859 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700860 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800861 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700862 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
863 account, key, callingUid, Binder.getCallingPid());
864 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800865 }
Fred Quintana382601f2010-03-25 12:25:10 -0700866 if (account == null) throw new IllegalArgumentException("account is null");
867 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000868 int userId = UserHandle.getCallingUserId();
869 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700870 String msg = String.format(
871 "uid %s cannot get user data for accounts of type: %s",
872 callingUid,
873 account.type);
874 throw new SecurityException(msg);
875 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600876 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -0700877 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
878 return null;
879 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700880 long identityToken = clearCallingIdentity();
881 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700882 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +0000883 synchronized (accounts.cacheLock) {
884 if (!accountExistsCacheLocked(accounts, account)) {
885 return null;
886 }
887 return readUserDataInternalLocked(accounts, account, key);
888 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700889 } finally {
890 restoreCallingIdentity(identityToken);
891 }
892 }
893
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800894 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100895 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700896 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800897 if (Log.isLoggable(TAG, Log.VERBOSE)) {
898 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100899 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700900 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800901 + ", pid " + Binder.getCallingPid());
902 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100903 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700904 if (isCrossUser(callingUid, userId)) {
905 throw new SecurityException(
906 String.format(
907 "User %s tying to get authenticator types for %s" ,
908 UserHandle.getCallingUserId(),
909 userId));
910 }
911
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700912 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700913 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000914 return getAuthenticatorTypesInternal(userId);
915
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700916 } finally {
917 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700918 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700919 }
920
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000921 /**
922 * Should only be called inside of a clearCallingIdentity block.
923 */
924 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
925 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
926 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
927 AuthenticatorDescription[] types =
928 new AuthenticatorDescription[authenticatorCollection.size()];
929 int i = 0;
930 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
931 : authenticatorCollection) {
932 types[i] = authenticator.type;
933 i++;
934 }
935 return types;
936 }
937
938
939
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700940 private boolean isCrossUser(int callingUid, int userId) {
941 return (userId != UserHandle.getCallingUserId()
942 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100943 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700944 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
945 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100946 }
947
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700948 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700949 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600950 Bundle.setDefusable(extras, true);
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700951 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800952 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700953 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700954 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800955 + ", pid " + Binder.getCallingPid());
956 }
Fred Quintana382601f2010-03-25 12:25:10 -0700957 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000958 int userId = UserHandle.getCallingUserId();
959 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700960 String msg = String.format(
961 "uid %s cannot explicitly add accounts of type: %s",
962 callingUid,
963 account.type);
964 throw new SecurityException(msg);
965 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700966 /*
967 * Child users are not allowed to add accounts. Only the accounts that are
968 * shared by the parent profile can be added to child profile.
969 *
970 * TODO: Only allow accounts that were shared to be added by
971 * a limited user.
972 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700973
Fred Quintana60307342009-03-24 22:48:12 -0700974 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700975 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700976 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700977 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700978 return addAccountInternal(accounts, account, password, extras, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700979 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700980 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700981 }
982 }
983
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000984 @Override
985 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700986 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700987 int callingUid = Binder.getCallingUid();
988 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
989 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000990 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700991 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800992 final UserAccounts fromAccounts = getUserAccounts(userFrom);
993 final UserAccounts toAccounts = getUserAccounts(userTo);
994 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000995 if (response != null) {
996 Bundle result = new Bundle();
997 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
998 try {
999 response.onResult(result);
1000 } catch (RemoteException e) {
1001 Slog.w(TAG, "Failed to report error back to the client." + e);
1002 }
1003 }
1004 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001005 }
1006
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001007 Slog.d(TAG, "Copying account " + account.name
1008 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001009 long identityToken = clearCallingIdentity();
1010 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001011 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001012 false /* stripAuthTokenFromResult */, account.name,
1013 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001014 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001015 protected String toDebugString(long now) {
1016 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1017 + ", " + account.type;
1018 }
1019
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001020 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001021 public void run() throws RemoteException {
1022 mAuthenticator.getAccountCredentialsForCloning(this, account);
1023 }
1024
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001025 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001026 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001027 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001028 if (result != null
1029 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1030 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001031 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001032 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001033 super.onResult(result);
1034 }
1035 }
1036 }.bind();
1037 } finally {
1038 restoreCallingIdentity(identityToken);
1039 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001040 }
1041
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001042 @Override
1043 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001044 final int callingUid = Binder.getCallingUid();
1045 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1046 String msg = String.format(
1047 "accountAuthenticated( account: %s, callerUid: %s)",
1048 account,
1049 callingUid);
1050 Log.v(TAG, msg);
1051 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001052 if (account == null) {
1053 throw new IllegalArgumentException("account is null");
1054 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001055 int userId = UserHandle.getCallingUserId();
1056 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001057 String msg = String.format(
1058 "uid %s cannot notify authentication for accounts of type: %s",
1059 callingUid,
1060 account.type);
1061 throw new SecurityException(msg);
1062 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001063
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001064 if (!canUserModifyAccounts(userId, callingUid) ||
1065 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001066 return false;
1067 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001068
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001069 long identityToken = clearCallingIdentity();
1070 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001071 UserAccounts accounts = getUserAccounts(userId);
1072 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001073 } finally {
1074 restoreCallingIdentity(identityToken);
1075 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001076 }
1077
1078 private boolean updateLastAuthenticatedTime(Account account) {
1079 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001080 synchronized (accounts.cacheLock) {
1081 final ContentValues values = new ContentValues();
1082 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
1083 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1084 int i = db.update(
1085 TABLE_ACCOUNTS,
1086 values,
1087 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1088 new String[] {
1089 account.name, account.type
1090 });
1091 if (i > 0) {
1092 return true;
1093 }
1094 }
1095 return false;
1096 }
1097
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001098 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001099 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1100 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001101 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001102 long id = clearCallingIdentity();
1103 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001104 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001105 false /* stripAuthTokenFromResult */, account.name,
1106 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001107 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001108 protected String toDebugString(long now) {
1109 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1110 + ", " + account.type;
1111 }
1112
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001113 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001114 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001115 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001116 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001117 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -07001118 for (Account acc : getAccounts(parentUserId,
1119 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001120 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001121 mAuthenticator.addAccountFromCredentials(
1122 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001123 break;
1124 }
1125 }
1126 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001127 }
1128
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001129 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001130 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001131 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001132 // TODO: Anything to do if if succedded?
1133 // TODO: If it failed: Show error notification? Should we remove the shadow
1134 // account to avoid retries?
1135 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001136 }
1137
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001138 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001139 public void onError(int errorCode, String errorMessage) {
1140 super.onError(errorCode, errorMessage);
1141 // TODO: Show error notification to user
1142 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1143 }
1144
1145 }.bind();
1146 } finally {
1147 restoreCallingIdentity(id);
1148 }
1149 }
1150
Amith Yamasani04e0d262012-02-14 11:50:53 -08001151 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001152 Bundle extras, int callingUid) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001153 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001154 if (account == null) {
1155 return false;
1156 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001157 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001158 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1159 + " is locked. callingUid=" + callingUid);
1160 return false;
1161 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001162 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001163 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001164 db.beginTransaction();
1165 try {
1166 long numMatches = DatabaseUtils.longForQuery(db,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001167 "select count(*) from " + CE_TABLE_ACCOUNTS
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001168 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1169 new String[]{account.name, account.type});
1170 if (numMatches > 0) {
1171 Log.w(TAG, "insertAccountIntoDatabase: " + account
1172 + ", skipping since the account already exists");
1173 return false;
1174 }
1175 ContentValues values = new ContentValues();
1176 values.put(ACCOUNTS_NAME, account.name);
1177 values.put(ACCOUNTS_TYPE, account.type);
1178 values.put(ACCOUNTS_PASSWORD, password);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001179 long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001180 if (accountId < 0) {
1181 Log.w(TAG, "insertAccountIntoDatabase: " + account
1182 + ", skipping the DB insert failed");
1183 return false;
1184 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001185 // Insert into DE table
1186 values = new ContentValues();
1187 values.put(ACCOUNTS_ID, accountId);
1188 values.put(ACCOUNTS_NAME, account.name);
1189 values.put(ACCOUNTS_TYPE, account.type);
1190 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1191 System.currentTimeMillis());
1192 if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1193 Log.w(TAG, "insertAccountIntoDatabase: " + account
1194 + ", skipping the DB insert failed");
1195 return false;
1196 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001197 if (extras != null) {
1198 for (String key : extras.keySet()) {
1199 final String value = extras.getString(key);
1200 if (insertExtraLocked(db, accountId, key, value) < 0) {
1201 Log.w(TAG, "insertAccountIntoDatabase: " + account
1202 + ", skipping since insertExtra failed for key " + key);
1203 return false;
1204 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001205 }
1206 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001207 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001208
1209 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1210 accounts, callingUid);
1211
Amith Yamasani04e0d262012-02-14 11:50:53 -08001212 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001213 } finally {
1214 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001215 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001216 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001217 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001218 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1219 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001220 }
1221 return true;
1222 }
1223
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001224 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001225 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001226 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001227 }
1228 }
1229
Amith Yamasani5be347b2013-03-31 17:44:31 -07001230 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001231 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001232 * running, then clone the account too.
1233 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001234 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001235 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001236 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001237 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001238 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001239 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001240 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001241 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001242 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1243 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001244 }
1245 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001246 }
1247 }
1248
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001249 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -07001250 ContentValues values = new ContentValues();
1251 values.put(EXTRAS_KEY, key);
1252 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1253 values.put(EXTRAS_VALUE, value);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001254 return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
Fred Quintana60307342009-03-24 22:48:12 -07001255 }
1256
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001257 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001258 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001259 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001260 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001261 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1262 Log.v(TAG, "hasFeatures: " + account
1263 + ", response " + response
1264 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001265 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001266 + ", pid " + Binder.getCallingPid());
1267 }
Fred Quintana382601f2010-03-25 12:25:10 -07001268 if (response == null) throw new IllegalArgumentException("response is null");
1269 if (account == null) throw new IllegalArgumentException("account is null");
1270 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001271 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001272 checkReadAccountsPermitted(callingUid, account.type, userId,
1273 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001274
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001275 long identityToken = clearCallingIdentity();
1276 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001277 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001278 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001279 } finally {
1280 restoreCallingIdentity(identityToken);
1281 }
1282 }
1283
1284 private class TestFeaturesSession extends Session {
1285 private final String[] mFeatures;
1286 private final Account mAccount;
1287
Amith Yamasani04e0d262012-02-14 11:50:53 -08001288 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001289 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001290 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001291 true /* stripAuthTokenFromResult */, account.name,
1292 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001293 mFeatures = features;
1294 mAccount = account;
1295 }
1296
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001297 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001298 public void run() throws RemoteException {
1299 try {
1300 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1301 } catch (RemoteException e) {
1302 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1303 }
1304 }
1305
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001306 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001307 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001308 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001309 IAccountManagerResponse response = getResponseAndClose();
1310 if (response != null) {
1311 try {
1312 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001313 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001314 return;
1315 }
Fred Quintana56285a62010-12-02 14:20:51 -08001316 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1317 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1318 + response);
1319 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001320 final Bundle newResult = new Bundle();
1321 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1322 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1323 response.onResult(newResult);
1324 } catch (RemoteException e) {
1325 // if the caller is dead then there is no one to care about remote exceptions
1326 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1327 Log.v(TAG, "failure while notifying response", e);
1328 }
1329 }
1330 }
1331 }
1332
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001333 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001334 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001335 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001336 + ", " + mAccount
1337 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1338 }
1339 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001340
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001341 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001342 public void renameAccount(
1343 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001344 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001345 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1346 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001347 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001348 + ", pid " + Binder.getCallingPid());
1349 }
1350 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001351 int userId = UserHandle.getCallingUserId();
1352 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001353 String msg = String.format(
1354 "uid %s cannot rename accounts of type: %s",
1355 callingUid,
1356 accountToRename.type);
1357 throw new SecurityException(msg);
1358 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001359 long identityToken = clearCallingIdentity();
1360 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001361 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001362 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001363 Bundle result = new Bundle();
1364 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1365 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1366 try {
1367 response.onResult(result);
1368 } catch (RemoteException e) {
1369 Log.w(TAG, e.getMessage());
1370 }
1371 } finally {
1372 restoreCallingIdentity(identityToken);
1373 }
1374 }
1375
1376 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001377 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001378 Account resultAccount = null;
1379 /*
1380 * Cancel existing notifications. Let authenticators
1381 * re-post notifications as required. But we don't know if
1382 * the authenticators have bound their notifications to
1383 * now stale account name data.
1384 *
1385 * With a rename api, we might not need to do this anymore but it
1386 * shouldn't hurt.
1387 */
1388 cancelNotification(
1389 getSigninRequiredNotificationId(accounts, accountToRename),
1390 new UserHandle(accounts.userId));
1391 synchronized(accounts.credentialsPermissionNotificationIds) {
1392 for (Pair<Pair<Account, String>, Integer> pair:
1393 accounts.credentialsPermissionNotificationIds.keySet()) {
1394 if (accountToRename.equals(pair.first.first)) {
1395 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1396 cancelNotification(id, new UserHandle(accounts.userId));
1397 }
1398 }
1399 }
1400 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001401 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001402 db.beginTransaction();
1403 boolean isSuccessful = false;
1404 Account renamedAccount = new Account(newName, accountToRename.type);
1405 try {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001406 final long accountId = getAccountIdLocked(db, accountToRename);
1407 if (accountId >= 0) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001408 final ContentValues values = new ContentValues();
1409 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001410 final String[] argsAccountId = { String.valueOf(accountId) };
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001411 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1412 // Update NAME/PREVIOUS_NAME in DE accounts table
1413 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001414 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1415 db.setTransactionSuccessful();
1416 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001417 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1418 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001419 }
1420 } finally {
1421 db.endTransaction();
1422 if (isSuccessful) {
1423 /*
1424 * Database transaction was successful. Clean up cached
1425 * data associated with the account in the user profile.
1426 */
1427 insertAccountIntoCacheLocked(accounts, renamedAccount);
1428 /*
1429 * Extract the data and token caches before removing the
1430 * old account to preserve the user data associated with
1431 * the account.
1432 */
1433 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1434 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1435 removeAccountFromCacheLocked(accounts, accountToRename);
1436 /*
1437 * Update the cached data associated with the renamed
1438 * account.
1439 */
1440 accounts.userDataCache.put(renamedAccount, tmpData);
1441 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1442 accounts.previousNameCache.put(
1443 renamedAccount,
1444 new AtomicReference<String>(accountToRename.name));
1445 resultAccount = renamedAccount;
1446
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001447 int parentUserId = accounts.userId;
1448 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001449 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001450 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001451 * those users with which the account was shared.
1452 */
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001453 List<UserInfo> users = getUserManager().getUsers(true);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001454 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001455 if (user.isRestricted()
1456 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001457 renameSharedAccountAsUser(accountToRename, newName, user.id);
1458 }
1459 }
1460 }
1461 sendAccountsChangedBroadcast(accounts.userId);
1462 }
1463 }
1464 }
1465 return resultAccount;
1466 }
1467
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001468 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001469 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001470 return userInfo != null && userInfo.canHaveProfile();
1471 }
1472
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001473 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001474 public void removeAccount(IAccountManagerResponse response, Account account,
1475 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001476 removeAccountAsUser(
1477 response,
1478 account,
1479 expectActivityLaunch,
1480 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001481 }
1482
1483 @Override
1484 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001485 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001486 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001487 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1488 Log.v(TAG, "removeAccount: " + account
1489 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001490 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001491 + ", pid " + Binder.getCallingPid()
1492 + ", for user id " + userId);
1493 }
1494 if (response == null) throw new IllegalArgumentException("response is null");
1495 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001496 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001497 if (isCrossUser(callingUid, userId)) {
1498 throw new SecurityException(
1499 String.format(
1500 "User %s tying remove account for %s" ,
1501 UserHandle.getCallingUserId(),
1502 userId));
1503 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001504 /*
1505 * Only the system or authenticator should be allowed to remove accounts for that
1506 * authenticator. This will let users remove accounts (via Settings in the system) but not
1507 * arbitrary applications (like competing authenticators).
1508 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001509 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001510 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1511 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001512 String msg = String.format(
1513 "uid %s cannot remove accounts of type: %s",
1514 callingUid,
1515 account.type);
1516 throw new SecurityException(msg);
1517 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001518 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001519 try {
1520 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1521 "User cannot modify accounts");
1522 } catch (RemoteException re) {
1523 }
1524 return;
1525 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001526 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001527 try {
1528 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1529 "User cannot modify accounts of this type (policy).");
1530 } catch (RemoteException re) {
1531 }
1532 return;
1533 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001534 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001535 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001536 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001537 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001538 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001539 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001540 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001541 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001542 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001543 }
1544 }
1545 }
1546
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001547 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1548
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001549 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001550 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1551 } finally {
1552 restoreCallingIdentity(identityToken);
1553 }
1554 }
1555
1556 @Override
1557 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001558 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001559 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1560 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001561 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001562 + ", pid " + Binder.getCallingPid());
1563 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001564 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001565 if (account == null) {
1566 /*
1567 * Null accounts should result in returning false, as per
1568 * AccountManage.addAccountExplicitly(...) java doc.
1569 */
1570 Log.e(TAG, "account is null");
1571 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001572 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001573 String msg = String.format(
1574 "uid %s cannot explicitly add accounts of type: %s",
1575 callingUid,
1576 account.type);
1577 throw new SecurityException(msg);
1578 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001579 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001580 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001581 long identityToken = clearCallingIdentity();
1582 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001583 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001584 } finally {
1585 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001586 }
Fred Quintana60307342009-03-24 22:48:12 -07001587 }
1588
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001589 private class RemoveAccountSession extends Session {
1590 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001591 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001592 Account account, boolean expectActivityLaunch) {
1593 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001594 true /* stripAuthTokenFromResult */, account.name,
1595 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001596 mAccount = account;
1597 }
1598
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001599 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001600 protected String toDebugString(long now) {
1601 return super.toDebugString(now) + ", removeAccount"
1602 + ", account " + mAccount;
1603 }
1604
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001605 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001606 public void run() throws RemoteException {
1607 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1608 }
1609
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001610 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001611 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001612 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001613 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1614 && !result.containsKey(AccountManager.KEY_INTENT)) {
1615 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001616 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001617 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001618 }
1619 IAccountManagerResponse response = getResponseAndClose();
1620 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001621 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1622 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1623 + response);
1624 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001625 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001626 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001627 try {
1628 response.onResult(result2);
1629 } catch (RemoteException e) {
1630 // ignore
1631 }
1632 }
1633 }
1634 super.onResult(result);
1635 }
1636 }
1637
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001638 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001639 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001640 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001641 }
1642
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001643 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001644 int deleted;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001645 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001646 if (!userUnlocked) {
1647 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
1648 + " is still locked. CE data will be removed later");
1649 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001650 synchronized (accounts.cacheLock) {
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001651 final SQLiteDatabase db = userUnlocked
1652 ? accounts.openHelper.getWritableDatabaseUserIsUnlocked()
1653 : accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001654 final long accountId = getAccountIdLocked(db, account);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001655 db.beginTransaction();
1656 try {
1657 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1658 + "=?", new String[]{account.name, account.type});
1659 if (userUnlocked) {
1660 // Delete from CE table
1661 deleted = db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1662 + "=?", new String[]{account.name, account.type});
1663 }
1664 db.setTransactionSuccessful();
1665 } finally {
1666 db.endTransaction();
1667 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001668 removeAccountFromCacheLocked(accounts, account);
1669 sendAccountsChangedBroadcast(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001670 String action = userUnlocked ? DebugDbHelper.ACTION_ACCOUNT_REMOVE
1671 : DebugDbHelper.ACTION_ACCOUNT_REMOVE_DE;
1672 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001673 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001674 long id = Binder.clearCallingIdentity();
1675 try {
1676 int parentUserId = accounts.userId;
1677 if (canHaveProfile(parentUserId)) {
1678 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001679 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001680 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001681 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001682 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001683 }
1684 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001685 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001686 } finally {
1687 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001688 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001689 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001690 }
1691
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001692 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001693 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001694 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001695 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1696 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001697 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001698 + ", pid " + Binder.getCallingPid());
1699 }
Fred Quintana382601f2010-03-25 12:25:10 -07001700 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1701 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001702 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001703 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001704 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001705 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001706 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001707 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001708 db.beginTransaction();
1709 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001710 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001711 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001712 db.setTransactionSuccessful();
1713 } finally {
1714 db.endTransaction();
1715 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001716 }
Fred Quintana60307342009-03-24 22:48:12 -07001717 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001718 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001719 }
1720 }
1721
Carlos Valdivia91979be2015-05-22 14:11:35 -07001722 private void invalidateCustomTokenLocked(
1723 UserAccounts accounts,
1724 String accountType,
1725 String authToken) {
1726 if (authToken == null || accountType == null) {
1727 return;
1728 }
1729 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001730 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001731 }
1732
Amith Yamasani04e0d262012-02-14 11:50:53 -08001733 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1734 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001735 if (authToken == null || accountType == null) {
1736 return;
1737 }
Fred Quintana33269202009-04-20 16:05:10 -07001738 Cursor cursor = db.rawQuery(
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001739 "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1740 + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1741 + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1742 + " FROM " + CE_TABLE_ACCOUNTS
1743 + " JOIN " + CE_TABLE_AUTHTOKENS
1744 + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1745 + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
1746 + " WHERE " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_AUTHTOKEN
1747 + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
Fred Quintana33269202009-04-20 16:05:10 -07001748 new String[]{authToken, accountType});
1749 try {
1750 while (cursor.moveToNext()) {
1751 long authTokenId = cursor.getLong(0);
1752 String accountName = cursor.getString(1);
1753 String authTokenType = cursor.getString(2);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001754 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001755 writeAuthTokenIntoCacheLocked(
1756 accounts,
1757 db,
1758 new Account(accountName, accountType),
1759 authTokenType,
1760 null);
Fred Quintana60307342009-03-24 22:48:12 -07001761 }
Fred Quintana33269202009-04-20 16:05:10 -07001762 } finally {
1763 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001764 }
1765 }
1766
Carlos Valdivia91979be2015-05-22 14:11:35 -07001767 private void saveCachedToken(
1768 UserAccounts accounts,
1769 Account account,
1770 String callerPkg,
1771 byte[] callerSigDigest,
1772 String tokenType,
1773 String token,
1774 long expiryMillis) {
1775
1776 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1777 return;
1778 }
1779 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001780 UserHandle.of(accounts.userId));
Carlos Valdivia91979be2015-05-22 14:11:35 -07001781 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001782 accounts.accountTokenCaches.put(
1783 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001784 }
1785 }
1786
Amith Yamasani04e0d262012-02-14 11:50:53 -08001787 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1788 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001789 if (account == null || type == null) {
1790 return false;
1791 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001792 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001793 UserHandle.of(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001794 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001795 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001796 db.beginTransaction();
1797 try {
1798 long accountId = getAccountIdLocked(db, account);
1799 if (accountId < 0) {
1800 return false;
1801 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001802 db.delete(CE_TABLE_AUTHTOKENS,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001803 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1804 new String[]{type});
1805 ContentValues values = new ContentValues();
1806 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1807 values.put(AUTHTOKENS_TYPE, type);
1808 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001809 if (db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001810 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001811 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001812 return true;
1813 }
Fred Quintana33269202009-04-20 16:05:10 -07001814 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001815 } finally {
1816 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001817 }
Fred Quintana60307342009-03-24 22:48:12 -07001818 }
1819 }
1820
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001821 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001822 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001823 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001824 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1825 Log.v(TAG, "peekAuthToken: " + account
1826 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001827 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001828 + ", pid " + Binder.getCallingPid());
1829 }
Fred Quintana382601f2010-03-25 12:25:10 -07001830 if (account == null) throw new IllegalArgumentException("account is null");
1831 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001832 int userId = UserHandle.getCallingUserId();
1833 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001834 String msg = String.format(
1835 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1836 callingUid,
1837 account.type);
1838 throw new SecurityException(msg);
1839 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001840 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001841 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
1842 + callingUid);
1843 return null;
1844 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001845 long identityToken = clearCallingIdentity();
1846 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001847 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001848 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001849 } finally {
1850 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001851 }
Fred Quintana60307342009-03-24 22:48:12 -07001852 }
1853
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001854 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001855 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001856 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001857 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1858 Log.v(TAG, "setAuthToken: " + account
1859 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001860 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001861 + ", pid " + Binder.getCallingPid());
1862 }
Fred Quintana382601f2010-03-25 12:25:10 -07001863 if (account == null) throw new IllegalArgumentException("account is null");
1864 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001865 int userId = UserHandle.getCallingUserId();
1866 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001867 String msg = String.format(
1868 "uid %s cannot set auth tokens associated with accounts of type: %s",
1869 callingUid,
1870 account.type);
1871 throw new SecurityException(msg);
1872 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001873 long identityToken = clearCallingIdentity();
1874 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001875 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001876 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001877 } finally {
1878 restoreCallingIdentity(identityToken);
1879 }
Fred Quintana60307342009-03-24 22:48:12 -07001880 }
1881
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001882 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001883 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001884 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001885 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1886 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001887 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001888 + ", pid " + Binder.getCallingPid());
1889 }
Fred Quintana382601f2010-03-25 12:25:10 -07001890 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001891 int userId = UserHandle.getCallingUserId();
1892 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001893 String msg = String.format(
1894 "uid %s cannot set secrets for accounts of type: %s",
1895 callingUid,
1896 account.type);
1897 throw new SecurityException(msg);
1898 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001899 long identityToken = clearCallingIdentity();
1900 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001901 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001902 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001903 } finally {
1904 restoreCallingIdentity(identityToken);
1905 }
Fred Quintana60307342009-03-24 22:48:12 -07001906 }
1907
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001908 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1909 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001910 if (account == null) {
1911 return;
1912 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001913 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001914 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001915 db.beginTransaction();
1916 try {
1917 final ContentValues values = new ContentValues();
1918 values.put(ACCOUNTS_PASSWORD, password);
1919 final long accountId = getAccountIdLocked(db, account);
1920 if (accountId >= 0) {
1921 final String[] argsAccountId = {String.valueOf(accountId)};
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001922 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1923 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001924 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001925 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001926 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001927
1928 String action = (password == null || password.length() == 0) ?
1929 DebugDbHelper.ACTION_CLEAR_PASSWORD
1930 : DebugDbHelper.ACTION_SET_PASSWORD;
1931 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001932 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001933 } finally {
1934 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001935 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001936 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001937 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001938 }
1939
Amith Yamasani04e0d262012-02-14 11:50:53 -08001940 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001941 Log.i(TAG, "the accounts changed, sending broadcast of "
1942 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001943 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001944 }
1945
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001946 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001947 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001948 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001949 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1950 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001951 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001952 + ", pid " + Binder.getCallingPid());
1953 }
Fred Quintana382601f2010-03-25 12:25:10 -07001954 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001955 int userId = UserHandle.getCallingUserId();
1956 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001957 String msg = String.format(
1958 "uid %s cannot clear passwords for accounts of type: %s",
1959 callingUid,
1960 account.type);
1961 throw new SecurityException(msg);
1962 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001963 long identityToken = clearCallingIdentity();
1964 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001965 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001966 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001967 } finally {
1968 restoreCallingIdentity(identityToken);
1969 }
Fred Quintana60307342009-03-24 22:48:12 -07001970 }
1971
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001972 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001973 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001974 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001975 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1976 Log.v(TAG, "setUserData: " + account
1977 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001978 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001979 + ", pid " + Binder.getCallingPid());
1980 }
Fred Quintana382601f2010-03-25 12:25:10 -07001981 if (key == null) throw new IllegalArgumentException("key is null");
1982 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001983 int userId = UserHandle.getCallingUserId();
1984 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001985 String msg = String.format(
1986 "uid %s cannot set user data for accounts of type: %s",
1987 callingUid,
1988 account.type);
1989 throw new SecurityException(msg);
1990 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001991 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001992 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001993 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00001994 synchronized (accounts.cacheLock) {
1995 if (!accountExistsCacheLocked(accounts, account)) {
1996 return;
1997 }
1998 setUserdataInternalLocked(accounts, account, key, value);
1999 }
Fred Quintana60307342009-03-24 22:48:12 -07002000 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002001 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002002 }
2003 }
2004
Simranjit Kohli858511c2016-03-10 18:36:11 +00002005 private boolean accountExistsCacheLocked(UserAccounts accounts, Account account) {
2006 if (accounts.accountCache.containsKey(account.type)) {
2007 for (Account acc : accounts.accountCache.get(account.type)) {
2008 if (acc.name.equals(account.name)) {
2009 return true;
2010 }
2011 }
2012 }
2013 return false;
2014 }
2015
2016 private void setUserdataInternalLocked(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002017 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07002018 if (account == null || key == null) {
2019 return;
2020 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002021 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2022 db.beginTransaction();
2023 try {
2024 long accountId = getAccountIdLocked(db, account);
2025 if (accountId < 0) {
2026 return;
2027 }
2028 long extrasId = getExtrasIdLocked(db, accountId, key);
2029 if (extrasId < 0) {
2030 extrasId = insertExtraLocked(db, accountId, key, value);
2031 if (extrasId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002032 return;
2033 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002034 } else {
2035 ContentValues values = new ContentValues();
2036 values.put(EXTRAS_VALUE, value);
2037 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
2038 return;
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00002039 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002040 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002041 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
2042 db.setTransactionSuccessful();
2043 } finally {
2044 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002045 }
2046 }
2047
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002048 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002049 if (result == null) {
2050 Log.e(TAG, "the result is unexpectedly null", new Exception());
2051 }
2052 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2053 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2054 + response);
2055 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002056 try {
2057 response.onResult(result);
2058 } catch (RemoteException e) {
2059 // if the caller is dead then there is no one to care about remote
2060 // exceptions
2061 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2062 Log.v(TAG, "failure while notifying response", e);
2063 }
2064 }
2065 }
2066
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002067 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002068 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2069 final String authTokenType)
2070 throws RemoteException {
2071 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002072 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2073
Fred Quintanad9640ec2012-05-23 12:37:00 -07002074 final int callingUid = getCallingUid();
2075 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07002076 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002077 throw new SecurityException("can only call from system");
2078 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002079 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002080 long identityToken = clearCallingIdentity();
2081 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002082 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002083 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2084 false /* stripAuthTokenFromResult */, null /* accountName */,
2085 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002086 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002087 protected String toDebugString(long now) {
2088 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002089 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002090 + ", authTokenType " + authTokenType;
2091 }
2092
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002093 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002094 public void run() throws RemoteException {
2095 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2096 }
2097
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002098 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002099 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002100 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002101 if (result != null) {
2102 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2103 Bundle bundle = new Bundle();
2104 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2105 super.onResult(bundle);
2106 return;
2107 } else {
2108 super.onResult(result);
2109 }
2110 }
2111 }.bind();
2112 } finally {
2113 restoreCallingIdentity(identityToken);
2114 }
2115 }
2116
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002117 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002118 public void getAuthToken(
2119 IAccountManagerResponse response,
2120 final Account account,
2121 final String authTokenType,
2122 final boolean notifyOnAuthFailure,
2123 final boolean expectActivityLaunch,
2124 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002125 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002126 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2127 Log.v(TAG, "getAuthToken: " + account
2128 + ", response " + response
2129 + ", authTokenType " + authTokenType
2130 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2131 + ", expectActivityLaunch " + expectActivityLaunch
2132 + ", caller's uid " + Binder.getCallingUid()
2133 + ", pid " + Binder.getCallingPid());
2134 }
Fred Quintana382601f2010-03-25 12:25:10 -07002135 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002136 try {
2137 if (account == null) {
2138 Slog.w(TAG, "getAuthToken called with null account");
2139 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2140 return;
2141 }
2142 if (authTokenType == null) {
2143 Slog.w(TAG, "getAuthToken called with null authTokenType");
2144 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2145 return;
2146 }
2147 } catch (RemoteException e) {
2148 Slog.w(TAG, "Failed to report error back to the client." + e);
2149 return;
2150 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002151 int userId = UserHandle.getCallingUserId();
2152 long ident = Binder.clearCallingIdentity();
2153 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002154 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002155 try {
2156 accounts = getUserAccounts(userId);
2157 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2158 AuthenticatorDescription.newKey(account.type), accounts.userId);
2159 } finally {
2160 Binder.restoreCallingIdentity(ident);
2161 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002162
Costin Manolachea40c6302010-12-13 14:50:45 -08002163 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002164 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002165
2166 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002167 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002168 final boolean permissionGranted =
2169 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002170
Carlos Valdivia91979be2015-05-22 14:11:35 -07002171 // Get the calling package. We will use it for the purpose of caching.
2172 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002173 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002174 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002175 try {
2176 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2177 } finally {
2178 Binder.restoreCallingIdentity(ident);
2179 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002180 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2181 String msg = String.format(
2182 "Uid %s is attempting to illegally masquerade as package %s!",
2183 callerUid,
2184 callerPkg);
2185 throw new SecurityException(msg);
2186 }
2187
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002188 // let authenticator know the identity of the caller
2189 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2190 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002191
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002192 if (notifyOnAuthFailure) {
2193 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002194 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002195
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002196 long identityToken = clearCallingIdentity();
2197 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002198 // Distill the caller's package signatures into a single digest.
2199 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2200
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002201 // if the caller has permission, do the peek. otherwise go the more expensive
2202 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002203 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002204 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002205 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002206 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002207 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2208 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2209 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002210 onResult(response, result);
2211 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002212 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002213 }
2214
Carlos Valdivia91979be2015-05-22 14:11:35 -07002215 if (customTokens) {
2216 /*
2217 * Look up tokens in the new cache only if the loginOptions don't have parameters
2218 * outside of those expected to be injected by the AccountManager, e.g.
2219 * ANDORID_PACKAGE_NAME.
2220 */
2221 String token = readCachedTokenInternal(
2222 accounts,
2223 account,
2224 authTokenType,
2225 callerPkg,
2226 callerPkgSigDigest);
2227 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002228 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2229 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2230 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002231 Bundle result = new Bundle();
2232 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2233 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2234 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2235 onResult(response, result);
2236 return;
2237 }
2238 }
2239
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002240 new Session(
2241 accounts,
2242 response,
2243 account.type,
2244 expectActivityLaunch,
2245 false /* stripAuthTokenFromResult */,
2246 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002247 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002248 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002249 protected String toDebugString(long now) {
2250 if (loginOptions != null) loginOptions.keySet();
2251 return super.toDebugString(now) + ", getAuthToken"
2252 + ", " + account
2253 + ", authTokenType " + authTokenType
2254 + ", loginOptions " + loginOptions
2255 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2256 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002257
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002258 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002259 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002260 // If the caller doesn't have permission then create and return the
2261 // "grant permission" intent instead of the "getAuthToken" intent.
2262 if (!permissionGranted) {
2263 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2264 } else {
2265 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2266 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002267 }
2268
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002269 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002270 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002271 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002272 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002273 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002274 Intent intent = newGrantCredentialsPermissionIntent(
2275 account,
2276 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002277 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002278 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002279 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002280 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002281 onResult(bundle);
2282 return;
2283 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002284 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002285 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002286 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2287 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002288 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002289 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002290 "the type and name should not be empty");
2291 return;
2292 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002293 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002294 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002295 saveAuthTokenToDatabase(
2296 mAccounts,
2297 resultAccount,
2298 authTokenType,
2299 authToken);
2300 }
2301 long expiryMillis = result.getLong(
2302 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2303 if (customTokens
2304 && expiryMillis > System.currentTimeMillis()) {
2305 saveCachedToken(
2306 mAccounts,
2307 account,
2308 callerPkg,
2309 callerPkgSigDigest,
2310 authTokenType,
2311 authToken,
2312 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002313 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002314 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002315
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002316 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002317 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002318 /*
2319 * Make sure that the supplied intent is owned by the authenticator
2320 * giving it to the system. Otherwise a malicious authenticator could
2321 * have users launching arbitrary activities by tricking users to
2322 * interact with malicious notifications.
2323 */
2324 checkKeyIntent(
2325 Binder.getCallingUid(),
2326 intent);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002327 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002328 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002329 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002330 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002331 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002332 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002333 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002334 }.bind();
2335 } finally {
2336 restoreCallingIdentity(identityToken);
2337 }
Fred Quintana60307342009-03-24 22:48:12 -07002338 }
2339
Carlos Valdivia91979be2015-05-22 14:11:35 -07002340 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2341 MessageDigest digester;
2342 try {
2343 digester = MessageDigest.getInstance("SHA-256");
2344 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2345 callerPkg, PackageManager.GET_SIGNATURES);
2346 for (Signature sig : pkgInfo.signatures) {
2347 digester.update(sig.toByteArray());
2348 }
2349 } catch (NoSuchAlgorithmException x) {
2350 Log.wtf(TAG, "SHA-256 should be available", x);
2351 digester = null;
2352 } catch (NameNotFoundException e) {
2353 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2354 digester = null;
2355 }
2356 return (digester == null) ? null : digester.digest();
2357 }
2358
Dianne Hackborn41203752012-08-31 14:05:51 -07002359 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2360 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002361 int uid = intent.getIntExtra(
2362 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2363 String authTokenType = intent.getStringExtra(
2364 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002365 final String titleAndSubtitle =
2366 mContext.getString(R.string.permission_request_notification_with_subtitle,
2367 account.name);
2368 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002369 String title = titleAndSubtitle;
2370 String subtitle = "";
2371 if (index > 0) {
2372 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002373 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002374 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002375 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002376 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002377 Notification n = new Notification.Builder(contextForUser)
2378 .setSmallIcon(android.R.drawable.stat_sys_warning)
2379 .setWhen(0)
2380 .setColor(contextForUser.getColor(
2381 com.android.internal.R.color.system_notification_accent_color))
2382 .setContentTitle(title)
2383 .setContentText(subtitle)
2384 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2385 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2386 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002387 installNotification(getCredentialPermissionNotificationId(
2388 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002389 }
2390
Costin Manolache5f383ad92010-12-02 16:44:46 -08002391 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002392 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002393
2394 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002395 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002396 // Since it was set in Eclair+ we can't change it without breaking apps using
2397 // the intent from a non-Activity context.
2398 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002399 intent.addCategory(
2400 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002401
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002402 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002403 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2404 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002405 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002406
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002407 return intent;
2408 }
2409
2410 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2411 int uid) {
2412 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002413 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002414 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002415 final Pair<Pair<Account, String>, Integer> key =
2416 new Pair<Pair<Account, String>, Integer>(
2417 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002418 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002419 if (id == null) {
2420 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002421 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002422 }
2423 }
2424 return id;
2425 }
2426
Amith Yamasani04e0d262012-02-14 11:50:53 -08002427 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002428 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002429 synchronized (accounts.signinRequiredNotificationIds) {
2430 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002431 if (id == null) {
2432 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002433 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002434 }
2435 }
2436 return id;
2437 }
2438
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002439 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002440 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002441 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002442 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002443 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002444 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2445 Log.v(TAG, "addAccount: accountType " + accountType
2446 + ", response " + response
2447 + ", authTokenType " + authTokenType
2448 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2449 + ", expectActivityLaunch " + expectActivityLaunch
2450 + ", caller's uid " + Binder.getCallingUid()
2451 + ", pid " + Binder.getCallingPid());
2452 }
Fred Quintana382601f2010-03-25 12:25:10 -07002453 if (response == null) throw new IllegalArgumentException("response is null");
2454 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002455
Amith Yamasani71e6c692013-03-24 17:39:28 -07002456 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002457 final int uid = Binder.getCallingUid();
2458 final int userId = UserHandle.getUserId(uid);
2459 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002460 try {
2461 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2462 "User is not allowed to add an account!");
2463 } catch (RemoteException re) {
2464 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002465 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002466 return;
2467 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002468 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002469 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002470 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2471 "User cannot modify accounts of this type (policy).");
2472 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002473 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002474 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2475 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002476 return;
2477 }
2478
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002479 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002480 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2481 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2482 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2483
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002484 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002485 long identityToken = clearCallingIdentity();
2486 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002487 UserAccounts accounts = getUserAccounts(usrId);
2488 logRecordWithUid(
2489 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002490 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002491 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002492 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002493 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002494 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002495 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002496 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002497 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002498
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002499 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002500 protected String toDebugString(long now) {
2501 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002502 + ", accountType " + accountType
2503 + ", requiredFeatures "
2504 + (requiredFeatures != null
2505 ? TextUtils.join(",", requiredFeatures)
2506 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002507 }
2508 }.bind();
2509 } finally {
2510 restoreCallingIdentity(identityToken);
2511 }
Fred Quintana60307342009-03-24 22:48:12 -07002512 }
2513
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002514 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002515 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2516 final String authTokenType, final String[] requiredFeatures,
2517 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002518 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002519 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002520 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2521 Log.v(TAG, "addAccount: accountType " + accountType
2522 + ", response " + response
2523 + ", authTokenType " + authTokenType
2524 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2525 + ", expectActivityLaunch " + expectActivityLaunch
2526 + ", caller's uid " + Binder.getCallingUid()
2527 + ", pid " + Binder.getCallingPid()
2528 + ", for user id " + userId);
2529 }
2530 if (response == null) throw new IllegalArgumentException("response is null");
2531 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002532 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002533 if (isCrossUser(callingUid, userId)) {
2534 throw new SecurityException(
2535 String.format(
2536 "User %s trying to add account for %s" ,
2537 UserHandle.getCallingUserId(),
2538 userId));
2539 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002540
2541 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002542 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002543 try {
2544 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2545 "User is not allowed to add an account!");
2546 } catch (RemoteException re) {
2547 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002548 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002549 return;
2550 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002551 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002552 try {
2553 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2554 "User cannot modify accounts of this type (policy).");
2555 } catch (RemoteException re) {
2556 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002557 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2558 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002559 return;
2560 }
2561
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002562 final int pid = Binder.getCallingPid();
2563 final int uid = Binder.getCallingUid();
2564 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2565 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2566 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2567
2568 long identityToken = clearCallingIdentity();
2569 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002570 UserAccounts accounts = getUserAccounts(userId);
2571 logRecordWithUid(
2572 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002573 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002574 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002575 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002576 @Override
2577 public void run() throws RemoteException {
2578 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2579 options);
2580 }
2581
2582 @Override
2583 protected String toDebugString(long now) {
2584 return super.toDebugString(now) + ", addAccount"
2585 + ", accountType " + accountType
2586 + ", requiredFeatures "
2587 + (requiredFeatures != null
2588 ? TextUtils.join(",", requiredFeatures)
2589 : null);
2590 }
2591 }.bind();
2592 } finally {
2593 restoreCallingIdentity(identityToken);
2594 }
2595 }
2596
Sandra Kwan78812282015-11-04 11:19:47 -08002597 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002598 public void startAddAccountSession(
2599 final IAccountManagerResponse response,
2600 final String accountType,
2601 final String authTokenType,
2602 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002603 final boolean expectActivityLaunch,
2604 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002605 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002606 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2607 Log.v(TAG,
2608 "startAddAccountSession: accountType " + accountType
2609 + ", response " + response
2610 + ", authTokenType " + authTokenType
2611 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2612 + ", expectActivityLaunch " + expectActivityLaunch
2613 + ", caller's uid " + Binder.getCallingUid()
2614 + ", pid " + Binder.getCallingPid());
2615 }
2616 if (response == null) {
2617 throw new IllegalArgumentException("response is null");
2618 }
2619 if (accountType == null) {
2620 throw new IllegalArgumentException("accountType is null");
2621 }
2622
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002623 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002624 // Only allow system to start session
2625 if (!isSystemUid(uid)) {
2626 String msg = String.format(
2627 "uid %s cannot stat add account session.",
2628 uid);
2629 throw new SecurityException(msg);
2630 }
2631
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002632 final int userId = UserHandle.getUserId(uid);
2633 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002634 try {
2635 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2636 "User is not allowed to add an account!");
2637 } catch (RemoteException re) {
2638 }
2639 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2640 return;
2641 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002642 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002643 try {
2644 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2645 "User cannot modify accounts of this type (policy).");
2646 } catch (RemoteException re) {
2647 }
2648 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2649 userId);
2650 return;
2651 }
Sandra Kwan78812282015-11-04 11:19:47 -08002652 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08002653 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2654 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2655 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2656
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002657 // Check to see if the Password should be included to the caller.
2658 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2659 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07002660 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002661
Sandra Kwan78812282015-11-04 11:19:47 -08002662 int usrId = UserHandle.getCallingUserId();
2663 long identityToken = clearCallingIdentity();
2664 try {
2665 UserAccounts accounts = getUserAccounts(usrId);
2666 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2667 TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002668 new StartAccountSession(
2669 accounts,
2670 response,
2671 accountType,
2672 expectActivityLaunch,
2673 null /* accountName */,
2674 false /* authDetailsRequired */,
2675 true /* updateLastAuthenticationTime */,
2676 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002677 @Override
2678 public void run() throws RemoteException {
2679 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2680 requiredFeatures, options);
2681 }
2682
2683 @Override
2684 protected String toDebugString(long now) {
2685 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2686 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2687 + accountType + ", requiredFeatures "
2688 + (requiredFeatures != null ? requiredFeaturesStr : null);
2689 }
2690 }.bind();
2691 } finally {
2692 restoreCallingIdentity(identityToken);
2693 }
2694 }
2695
2696 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2697 private abstract class StartAccountSession extends Session {
2698
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002699 private final boolean mIsPasswordForwardingAllowed;
2700
2701 public StartAccountSession(
2702 UserAccounts accounts,
2703 IAccountManagerResponse response,
2704 String accountType,
2705 boolean expectActivityLaunch,
2706 String accountName,
2707 boolean authDetailsRequired,
2708 boolean updateLastAuthenticationTime,
2709 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002710 super(accounts, response, accountType, expectActivityLaunch,
2711 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2712 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002713 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08002714 }
2715
2716 @Override
2717 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002718 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002719 mNumResults++;
2720 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08002721 if (result != null
2722 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08002723 checkKeyIntent(
2724 Binder.getCallingUid(),
2725 intent);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002726 // Omit passwords if the caller isn't permitted to see them.
2727 if (!mIsPasswordForwardingAllowed) {
2728 result.remove(AccountManager.KEY_PASSWORD);
2729 }
Sandra Kwan78812282015-11-04 11:19:47 -08002730 }
Sandra Kwan78812282015-11-04 11:19:47 -08002731 IAccountManagerResponse response;
2732 if (mExpectActivityLaunch && result != null
2733 && result.containsKey(AccountManager.KEY_INTENT)) {
2734 response = mResponse;
2735 } else {
2736 response = getResponseAndClose();
2737 }
2738 if (response == null) {
2739 return;
2740 }
2741 if (result == null) {
2742 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2743 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2744 + response);
2745 }
2746 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2747 "null bundle returned");
2748 return;
2749 }
2750
2751 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2752 // All AccountManager error codes are greater
2753 // than 0
2754 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2755 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2756 return;
2757 }
2758
2759 // Strip auth token from result.
2760 result.remove(AccountManager.KEY_AUTHTOKEN);
2761
2762 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2763 Log.v(TAG,
2764 getClass().getSimpleName() + " calling onResult() on response " + response);
2765 }
2766
2767 // Get the session bundle created by authenticator. The
2768 // bundle contains data necessary for finishing the session
2769 // later. The session bundle will be encrypted here and
2770 // decrypted later when trying to finish the session.
2771 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2772 if (sessionBundle != null) {
2773 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2774 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08002775 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002776 Log.w(TAG, "Account type in session bundle doesn't match request.");
2777 }
2778 // Add accountType info to session bundle. This will
2779 // override any value set by authenticator.
2780 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2781
2782 // Encrypt session bundle before returning to caller.
2783 try {
2784 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2785 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2786 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2787 } catch (GeneralSecurityException e) {
2788 if (Log.isLoggable(TAG, Log.DEBUG)) {
2789 Log.v(TAG, "Failed to encrypt session bundle!", e);
2790 }
2791 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2792 "failed to encrypt session bundle");
2793 return;
2794 }
2795 }
2796
2797 sendResponse(response, result);
2798 }
2799 }
2800
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002801 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08002802 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002803 @NonNull Bundle sessionBundle,
2804 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002805 Bundle appInfo,
2806 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002807 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08002808 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002809 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2810 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002811 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002812 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08002813 + ", caller's uid " + callingUid
2814 + ", caller's user id " + UserHandle.getCallingUserId()
2815 + ", pid " + Binder.getCallingPid()
2816 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002817 }
2818 if (response == null) {
2819 throw new IllegalArgumentException("response is null");
2820 }
2821
2822 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2823 // Account type is added to it before encryption.
2824 if (sessionBundle == null || sessionBundle.size() == 0) {
2825 throw new IllegalArgumentException("sessionBundle is empty");
2826 }
2827
Sandra Kwan0b84b452016-01-20 15:25:42 -08002828 // Only allow the system process to finish session for other users
2829 if (isCrossUser(callingUid, userId)) {
2830 throw new SecurityException(
2831 String.format(
2832 "User %s trying to finish session for %s without cross user permission",
2833 UserHandle.getCallingUserId(),
2834 userId));
2835 }
2836
Sandra Kwana578d112015-12-16 16:01:43 -08002837 // Only allow system to finish session
Sandra Kwan0b84b452016-01-20 15:25:42 -08002838 if (!isSystemUid(callingUid)) {
Sandra Kwana578d112015-12-16 16:01:43 -08002839 String msg = String.format(
Sandra Kwan0b84b452016-01-20 15:25:42 -08002840 "uid %s cannot finish session because it's not system uid.",
2841 callingUid);
Sandra Kwana578d112015-12-16 16:01:43 -08002842 throw new SecurityException(msg);
2843 }
2844
Sandra Kwan0b84b452016-01-20 15:25:42 -08002845 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002846 sendErrorResponse(response,
2847 AccountManager.ERROR_CODE_USER_RESTRICTED,
2848 "User is not allowed to add an account!");
2849 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2850 return;
2851 }
2852
2853 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002854 final Bundle decryptedBundle;
2855 final String accountType;
2856 // First decrypt session bundle to get account type for checking permission.
2857 try {
2858 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2859 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2860 if (decryptedBundle == null) {
2861 sendErrorResponse(
2862 response,
2863 AccountManager.ERROR_CODE_BAD_REQUEST,
2864 "failed to decrypt session bundle");
2865 return;
2866 }
2867 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2868 // Account type cannot be null. This should not happen if session bundle was created
2869 // properly by #StartAccountSession.
2870 if (TextUtils.isEmpty(accountType)) {
2871 sendErrorResponse(
2872 response,
2873 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2874 "accountType is empty");
2875 return;
2876 }
2877
2878 // If by any chances, decryptedBundle contains colliding keys with
2879 // system info
2880 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2881 // update credentials flow, we should replace with the new values of the current call.
2882 if (appInfo != null) {
2883 decryptedBundle.putAll(appInfo);
2884 }
2885
2886 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08002887 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002888 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2889 } catch (GeneralSecurityException e) {
2890 if (Log.isLoggable(TAG, Log.DEBUG)) {
2891 Log.v(TAG, "Failed to decrypt session bundle!", e);
2892 }
2893 sendErrorResponse(
2894 response,
2895 AccountManager.ERROR_CODE_BAD_REQUEST,
2896 "failed to decrypt session bundle");
2897 return;
2898 }
2899
Sandra Kwan0b84b452016-01-20 15:25:42 -08002900 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002901 sendErrorResponse(
2902 response,
2903 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2904 "User cannot modify accounts of this type (policy).");
2905 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2906 userId);
2907 return;
2908 }
2909
2910 long identityToken = clearCallingIdentity();
2911 try {
2912 UserAccounts accounts = getUserAccounts(userId);
2913 logRecordWithUid(
2914 accounts,
2915 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2916 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002917 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002918 new Session(
2919 accounts,
2920 response,
2921 accountType,
2922 expectActivityLaunch,
2923 true /* stripAuthTokenFromResult */,
2924 null /* accountName */,
2925 false /* authDetailsRequired */,
2926 true /* updateLastAuthenticationTime */) {
2927 @Override
2928 public void run() throws RemoteException {
2929 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2930 }
2931
2932 @Override
2933 protected String toDebugString(long now) {
2934 return super.toDebugString(now)
2935 + ", finishSession"
2936 + ", accountType " + accountType;
2937 }
2938 }.bind();
2939 } finally {
2940 restoreCallingIdentity(identityToken);
2941 }
2942 }
2943
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002944 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002945 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2946 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2947 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2948 long identityToken = clearCallingIdentity();
2949 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002950 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002951 } finally {
2952 restoreCallingIdentity(identityToken);
2953 }
2954 }
2955
2956 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002957 public void confirmCredentialsAsUser(
2958 IAccountManagerResponse response,
2959 final Account account,
2960 final Bundle options,
2961 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002962 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002963 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002964 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002965 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2966 Log.v(TAG, "confirmCredentials: " + account
2967 + ", response " + response
2968 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002969 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002970 + ", pid " + Binder.getCallingPid());
2971 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002972 // Only allow the system process to read accounts of other users
2973 if (isCrossUser(callingUid, userId)) {
2974 throw new SecurityException(
2975 String.format(
2976 "User %s trying to confirm account credentials for %s" ,
2977 UserHandle.getCallingUserId(),
2978 userId));
2979 }
Fred Quintana382601f2010-03-25 12:25:10 -07002980 if (response == null) throw new IllegalArgumentException("response is null");
2981 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002982 long identityToken = clearCallingIdentity();
2983 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002984 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002985 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002986 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002987 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002988 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002989 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002990 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002991 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002992 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002993 protected String toDebugString(long now) {
2994 return super.toDebugString(now) + ", confirmCredentials"
2995 + ", " + account;
2996 }
2997 }.bind();
2998 } finally {
2999 restoreCallingIdentity(identityToken);
3000 }
Fred Quintana60307342009-03-24 22:48:12 -07003001 }
3002
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003003 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003004 public void updateCredentials(IAccountManagerResponse response, final Account account,
3005 final String authTokenType, final boolean expectActivityLaunch,
3006 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003007 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003008 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3009 Log.v(TAG, "updateCredentials: " + account
3010 + ", response " + response
3011 + ", authTokenType " + authTokenType
3012 + ", expectActivityLaunch " + expectActivityLaunch
3013 + ", caller's uid " + Binder.getCallingUid()
3014 + ", pid " + Binder.getCallingPid());
3015 }
Fred Quintana382601f2010-03-25 12:25:10 -07003016 if (response == null) throw new IllegalArgumentException("response is null");
3017 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003018 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003019 long identityToken = clearCallingIdentity();
3020 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003021 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003022 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003023 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003024 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003025 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003026 public void run() throws RemoteException {
3027 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3028 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003029 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003030 protected String toDebugString(long now) {
3031 if (loginOptions != null) loginOptions.keySet();
3032 return super.toDebugString(now) + ", updateCredentials"
3033 + ", " + account
3034 + ", authTokenType " + authTokenType
3035 + ", loginOptions " + loginOptions;
3036 }
3037 }.bind();
3038 } finally {
3039 restoreCallingIdentity(identityToken);
3040 }
Fred Quintana60307342009-03-24 22:48:12 -07003041 }
3042
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003043 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003044 public void startUpdateCredentialsSession(
3045 IAccountManagerResponse response,
3046 final Account account,
3047 final String authTokenType,
3048 final boolean expectActivityLaunch,
3049 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003050 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003051 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3052 Log.v(TAG,
3053 "startUpdateCredentialsSession: " + account + ", response " + response
3054 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3055 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3056 + ", pid " + Binder.getCallingPid());
3057 }
3058 if (response == null) {
3059 throw new IllegalArgumentException("response is null");
3060 }
3061 if (account == null) {
3062 throw new IllegalArgumentException("account is null");
3063 }
Sandra Kwana578d112015-12-16 16:01:43 -08003064
3065 final int uid = Binder.getCallingUid();
3066 // Only allow system to start session
3067 if (!isSystemUid(uid)) {
3068 String msg = String.format(
3069 "uid %s cannot start update credentials session.",
3070 uid);
3071 throw new SecurityException(msg);
3072 }
3073
Sandra Kwane68c37e2015-11-12 17:11:49 -08003074 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003075
3076 // Check to see if the Password should be included to the caller.
3077 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3078 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003079 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003080
Sandra Kwane68c37e2015-11-12 17:11:49 -08003081 long identityToken = clearCallingIdentity();
3082 try {
3083 UserAccounts accounts = getUserAccounts(userId);
3084 new StartAccountSession(
3085 accounts,
3086 response,
3087 account.type,
3088 expectActivityLaunch,
3089 account.name,
3090 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003091 true /* updateLastCredentialTime */,
3092 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003093 @Override
3094 public void run() throws RemoteException {
3095 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3096 loginOptions);
3097 }
3098
3099 @Override
3100 protected String toDebugString(long now) {
3101 if (loginOptions != null)
3102 loginOptions.keySet();
3103 return super.toDebugString(now)
3104 + ", startUpdateCredentialsSession"
3105 + ", " + account
3106 + ", authTokenType " + authTokenType
3107 + ", loginOptions " + loginOptions;
3108 }
3109 }.bind();
3110 } finally {
3111 restoreCallingIdentity(identityToken);
3112 }
3113 }
3114
3115 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003116 public void isCredentialsUpdateSuggested(
3117 IAccountManagerResponse response,
3118 final Account account,
3119 final String statusToken) {
3120 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3121 Log.v(TAG,
3122 "isCredentialsUpdateSuggested: " + account + ", response " + response
3123 + ", caller's uid " + Binder.getCallingUid()
3124 + ", pid " + Binder.getCallingPid());
3125 }
3126 if (response == null) {
3127 throw new IllegalArgumentException("response is null");
3128 }
3129 if (account == null) {
3130 throw new IllegalArgumentException("account is null");
3131 }
3132 if (TextUtils.isEmpty(statusToken)) {
3133 throw new IllegalArgumentException("status token is empty");
3134 }
3135
3136 int uid = Binder.getCallingUid();
3137 // Only allow system to start session
3138 if (!isSystemUid(uid)) {
3139 String msg = String.format(
3140 "uid %s cannot stat add account session.",
3141 uid);
3142 throw new SecurityException(msg);
3143 }
3144
3145 int usrId = UserHandle.getCallingUserId();
3146 long identityToken = clearCallingIdentity();
3147 try {
3148 UserAccounts accounts = getUserAccounts(usrId);
3149 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3150 false /* stripAuthTokenFromResult */, account.name,
3151 false /* authDetailsRequired */) {
3152 @Override
3153 protected String toDebugString(long now) {
3154 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3155 + ", " + account;
3156 }
3157
3158 @Override
3159 public void run() throws RemoteException {
3160 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3161 }
3162
3163 @Override
3164 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003165 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003166 IAccountManagerResponse response = getResponseAndClose();
3167 if (response == null) {
3168 return;
3169 }
3170
3171 if (result == null) {
3172 sendErrorResponse(
3173 response,
3174 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3175 "null bundle");
3176 return;
3177 }
3178
3179 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3180 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3181 + response);
3182 }
3183 // Check to see if an error occurred. We know if an error occurred because all
3184 // error codes are greater than 0.
3185 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3186 sendErrorResponse(response,
3187 result.getInt(AccountManager.KEY_ERROR_CODE),
3188 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3189 return;
3190 }
3191 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3192 sendErrorResponse(
3193 response,
3194 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3195 "no result in response");
3196 return;
3197 }
3198 final Bundle newResult = new Bundle();
3199 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3200 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3201 sendResponse(response, newResult);
3202 }
3203 }.bind();
3204 } finally {
3205 restoreCallingIdentity(identityToken);
3206 }
3207 }
3208
3209 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003210 public void editProperties(IAccountManagerResponse response, final String accountType,
3211 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003212 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003213 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3214 Log.v(TAG, "editProperties: accountType " + accountType
3215 + ", response " + response
3216 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003217 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003218 + ", pid " + Binder.getCallingPid());
3219 }
Fred Quintana382601f2010-03-25 12:25:10 -07003220 if (response == null) throw new IllegalArgumentException("response is null");
3221 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003222 int userId = UserHandle.getCallingUserId();
3223 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003224 String msg = String.format(
3225 "uid %s cannot edit authenticator properites for account type: %s",
3226 callingUid,
3227 accountType);
3228 throw new SecurityException(msg);
3229 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003230 long identityToken = clearCallingIdentity();
3231 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003232 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003233 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003234 true /* stripAuthTokenFromResult */, null /* accountName */,
3235 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003236 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003237 public void run() throws RemoteException {
3238 mAuthenticator.editProperties(this, mAccountType);
3239 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003240 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003241 protected String toDebugString(long now) {
3242 return super.toDebugString(now) + ", editProperties"
3243 + ", accountType " + accountType;
3244 }
3245 }.bind();
3246 } finally {
3247 restoreCallingIdentity(identityToken);
3248 }
Fred Quintana60307342009-03-24 22:48:12 -07003249 }
3250
Amith Yamasani12747872015-12-07 14:19:49 -08003251 @Override
3252 public boolean someUserHasAccount(@NonNull final Account account) {
3253 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3254 throw new SecurityException("Only system can check for accounts across users");
3255 }
3256 final long token = Binder.clearCallingIdentity();
3257 try {
3258 AccountAndUser[] allAccounts = getAllAccounts();
3259 for (int i = allAccounts.length - 1; i >= 0; i--) {
3260 if (allAccounts[i].account.equals(account)) {
3261 return true;
3262 }
3263 }
3264 return false;
3265 } finally {
3266 Binder.restoreCallingIdentity(token);
3267 }
3268 }
3269
Fred Quintana33269202009-04-20 16:05:10 -07003270 private class GetAccountsByTypeAndFeatureSession extends Session {
3271 private final String[] mFeatures;
3272 private volatile Account[] mAccountsOfType = null;
3273 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3274 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003275 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003276
Amith Yamasani04e0d262012-02-14 11:50:53 -08003277 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003278 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003279 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003280 true /* stripAuthTokenFromResult */, null /* accountName */,
3281 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003282 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003283 mFeatures = features;
3284 }
3285
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003286 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003287 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003288 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003289 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3290 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003291 }
Fred Quintana33269202009-04-20 16:05:10 -07003292 // check whether each account matches the requested features
3293 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
3294 mCurrentAccount = 0;
3295
3296 checkAccount();
3297 }
3298
3299 public void checkAccount() {
3300 if (mCurrentAccount >= mAccountsOfType.length) {
3301 sendResult();
3302 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003303 }
Fred Quintana33269202009-04-20 16:05:10 -07003304
Fred Quintana29e94b82010-03-10 12:11:51 -08003305 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3306 if (accountAuthenticator == null) {
3307 // It is possible that the authenticator has died, which is indicated by
3308 // mAuthenticator being set to null. If this happens then just abort.
3309 // There is no need to send back a result or error in this case since
3310 // that already happened when mAuthenticator was cleared.
3311 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3312 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3313 + " connected to the authenticator, " + toDebugString());
3314 }
3315 return;
3316 }
Fred Quintana33269202009-04-20 16:05:10 -07003317 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003318 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003319 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003320 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003321 }
3322 }
3323
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003324 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003325 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003326 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003327 mNumResults++;
3328 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003329 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003330 return;
3331 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003332 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003333 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3334 }
3335 mCurrentAccount++;
3336 checkAccount();
3337 }
3338
3339 public void sendResult() {
3340 IAccountManagerResponse response = getResponseAndClose();
3341 if (response != null) {
3342 try {
3343 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3344 for (int i = 0; i < accounts.length; i++) {
3345 accounts[i] = mAccountsWithFeatures.get(i);
3346 }
Fred Quintana56285a62010-12-02 14:20:51 -08003347 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3348 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3349 + response);
3350 }
Fred Quintana33269202009-04-20 16:05:10 -07003351 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003352 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003353 response.onResult(result);
3354 } catch (RemoteException e) {
3355 // if the caller is dead then there is no one to care about remote exceptions
3356 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3357 Log.v(TAG, "failure while notifying response", e);
3358 }
3359 }
3360 }
3361 }
3362
3363
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003364 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003365 protected String toDebugString(long now) {
3366 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3367 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3368 }
3369 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003370
Amith Yamasani04e0d262012-02-14 11:50:53 -08003371 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003372 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003373 * @hide
3374 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003375 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003376 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003377 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003378 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3379 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003380 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003381 return new Account[0];
3382 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003383 long identityToken = clearCallingIdentity();
3384 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003385 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003386 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003387 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003388 callingUid,
3389 null, // packageName
3390 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003391 } finally {
3392 restoreCallingIdentity(identityToken);
3393 }
3394 }
3395
Amith Yamasanif29f2362012-04-05 18:29:52 -07003396 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003397 * Returns accounts for all running users.
3398 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003399 * @hide
3400 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003401 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003402 public AccountAndUser[] getRunningAccounts() {
3403 final int[] runningUserIds;
3404 try {
3405 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3406 } catch (RemoteException e) {
3407 // Running in system_server; should never happen
3408 throw new RuntimeException(e);
3409 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003410 return getAccounts(runningUserIds);
3411 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003412
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003413 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003414 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003415 public AccountAndUser[] getAllAccounts() {
3416 final List<UserInfo> users = getUserManager().getUsers();
3417 final int[] userIds = new int[users.size()];
3418 for (int i = 0; i < userIds.length; i++) {
3419 userIds[i] = users.get(i).id;
3420 }
3421 return getAccounts(userIds);
3422 }
3423
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003424 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003425 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003426 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003427 for (int userId : userIds) {
3428 UserAccounts userAccounts = getUserAccounts(userId);
3429 if (userAccounts == null) continue;
3430 synchronized (userAccounts.cacheLock) {
3431 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3432 Binder.getCallingUid(), null);
3433 for (int a = 0; a < accounts.length; a++) {
3434 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003435 }
3436 }
3437 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003438
3439 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3440 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003441 }
3442
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003443 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003444 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003445 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3446 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003447 }
3448
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003449 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003450 private Account[] getAccountsAsUser(
3451 String type,
3452 int userId,
3453 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003454 int packageUid,
3455 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003456 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003457 // Only allow the system process to read accounts of other users
3458 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003459 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003460 && mContext.checkCallingOrSelfPermission(
3461 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3462 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003463 throw new SecurityException("User " + UserHandle.getCallingUserId()
3464 + " trying to get account for " + userId);
3465 }
3466
Fred Quintana56285a62010-12-02 14:20:51 -08003467 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3468 Log.v(TAG, "getAccounts: accountType " + type
3469 + ", caller's uid " + Binder.getCallingUid()
3470 + ", pid " + Binder.getCallingPid());
3471 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003472 // If the original calling app was using the framework account chooser activity, we'll
3473 // be passed in the original caller's uid here, which is what should be used for filtering.
3474 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3475 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003476 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003477 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003478
Svetoslavf3f02ac2015-09-08 14:36:35 -07003479 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3480 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003481 if (visibleAccountTypes.isEmpty()
3482 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003483 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003484 } else if (visibleAccountTypes.contains(type)) {
3485 // Prune the list down to just the requested type.
3486 visibleAccountTypes = new ArrayList<>();
3487 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003488 } // else aggregate all the visible accounts (it won't matter if the
3489 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003490
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003491 long identityToken = clearCallingIdentity();
3492 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003493 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003494 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003495 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003496 callingUid,
3497 callingPackage,
3498 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003499 } finally {
3500 restoreCallingIdentity(identityToken);
3501 }
3502 }
3503
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003504 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003505 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003506 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003507 int callingUid,
3508 String callingPackage,
3509 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003510 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003511 ArrayList<Account> visibleAccounts = new ArrayList<>();
3512 for (String visibleType : visibleAccountTypes) {
3513 Account[] accountsForType = getAccountsFromCacheLocked(
3514 userAccounts, visibleType, callingUid, callingPackage);
3515 if (accountsForType != null) {
3516 visibleAccounts.addAll(Arrays.asList(accountsForType));
3517 }
3518 }
3519 Account[] result = new Account[visibleAccounts.size()];
3520 for (int i = 0; i < visibleAccounts.size(); i++) {
3521 result[i] = visibleAccounts.get(i);
3522 }
3523 return result;
3524 }
3525 }
3526
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003527 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003528 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
3529 checkManageUsersPermission("addSharedAccountsFromParentUser");
3530 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3531 for (Account account : accounts) {
3532 addSharedAccountAsUser(account, userId);
3533 }
3534 }
3535
3536 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003537 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003538 UserAccounts accounts = getUserAccounts(userId);
3539 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003540 ContentValues values = new ContentValues();
3541 values.put(ACCOUNTS_NAME, account.name);
3542 values.put(ACCOUNTS_TYPE, account.type);
3543 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3544 new String[] {account.name, account.type});
3545 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3546 if (accountId < 0) {
3547 Log.w(TAG, "insertAccountIntoDatabase: " + account
3548 + ", skipping the DB insert failed");
3549 return false;
3550 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003551 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003552 return true;
3553 }
3554
3555 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003556 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3557 userId = handleIncomingUser(userId);
3558 UserAccounts accounts = getUserAccounts(userId);
3559 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003560 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003561 final ContentValues values = new ContentValues();
3562 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003563 int r = db.update(
3564 TABLE_SHARED_ACCOUNTS,
3565 values,
3566 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3567 new String[] { account.name, account.type });
3568 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003569 int callingUid = getCallingUid();
3570 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3571 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003572 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003573 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003574 }
3575 return r > 0;
3576 }
3577
3578 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003579 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003580 return removeSharedAccountAsUser(account, userId, getCallingUid());
3581 }
3582
3583 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003584 userId = handleIncomingUser(userId);
3585 UserAccounts accounts = getUserAccounts(userId);
3586 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003587 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003588 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3589 new String[] {account.name, account.type});
3590 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003591 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3592 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003593 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003594 }
3595 return r > 0;
3596 }
3597
3598 @Override
3599 public Account[] getSharedAccountsAsUser(int userId) {
3600 userId = handleIncomingUser(userId);
3601 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003602 ArrayList<Account> accountList = new ArrayList<>();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003603 Cursor cursor = null;
3604 try {
3605 cursor = accounts.openHelper.getReadableDatabase()
3606 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3607 null, null, null, null, null);
3608 if (cursor != null && cursor.moveToFirst()) {
3609 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3610 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3611 do {
3612 accountList.add(new Account(cursor.getString(nameIndex),
3613 cursor.getString(typeIndex)));
3614 } while (cursor.moveToNext());
3615 }
3616 } finally {
3617 if (cursor != null) {
3618 cursor.close();
3619 }
3620 }
3621 Account[] accountArray = new Account[accountList.size()];
3622 accountList.toArray(accountArray);
3623 return accountArray;
3624 }
3625
3626 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003627 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003628 public Account[] getAccounts(String type, String opPackageName) {
3629 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003630 }
3631
Amith Yamasani27db4682013-03-30 17:07:47 -07003632 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003633 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003634 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003635 int callingUid = Binder.getCallingUid();
3636 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3637 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3638 + callingUid + " with uid=" + uid);
3639 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003640 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3641 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003642 }
3643
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003644 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003645 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003646 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3647 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003648 int packageUid = -1;
3649 try {
3650 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07003651 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3652 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003653 } catch (RemoteException re) {
3654 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3655 return new Account[0];
3656 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003657 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3658 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003659 }
3660
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003661 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003662 public void getAccountsByFeatures(
3663 IAccountManagerResponse response,
3664 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003665 String[] features,
3666 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003667 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003668 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3669 Log.v(TAG, "getAccounts: accountType " + type
3670 + ", response " + response
3671 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003672 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003673 + ", pid " + Binder.getCallingPid());
3674 }
Fred Quintana382601f2010-03-25 12:25:10 -07003675 if (response == null) throw new IllegalArgumentException("response is null");
3676 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003677 int userId = UserHandle.getCallingUserId();
3678
Svetoslavf3f02ac2015-09-08 14:36:35 -07003679 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3680 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003681 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003682 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003683 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003684 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3685 try {
3686 response.onResult(result);
3687 } catch (RemoteException e) {
3688 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3689 }
3690 return;
3691 }
Fred Quintana33269202009-04-20 16:05:10 -07003692 long identityToken = clearCallingIdentity();
3693 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003694 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003695 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003696 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003697 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003698 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003699 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08003700 Bundle result = new Bundle();
3701 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3702 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003703 return;
3704 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003705 new GetAccountsByTypeAndFeatureSession(
3706 userAccounts,
3707 response,
3708 type,
3709 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003710 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07003711 } finally {
3712 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07003713 }
3714 }
3715
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003716 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3717 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3718 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3719 try {
3720 if (cursor.moveToNext()) {
3721 return cursor.getLong(0);
3722 }
3723 return -1;
3724 } finally {
3725 cursor.close();
3726 }
3727 }
3728
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003729 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07003730 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003731 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07003732 try {
3733 if (cursor.moveToNext()) {
3734 return cursor.getLong(0);
3735 }
3736 return -1;
3737 } finally {
3738 cursor.close();
3739 }
3740 }
3741
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003742 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003743 Cursor cursor = db.query(CE_TABLE_EXTRAS, new String[]{EXTRAS_ID},
Fred Quintana60307342009-03-24 22:48:12 -07003744 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3745 new String[]{key}, null, null, null);
3746 try {
3747 if (cursor.moveToNext()) {
3748 return cursor.getLong(0);
3749 }
3750 return -1;
3751 } finally {
3752 cursor.close();
3753 }
3754 }
3755
Fred Quintanaa698f422009-04-08 19:14:54 -07003756 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07003757 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07003758 IAccountManagerResponse mResponse;
3759 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003760 final boolean mExpectActivityLaunch;
3761 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003762 final String mAccountName;
3763 // Indicates if we need to add auth details(like last credential time)
3764 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003765 // If set, we need to update the last authenticated time. This is
3766 // currently
3767 // used on
3768 // successful confirming credentials.
3769 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07003770
Fred Quintana33269202009-04-20 16:05:10 -07003771 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07003772 private int mNumRequestContinued = 0;
3773 private int mNumErrors = 0;
3774
Fred Quintana60307342009-03-24 22:48:12 -07003775 IAccountAuthenticator mAuthenticator = null;
3776
Fred Quintana8570f742010-02-18 10:32:54 -08003777 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003778 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003779
Amith Yamasani04e0d262012-02-14 11:50:53 -08003780 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003781 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3782 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003783 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3784 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3785 }
3786
3787 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3788 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3789 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07003790 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003791 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07003792 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08003793 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003794 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07003795 mResponse = response;
3796 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003797 mExpectActivityLaunch = expectActivityLaunch;
3798 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003799 mAccountName = accountName;
3800 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003801 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003802
Fred Quintanaa698f422009-04-08 19:14:54 -07003803 synchronized (mSessions) {
3804 mSessions.put(toString(), this);
3805 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003806 if (response != null) {
3807 try {
3808 response.asBinder().linkToDeath(this, 0 /* flags */);
3809 } catch (RemoteException e) {
3810 mResponse = null;
3811 binderDied();
3812 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003813 }
Fred Quintana60307342009-03-24 22:48:12 -07003814 }
3815
Fred Quintanaa698f422009-04-08 19:14:54 -07003816 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07003817 if (mResponse == null) {
3818 // this session has already been closed
3819 return null;
3820 }
Fred Quintana60307342009-03-24 22:48:12 -07003821 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07003822 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07003823 return response;
3824 }
3825
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003826 /**
3827 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
3828 * security policy.
3829 *
3830 * In particular we want to make sure that the Authenticator doesn't try to trick users
3831 * into launching aribtrary intents on the device via by tricking to click authenticator
3832 * supplied entries in the system Settings app.
3833 */
3834 protected void checkKeyIntent(
3835 int authUid,
3836 Intent intent) throws SecurityException {
3837 long bid = Binder.clearCallingIdentity();
3838 try {
3839 PackageManager pm = mContext.getPackageManager();
3840 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3841 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
3842 int targetUid = targetActivityInfo.applicationInfo.uid;
3843 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid)) {
3844 String pkgName = targetActivityInfo.packageName;
3845 String activityName = targetActivityInfo.name;
3846 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
3847 + "does not share a signature with the supplying authenticator (%s).";
3848 throw new SecurityException(
3849 String.format(tmpl, activityName, pkgName, mAccountType));
3850 }
3851 } finally {
3852 Binder.restoreCallingIdentity(bid);
3853 }
3854 }
3855
Fred Quintanaa698f422009-04-08 19:14:54 -07003856 private void close() {
3857 synchronized (mSessions) {
3858 if (mSessions.remove(toString()) == null) {
3859 // the session was already closed, so bail out now
3860 return;
3861 }
3862 }
3863 if (mResponse != null) {
3864 // stop listening for response deaths
3865 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3866
3867 // clear this so that we don't accidentally send any further results
3868 mResponse = null;
3869 }
3870 cancelTimeout();
3871 unbind();
3872 }
3873
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003874 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003875 public void binderDied() {
3876 mResponse = null;
3877 close();
3878 }
3879
3880 protected String toDebugString() {
3881 return toDebugString(SystemClock.elapsedRealtime());
3882 }
3883
3884 protected String toDebugString(long now) {
3885 return "Session: expectLaunch " + mExpectActivityLaunch
3886 + ", connected " + (mAuthenticator != null)
3887 + ", stats (" + mNumResults + "/" + mNumRequestContinued
3888 + "/" + mNumErrors + ")"
3889 + ", lifetime " + ((now - mCreationTime) / 1000.0);
3890 }
3891
Fred Quintana60307342009-03-24 22:48:12 -07003892 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003893 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3894 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3895 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003896 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003897 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003898 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003899 }
3900 }
3901
3902 private void unbind() {
3903 if (mAuthenticator != null) {
3904 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003905 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003906 }
3907 }
3908
Fred Quintana60307342009-03-24 22:48:12 -07003909 public void cancelTimeout() {
3910 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3911 }
3912
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003913 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003914 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003915 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003916 try {
3917 run();
3918 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003919 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003920 "remote exception");
3921 }
Fred Quintana60307342009-03-24 22:48:12 -07003922 }
3923
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003924 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003925 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003926 mAuthenticator = null;
3927 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003928 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003929 try {
3930 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3931 "disconnected");
3932 } catch (RemoteException e) {
3933 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3934 Log.v(TAG, "Session.onServiceDisconnected: "
3935 + "caught RemoteException while responding", e);
3936 }
3937 }
Fred Quintana60307342009-03-24 22:48:12 -07003938 }
3939 }
3940
Fred Quintanab839afc2009-10-14 15:57:28 -07003941 public abstract void run() throws RemoteException;
3942
Fred Quintana60307342009-03-24 22:48:12 -07003943 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003944 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003945 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003946 try {
3947 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3948 "timeout");
3949 } catch (RemoteException e) {
3950 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3951 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3952 e);
3953 }
3954 }
Fred Quintana60307342009-03-24 22:48:12 -07003955 }
3956 }
3957
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003958 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003959 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003960 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07003961 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003962 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003963 if (result != null) {
3964 boolean isSuccessfulConfirmCreds = result.getBoolean(
3965 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003966 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003967 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3968 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003969 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003970 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3971 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003972 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003973 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003974 if (needUpdate || mAuthDetailsRequired) {
3975 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3976 if (needUpdate && accountPresent) {
3977 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3978 }
3979 if (mAuthDetailsRequired) {
3980 long lastAuthenticatedTime = -1;
3981 if (accountPresent) {
3982 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3983 mAccounts.openHelper.getReadableDatabase(),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003984 "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3985 + " FROM " +
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003986 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3987 + ACCOUNTS_TYPE + "=?",
3988 new String[] {
3989 mAccountName, mAccountType
3990 });
3991 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003992 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003993 lastAuthenticatedTime);
3994 }
3995 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003996 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003997 if (result != null
3998 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003999 checkKeyIntent(
4000 Binder.getCallingUid(),
4001 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004002 }
4003 if (result != null
4004 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004005 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4006 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004007 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4008 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004009 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4010 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004011 }
Fred Quintana60307342009-03-24 22:48:12 -07004012 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004013 IAccountManagerResponse response;
4014 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004015 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004016 response = mResponse;
4017 } else {
4018 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004019 }
Fred Quintana60307342009-03-24 22:48:12 -07004020 if (response != null) {
4021 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004022 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004023 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4024 Log.v(TAG, getClass().getSimpleName()
4025 + " calling onError() on response " + response);
4026 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004027 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004028 "null bundle returned");
4029 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004030 if (mStripAuthTokenFromResult) {
4031 result.remove(AccountManager.KEY_AUTHTOKEN);
4032 }
Fred Quintana56285a62010-12-02 14:20:51 -08004033 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4034 Log.v(TAG, getClass().getSimpleName()
4035 + " calling onResult() on response " + response);
4036 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004037 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4038 (intent == null)) {
4039 // All AccountManager error codes are greater than 0
4040 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4041 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4042 } else {
4043 response.onResult(result);
4044 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004045 }
Fred Quintana60307342009-03-24 22:48:12 -07004046 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004047 // if the caller is dead then there is no one to care about remote exceptions
4048 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4049 Log.v(TAG, "failure while notifying response", e);
4050 }
Fred Quintana60307342009-03-24 22:48:12 -07004051 }
4052 }
4053 }
Fred Quintana60307342009-03-24 22:48:12 -07004054
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004055 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004056 public void onRequestContinued() {
4057 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004058 }
4059
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004060 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004061 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004062 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004063 IAccountManagerResponse response = getResponseAndClose();
4064 if (response != null) {
4065 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004066 Log.v(TAG, getClass().getSimpleName()
4067 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004068 }
4069 try {
4070 response.onError(errorCode, errorMessage);
4071 } catch (RemoteException e) {
4072 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4073 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4074 }
4075 }
4076 } else {
4077 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4078 Log.v(TAG, "Session.onError: already closed");
4079 }
Fred Quintana60307342009-03-24 22:48:12 -07004080 }
4081 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004082
4083 /**
4084 * find the component name for the authenticator and initiate a bind
4085 * if no authenticator or the bind fails then return false, otherwise return true
4086 */
4087 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004088 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4089 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4090 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004091 if (authenticatorInfo == null) {
4092 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4093 Log.v(TAG, "there is no authenticator for " + authenticatorType
4094 + ", bailing out");
4095 }
4096 return false;
4097 }
4098
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004099 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004100 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004101 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4102 + " which isn't encryption aware");
4103 return false;
4104 }
4105
Fred Quintanab839afc2009-10-14 15:57:28 -07004106 Intent intent = new Intent();
4107 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4108 intent.setComponent(authenticatorInfo.componentName);
4109 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4110 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4111 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004112 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004113 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004114 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4115 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4116 }
4117 return false;
4118 }
4119
Fred Quintanab839afc2009-10-14 15:57:28 -07004120 return true;
4121 }
Fred Quintana60307342009-03-24 22:48:12 -07004122 }
4123
4124 private class MessageHandler extends Handler {
4125 MessageHandler(Looper looper) {
4126 super(looper);
4127 }
Costin Manolache3348f142009-09-29 18:58:36 -07004128
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004129 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004130 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004131 switch (msg.what) {
4132 case MESSAGE_TIMED_OUT:
4133 Session session = (Session)msg.obj;
4134 session.onTimedOut();
4135 break;
4136
Amith Yamasani5be347b2013-03-31 17:44:31 -07004137 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004138 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004139 break;
4140
Fred Quintana60307342009-03-24 22:48:12 -07004141 default:
4142 throw new IllegalStateException("unhandled message: " + msg.what);
4143 }
4144 }
4145 }
4146
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004147 @VisibleForTesting
4148 String getPreNDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07004149 File systemDir = Environment.getDataSystemDirectory();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004150 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
4151 PRE_N_DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004152 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07004153 // Migrate old file, if it exists, to the new location.
4154 // Make sure the new file doesn't already exist. A dummy file could have been
4155 // accidentally created in the old location, causing the new one to become corrupted
4156 // as well.
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004157 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07004158 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07004159 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07004160 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07004161 if (!userDir.exists()) {
4162 if (!userDir.mkdirs()) {
4163 throw new IllegalStateException("User dir cannot be created: " + userDir);
4164 }
4165 }
4166 if (!oldFile.renameTo(databaseFile)) {
4167 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
4168 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004169 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004170 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004171 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08004172 }
4173
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004174 @VisibleForTesting
4175 String getDeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004176 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
4177 DE_DATABASE_NAME);
4178 return databaseFile.getPath();
4179 }
4180
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004181 @VisibleForTesting
4182 String getCeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004183 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4184 CE_DATABASE_NAME);
4185 return databaseFile.getPath();
4186 }
4187
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004188 private static class DebugDbHelper{
4189 private DebugDbHelper() {
4190 }
4191
4192 private static String TABLE_DEBUG = "debug_table";
4193
4194 // Columns for the table
4195 private static String ACTION_TYPE = "action_type";
4196 private static String TIMESTAMP = "time";
4197 private static String CALLER_UID = "caller_uid";
4198 private static String TABLE_NAME = "table_name";
4199 private static String KEY = "primary_key";
4200
4201 // These actions correspond to the occurrence of real actions. Since
4202 // these are called by the authenticators, the uid associated will be
4203 // of the authenticator.
4204 private static String ACTION_SET_PASSWORD = "action_set_password";
4205 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4206 private static String ACTION_ACCOUNT_ADD = "action_account_add";
4207 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004208 private static String ACTION_ACCOUNT_REMOVE_DE = "action_account_remove_de";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004209 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4210 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4211
4212 // These actions don't necessarily correspond to any action on
4213 // accountDb taking place. As an example, there might be a request for
4214 // addingAccount, which might not lead to addition of account on grounds
4215 // of bad authentication. We will still be logging it to keep track of
4216 // who called.
4217 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4218 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004219 private static String ACTION_SYNC_DE_CE_ACCOUNTS = "action_sync_de_ce_accounts";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004220
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004221 //This action doesn't add account to accountdb. Account is only
4222 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08004223 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004224 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4225 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08004226
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004227 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4228
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004229 private static void createDebugTable(SQLiteDatabase db) {
4230 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4231 + ACCOUNTS_ID + " INTEGER,"
4232 + ACTION_TYPE + " TEXT NOT NULL, "
4233 + TIMESTAMP + " DATETIME,"
4234 + CALLER_UID + " INTEGER NOT NULL,"
4235 + TABLE_NAME + " TEXT NOT NULL,"
4236 + KEY + " INTEGER PRIMARY KEY)");
4237 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4238 }
4239 }
4240
4241 private void logRecord(UserAccounts accounts, String action, String tableName) {
4242 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4243 logRecord(db, action, tableName, -1, accounts);
4244 }
4245
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004246 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4247 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4248 logRecord(db, action, tableName, -1, accounts, uid);
4249 }
4250
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004251 /*
4252 * This function receives an opened writable database.
4253 */
4254 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4255 UserAccounts userAccount) {
4256 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4257 }
4258
4259 /*
4260 * This function receives an opened writable database.
4261 */
4262 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4263 UserAccounts userAccount, int callingUid) {
4264 SQLiteStatement logStatement = userAccount.statementForLogging;
4265 logStatement.bindLong(1, accountId);
4266 logStatement.bindString(2, action);
4267 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4268 logStatement.bindLong(4, callingUid);
4269 logStatement.bindString(5, tableName);
4270 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
4271 logStatement.execute();
4272 logStatement.clearBindings();
4273 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4274 % MAX_DEBUG_DB_SIZE;
4275 }
4276
4277 /*
4278 * This should only be called once to compile the sql statement for logging
4279 * and to find the insertion point.
4280 */
4281 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4282 UserAccounts userAccount) {
4283 // Initialize the count if not done earlier.
4284 int size = (int) getDebugTableRowCount(db);
4285 if (size >= MAX_DEBUG_DB_SIZE) {
4286 // Table is full, and we need to find the point where to insert.
4287 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4288 } else {
4289 userAccount.debugDbInsertionPoint = size;
4290 }
4291 compileSqlStatementForLogging(db, userAccount);
4292 }
4293
4294 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4295 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4296 + " VALUES (?,?,?,?,?,?)";
4297 userAccount.statementForLogging = db.compileStatement(sql);
4298 }
4299
4300 private long getDebugTableRowCount(SQLiteDatabase db) {
4301 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4302 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4303 }
4304
4305 /*
4306 * Finds the row key where the next insertion should take place. This should
4307 * be invoked only if the table has reached its full capacity.
4308 */
4309 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4310 // This query finds the smallest timestamp value (and if 2 records have
4311 // same timestamp, the choose the lower id).
4312 String queryCountDebugDbRows = new StringBuilder()
4313 .append("SELECT ").append(DebugDbHelper.KEY)
4314 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4315 .append(" ORDER BY ")
4316 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4317 .append(" LIMIT 1")
4318 .toString();
4319 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4320 }
4321
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004322 static class PreNDatabaseHelper extends SQLiteOpenHelper {
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004323 private final Context mContext;
4324 private final int mUserId;
4325
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004326 public PreNDatabaseHelper(Context context, int userId, String preNDatabaseName) {
4327 super(context, preNDatabaseName, null, PRE_N_DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004328 mContext = context;
4329 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004330 }
4331
4332 @Override
4333 public void onCreate(SQLiteDatabase db) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004334 // We use PreNDatabaseHelper only if pre-N db exists
4335 throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004336 }
4337
Amith Yamasani67df64b2012-12-14 12:09:36 -08004338 private void createSharedAccountsTable(SQLiteDatabase db) {
4339 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4340 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4341 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4342 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4343 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4344 }
4345
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004346 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4347 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4348 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4349 }
4350
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004351 private void addOldAccountNameColumn(SQLiteDatabase db) {
4352 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4353 }
4354
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004355 private void addDebugTable(SQLiteDatabase db) {
4356 DebugDbHelper.createDebugTable(db);
4357 }
4358
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004359 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004360 db.execSQL(""
4361 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4362 + " BEGIN"
4363 + " DELETE FROM " + TABLE_AUTHTOKENS
4364 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4365 + " DELETE FROM " + TABLE_EXTRAS
4366 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004367 + " DELETE FROM " + TABLE_GRANTS
4368 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004369 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004370 }
4371
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004372 private void createGrantsTable(SQLiteDatabase db) {
4373 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4374 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4375 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4376 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4377 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4378 + "," + GRANTS_GRANTEE_UID + "))");
4379 }
4380
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004381 private void populateMetaTableWithAuthTypeAndUID(
4382 SQLiteDatabase db,
4383 Map<String, Integer> authTypeAndUIDMap) {
4384 Iterator<Entry<String, Integer>> iterator = authTypeAndUIDMap.entrySet().iterator();
4385 while (iterator.hasNext()) {
4386 Entry<String, Integer> entry = iterator.next();
4387 ContentValues values = new ContentValues();
4388 values.put(META_KEY,
4389 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
4390 values.put(META_VALUE, entry.getValue());
4391 db.insert(TABLE_META, null, values);
4392 }
4393 }
4394
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004395 /**
4396 * Pre-N database may need an upgrade before splitting
4397 */
Fred Quintana60307342009-03-24 22:48:12 -07004398 @Override
4399 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004400 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004401
Fred Quintanaa698f422009-04-08 19:14:54 -07004402 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004403 // no longer need to do anything since the work is done
4404 // when upgrading from version 2
4405 oldVersion++;
4406 }
4407
4408 if (oldVersion == 2) {
4409 createGrantsTable(db);
4410 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4411 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004412 oldVersion++;
4413 }
Costin Manolache3348f142009-09-29 18:58:36 -07004414
4415 if (oldVersion == 3) {
4416 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4417 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4418 oldVersion++;
4419 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004420
4421 if (oldVersion == 4) {
4422 createSharedAccountsTable(db);
4423 oldVersion++;
4424 }
4425
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004426 if (oldVersion == 5) {
4427 addOldAccountNameColumn(db);
4428 oldVersion++;
4429 }
4430
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004431 if (oldVersion == 6) {
4432 addLastSuccessfullAuthenticatedTimeColumn(db);
4433 oldVersion++;
4434 }
4435
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004436 if (oldVersion == 7) {
4437 addDebugTable(db);
4438 oldVersion++;
4439 }
4440
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004441 if (oldVersion == 8) {
4442 populateMetaTableWithAuthTypeAndUID(
4443 db,
4444 AccountManagerService.getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
4445 oldVersion++;
4446 }
4447
Amith Yamasani67df64b2012-12-14 12:09:36 -08004448 if (oldVersion != newVersion) {
4449 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4450 }
Fred Quintana60307342009-03-24 22:48:12 -07004451 }
4452
4453 @Override
4454 public void onOpen(SQLiteDatabase db) {
4455 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4456 }
4457 }
4458
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004459 static class DeDatabaseHelper extends SQLiteOpenHelper {
4460
4461 private final int mUserId;
4462 private volatile boolean mCeAttached;
4463
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004464 private DeDatabaseHelper(Context context, int userId, String deDatabaseName) {
4465 super(context, deDatabaseName, null, DE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004466 mUserId = userId;
4467 }
4468
4469 /**
4470 * This call needs to be made while the mCacheLock is held. The way to
4471 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4472 * @param db The database.
4473 */
4474 @Override
4475 public void onCreate(SQLiteDatabase db) {
4476 Log.i(TAG, "Creating DE database for user " + mUserId);
4477 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4478 + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4479 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4480 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4481 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4482 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4483 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4484
4485 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4486 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4487 + META_VALUE + " TEXT)");
4488
4489 createGrantsTable(db);
4490 createSharedAccountsTable(db);
4491 createAccountsDeletionTrigger(db);
4492 DebugDbHelper.createDebugTable(db);
4493 }
4494
4495 private void createSharedAccountsTable(SQLiteDatabase db) {
4496 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4497 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4498 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4499 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4500 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4501 }
4502
4503 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4504 db.execSQL(""
4505 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4506 + " BEGIN"
4507 + " DELETE FROM " + TABLE_GRANTS
4508 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4509 + " END");
4510 }
4511
4512 private void createGrantsTable(SQLiteDatabase db) {
4513 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4514 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4515 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4516 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4517 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4518 + "," + GRANTS_GRANTEE_UID + "))");
4519 }
4520
4521 @Override
4522 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4523 Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4524
4525 if (oldVersion != newVersion) {
4526 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4527 }
4528 }
4529
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004530 public void attachCeDatabase(File ceDbFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004531 SQLiteDatabase db = getWritableDatabase();
4532 db.execSQL("ATTACH DATABASE '" + ceDbFile.getPath()+ "' AS ceDb");
4533 mCeAttached = true;
4534 }
4535
4536 public boolean isCeDatabaseAttached() {
4537 return mCeAttached;
4538 }
4539
4540
4541 public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
4542 if(!mCeAttached) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004543 Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user " + mUserId
4544 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004545 }
4546 return super.getReadableDatabase();
4547 }
4548
4549 public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
4550 if(!mCeAttached) {
4551 Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004552 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004553 }
4554 return super.getWritableDatabase();
4555 }
4556
4557 @Override
4558 public void onOpen(SQLiteDatabase db) {
4559 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
4560 }
4561
4562 private void migratePreNDbToDe(File preNDbFile) {
4563 Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
4564 SQLiteDatabase db = getWritableDatabase();
4565 db.execSQL("ATTACH DATABASE '" + preNDbFile.getPath() + "' AS preNDb");
4566 db.beginTransaction();
4567 // Copy accounts fields
4568 db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
4569 + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4570 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4571 + ") "
4572 + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4573 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4574 + " FROM preNDb." + TABLE_ACCOUNTS);
4575 // Copy SHARED_ACCOUNTS
4576 db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
4577 + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
4578 "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4579 + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
4580 // Copy DEBUG_TABLE
4581 db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
4582 + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4583 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4584 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
4585 "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4586 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4587 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
4588 + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
4589 // Copy GRANTS
4590 db.execSQL("INSERT INTO " + TABLE_GRANTS
4591 + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4592 + GRANTS_GRANTEE_UID + ") " +
4593 "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4594 + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
4595 // Copy META
4596 db.execSQL("INSERT INTO " + TABLE_META
4597 + "(" + META_KEY + "," + META_VALUE + ") "
4598 + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
4599 db.setTransactionSuccessful();
4600 db.endTransaction();
4601
4602 db.execSQL("DETACH DATABASE preNDb");
4603 }
4604
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004605 static DeDatabaseHelper create(
4606 Context context,
4607 int userId,
4608 File preNDatabaseFile,
4609 File deDatabaseFile) {
4610 boolean newDbExists = deDatabaseFile.exists();
4611 DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId,
4612 deDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004613 // If the db just created, and there is a legacy db, migrate it
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004614 if (!newDbExists && preNDatabaseFile.exists()) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004615 // Migrate legacy db to the latest version - PRE_N_DATABASE_VERSION
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004616 PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId,
4617 preNDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004618 // Open the database to force upgrade if required
4619 preNDatabaseHelper.getWritableDatabase();
4620 preNDatabaseHelper.close();
4621 // Move data without SPII to DE
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004622 deDatabaseHelper.migratePreNDbToDe(preNDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004623 }
4624 return deDatabaseHelper;
4625 }
4626 }
4627
4628 static class CeDatabaseHelper extends SQLiteOpenHelper {
4629
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004630 public CeDatabaseHelper(Context context, String ceDatabaseName) {
4631 super(context, ceDatabaseName, null, CE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004632 }
4633
4634 /**
4635 * This call needs to be made while the mCacheLock is held.
4636 * @param db The database.
4637 */
4638 @Override
4639 public void onCreate(SQLiteDatabase db) {
4640 Log.i(TAG, "Creating CE database " + getDatabaseName());
4641 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4642 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4643 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4644 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4645 + ACCOUNTS_PASSWORD + " TEXT, "
4646 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4647
4648 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
4649 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4650 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4651 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
4652 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
4653 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
4654
4655 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
4656 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4657 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
4658 + EXTRAS_KEY + " TEXT NOT NULL, "
4659 + EXTRAS_VALUE + " TEXT, "
4660 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
4661
4662 createAccountsDeletionTrigger(db);
4663 }
4664
4665 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4666 db.execSQL(""
4667 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4668 + " BEGIN"
4669 + " DELETE FROM " + TABLE_AUTHTOKENS
4670 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4671 + " DELETE FROM " + TABLE_EXTRAS
4672 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4673 + " END");
4674 }
4675
4676 @Override
4677 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4678 Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
4679
4680 if (oldVersion == 9) {
4681 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4682 Log.v(TAG, "onUpgrade upgrading to v10");
4683 }
4684 db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
4685 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
4686 // Recreate the trigger, since the old one references the table to be removed
4687 db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
4688 createAccountsDeletionTrigger(db);
4689 db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
4690 db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
4691 oldVersion ++;
4692 }
4693
4694 if (oldVersion != newVersion) {
4695 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4696 }
4697 }
4698
4699 @Override
4700 public void onOpen(SQLiteDatabase db) {
4701 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
4702 }
4703
4704 static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
4705 String type) {
4706 Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
4707 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
4708 new String[]{name, type}, null, null, null);
4709 try {
4710 if (cursor.moveToNext()) {
4711 return cursor.getString(0);
4712 }
4713 return null;
4714 } finally {
4715 cursor.close();
4716 }
4717 }
4718
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004719 static List<Account> findCeAccountsNotInDe(SQLiteDatabase db) {
4720 // Select accounts from CE that do not exist in DE
4721 Cursor cursor = db.rawQuery(
4722 "SELECT " + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4723 + " FROM " + CE_TABLE_ACCOUNTS
4724 + " WHERE NOT EXISTS "
4725 + " (SELECT " + ACCOUNTS_ID + " FROM " + TABLE_ACCOUNTS
4726 + " WHERE " + ACCOUNTS_ID + "=" + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
4727 + " )", null);
4728 try {
4729 List<Account> accounts = new ArrayList<>(cursor.getCount());
4730 while (cursor.moveToNext()) {
4731 String accountName = cursor.getString(0);
4732 String accountType = cursor.getString(1);
4733 accounts.add(new Account(accountName, accountType));
4734 }
4735 return accounts;
4736 } finally {
4737 cursor.close();
4738 }
4739 }
4740
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004741 /**
4742 * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
4743 * it also performs migration to the new CE database.
4744 * @param context
4745 * @param userId id of the user where the database is located
4746 */
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004747 static CeDatabaseHelper create(
4748 Context context,
4749 int userId,
4750 File preNDatabaseFile,
4751 File ceDatabaseFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004752 boolean newDbExists = ceDatabaseFile.exists();
4753 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4754 Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004755 + preNDatabaseFile.exists() + " newDbExists=" + newDbExists);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004756 }
4757 boolean removeOldDb = false;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004758 if (!newDbExists && preNDatabaseFile.exists()) {
4759 removeOldDb = migratePreNDbToCe(preNDatabaseFile, ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004760 }
4761 // Try to open and upgrade if necessary
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004762 CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, ceDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004763 ceHelper.getWritableDatabase();
4764 ceHelper.close();
4765 if (removeOldDb) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004766 Slog.i(TAG, "Migration complete - removing pre-N db " + preNDatabaseFile);
4767 if (!SQLiteDatabase.deleteDatabase(preNDatabaseFile)) {
4768 Slog.e(TAG, "Cannot remove pre-N db " + preNDatabaseFile);
4769 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004770 }
4771 return ceHelper;
4772 }
4773
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004774 private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004775 Slog.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004776 try {
4777 FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
4778 } catch (IOException e) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07004779 Slog.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004780 // Try to remove potentially damaged file if I/O error occurred
4781 deleteDbFileWarnIfFailed(ceDbFile);
4782 return false;
4783 }
4784 return true;
4785 }
4786 }
4787
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004788 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004789 return asBinder();
4790 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004791
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004792 /**
4793 * Searches array of arguments for the specified string
4794 * @param args array of argument strings
4795 * @param value value to search for
4796 * @return true if the value is contained in the array
4797 */
4798 private static boolean scanArgs(String[] args, String value) {
4799 if (args != null) {
4800 for (String arg : args) {
4801 if (value.equals(arg)) {
4802 return true;
4803 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004804 }
4805 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004806 return false;
4807 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004808
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004809 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004810 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07004811 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4812 != PackageManager.PERMISSION_GRANTED) {
4813 fout.println("Permission Denial: can't dump AccountsManager from from pid="
4814 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4815 + " without permission " + android.Manifest.permission.DUMP);
4816 return;
4817 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004818 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004819 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004820
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004821 final List<UserInfo> users = getUserManager().getUsers();
4822 for (UserInfo user : users) {
4823 ipw.println("User " + user + ":");
4824 ipw.increaseIndent();
4825 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4826 ipw.println();
4827 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08004828 }
4829 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004830
Amith Yamasani04e0d262012-02-14 11:50:53 -08004831 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4832 String[] args, boolean isCheckinRequest) {
4833 synchronized (userAccounts.cacheLock) {
4834 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004835
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004836 if (isCheckinRequest) {
4837 // This is a checkin request. *Only* upload the account types and the count of each.
4838 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4839 null, null, ACCOUNTS_TYPE, null, null);
4840 try {
4841 while (cursor.moveToNext()) {
4842 // print type,count
4843 fout.println(cursor.getString(0) + "," + cursor.getString(1));
4844 }
4845 } finally {
4846 if (cursor != null) {
4847 cursor.close();
4848 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004849 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004850 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004851 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07004852 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004853 fout.println("Accounts: " + accounts.length);
4854 for (Account account : accounts) {
4855 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004856 }
Fred Quintana307da1a2010-01-21 14:24:20 -08004857
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004858 // Add debug information.
4859 fout.println();
4860 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4861 null, null, null, null, DebugDbHelper.TIMESTAMP);
4862 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4863 fout.println("Accounts History");
4864 try {
4865 while (cursor.moveToNext()) {
4866 // print type,count
4867 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4868 cursor.getString(2) + "," + cursor.getString(3) + ","
4869 + cursor.getString(4) + "," + cursor.getString(5));
4870 }
4871 } finally {
4872 cursor.close();
4873 }
4874
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004875 fout.println();
4876 synchronized (mSessions) {
4877 final long now = SystemClock.elapsedRealtime();
4878 fout.println("Active Sessions: " + mSessions.size());
4879 for (Session session : mSessions.values()) {
4880 fout.println(" " + session.toDebugString(now));
4881 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004882 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004883
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004884 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004885 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004886 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004887 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004888 }
4889
Amith Yamasani04e0d262012-02-14 11:50:53 -08004890 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07004891 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004892 long identityToken = clearCallingIdentity();
4893 try {
4894 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4895 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4896 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004897
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004898 if (intent.getComponent() != null &&
4899 GrantCredentialsPermissionActivity.class.getName().equals(
4900 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004901 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004902 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004903 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004904 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004905 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004906 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07004907 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004908 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004909 Notification n = new Notification.Builder(contextForUser)
4910 .setWhen(0)
4911 .setSmallIcon(android.R.drawable.stat_sys_warning)
4912 .setColor(contextForUser.getColor(
4913 com.android.internal.R.color.system_notification_accent_color))
4914 .setContentTitle(String.format(notificationTitleFormat, account.name))
4915 .setContentText(message)
4916 .setContentIntent(PendingIntent.getActivityAsUser(
4917 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4918 null, user))
4919 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004920 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004921 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004922 } finally {
4923 restoreCallingIdentity(identityToken);
4924 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004925 }
4926
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004927 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004928 protected void installNotification(final int notificationId, final Notification n,
4929 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08004930 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004931 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08004932 }
4933
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004934 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004935 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004936 long identityToken = clearCallingIdentity();
4937 try {
4938 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004939 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004940 } finally {
4941 restoreCallingIdentity(identityToken);
4942 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004943 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004944
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004945 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
4946 for (String perm : permissions) {
4947 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
4948 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4949 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
4950 }
4951 final int opCode = AppOpsManager.permissionToOpCode(perm);
4952 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
4953 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
4954 return true;
4955 }
4956 }
4957 }
4958 return false;
4959 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004960
Amith Yamasani67df64b2012-12-14 12:09:36 -08004961 private int handleIncomingUser(int userId) {
4962 try {
4963 return ActivityManagerNative.getDefault().handleIncomingUser(
4964 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
4965 } catch (RemoteException re) {
4966 // Shouldn't happen, local.
4967 }
4968 return userId;
4969 }
4970
Christopher Tateccbf84f2013-05-08 15:25:41 -07004971 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004972 final int callingUserId = UserHandle.getUserId(callingUid);
4973
4974 final PackageManager userPackageManager;
4975 try {
4976 userPackageManager = mContext.createPackageContextAsUser(
4977 "android", 0, new UserHandle(callingUserId)).getPackageManager();
4978 } catch (NameNotFoundException e) {
4979 return false;
4980 }
4981
4982 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07004983 for (String name : packages) {
4984 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004985 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08004986 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08004987 && (packageInfo.applicationInfo.privateFlags
4988 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07004989 return true;
4990 }
4991 } catch (PackageManager.NameNotFoundException e) {
4992 return false;
4993 }
4994 }
4995 return false;
4996 }
4997
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004998 private boolean permissionIsGranted(
4999 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07005000 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07005001 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005002 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07005003 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08005004 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005005 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5006 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08005007 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005008 + ": is authenticator? " + fromAuthenticator
5009 + ", has explicit permission? " + hasExplicitGrants);
5010 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07005011 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005012 }
5013
Svetoslavf3f02ac2015-09-08 14:36:35 -07005014 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5015 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005016 if (accountType == null) {
5017 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005018 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005019 return getTypesVisibleToCaller(callingUid, userId,
5020 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005021 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005022 }
5023
5024 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5025 if (accountType == null) {
5026 return false;
5027 } else {
5028 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5029 }
5030 }
5031
Svetoslavf3f02ac2015-09-08 14:36:35 -07005032 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5033 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005034 boolean isPermitted =
5035 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
5036 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005037 return getTypesForCaller(callingUid, userId, isPermitted);
5038 }
5039
5040 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
5041 return getTypesForCaller(callingUid, userId, false);
5042 }
5043
5044 private List<String> getTypesForCaller(
5045 int callingUid, int userId, boolean isOtherwisePermitted) {
5046 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005047 long identityToken = Binder.clearCallingIdentity();
5048 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5049 try {
5050 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5051 } finally {
5052 Binder.restoreCallingIdentity(identityToken);
5053 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005054 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005055 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005056 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5057 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
5058 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005059 }
5060 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005061 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005062 }
5063
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005064 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5065 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5066 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5067 if (account.name.equals(accountName)) {
5068 return true;
5069 }
5070 }
5071 }
5072 return false;
5073 }
5074
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005075 private static void checkManageUsersPermission(String message) {
5076 if (ActivityManager.checkComponentPermission(
5077 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5078 != PackageManager.PERMISSION_GRANTED) {
5079 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5080 }
5081 }
5082
Amith Yamasani04e0d262012-02-14 11:50:53 -08005083 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5084 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07005085 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005086 return true;
5087 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005088 UserAccounts accounts = getUserAccountsForCaller();
5089 synchronized (accounts.cacheLock) {
5090 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
5091 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005092 account.name, account.type};
5093 final boolean permissionGranted =
5094 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
5095 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5096 // TODO: Skip this check when running automated tests. Replace this
5097 // with a more general solution.
5098 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08005099 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005100 + " but ignoring since device is in test harness.");
5101 return true;
5102 }
5103 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005104 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005105 }
5106
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005107 private boolean isSystemUid(int callingUid) {
5108 String[] packages = null;
5109 long ident = Binder.clearCallingIdentity();
5110 try {
5111 packages = mPackageManager.getPackagesForUid(callingUid);
5112 } finally {
5113 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005114 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005115 if (packages != null) {
5116 for (String name : packages) {
5117 try {
5118 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5119 if (packageInfo != null
5120 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5121 != 0) {
5122 return true;
5123 }
5124 } catch (PackageManager.NameNotFoundException e) {
5125 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5126 }
5127 }
5128 } else {
5129 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005130 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005131 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005132 }
5133
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005134 /** Succeeds if any of the specified permissions are granted. */
5135 private void checkReadAccountsPermitted(
5136 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005137 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005138 int userId,
5139 String opPackageName) {
5140 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005141 String msg = String.format(
5142 "caller uid %s cannot access %s accounts",
5143 callingUid,
5144 accountType);
5145 Log.w(TAG, " " + msg);
5146 throw new SecurityException(msg);
5147 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005148 }
5149
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005150 private boolean canUserModifyAccounts(int userId, int callingUid) {
5151 // the managing app can always modify accounts
5152 if (isProfileOwner(callingUid)) {
5153 return true;
5154 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005155 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5156 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5157 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005158 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005159 return true;
5160 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005161
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005162 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5163 // the managing app can always modify accounts
5164 if (isProfileOwner(callingUid)) {
5165 return true;
5166 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005167 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5168 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005169 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005170 if (typesArray == null) {
5171 return true;
5172 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005173 for (String forbiddenType : typesArray) {
5174 if (forbiddenType.equals(accountType)) {
5175 return false;
5176 }
5177 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005178 return true;
5179 }
5180
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005181 private boolean isProfileOwner(int uid) {
5182 final DevicePolicyManagerInternal dpmi =
5183 LocalServices.getService(DevicePolicyManagerInternal.class);
5184 return (dpmi != null)
5185 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5186 }
5187
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005188 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005189 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5190 throws RemoteException {
5191 final int callingUid = getCallingUid();
5192
Amith Yamasani27db4682013-03-30 17:07:47 -07005193 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005194 throw new SecurityException();
5195 }
5196
5197 if (value) {
5198 grantAppPermission(account, authTokenType, uid);
5199 } else {
5200 revokeAppPermission(account, authTokenType, uid);
5201 }
5202 }
5203
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005204 /**
5205 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5206 * <p>
5207 * Although this is public it can only be accessed via the AccountManagerService object
5208 * which is in the system. This means we don't need to protect it with permissions.
5209 * @hide
5210 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005211 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005212 if (account == null || authTokenType == null) {
5213 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005214 return;
5215 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005216 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005217 synchronized (accounts.cacheLock) {
5218 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005219 db.beginTransaction();
5220 try {
5221 long accountId = getAccountIdLocked(db, account);
5222 if (accountId >= 0) {
5223 ContentValues values = new ContentValues();
5224 values.put(GRANTS_ACCOUNTS_ID, accountId);
5225 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
5226 values.put(GRANTS_GRANTEE_UID, uid);
5227 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
5228 db.setTransactionSuccessful();
5229 }
5230 } finally {
5231 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005232 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005233 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005234 UserHandle.of(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005235 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005236 }
5237
5238 /**
5239 * Don't allow callers with the given uid permission to get credentials for
5240 * account/authTokenType.
5241 * <p>
5242 * Although this is public it can only be accessed via the AccountManagerService object
5243 * which is in the system. This means we don't need to protect it with permissions.
5244 * @hide
5245 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005246 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005247 if (account == null || authTokenType == null) {
5248 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005249 return;
5250 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005251 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005252 synchronized (accounts.cacheLock) {
5253 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005254 db.beginTransaction();
5255 try {
5256 long accountId = getAccountIdLocked(db, account);
5257 if (accountId >= 0) {
5258 db.delete(TABLE_GRANTS,
5259 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
5260 + GRANTS_GRANTEE_UID + "=?",
5261 new String[]{String.valueOf(accountId), authTokenType,
5262 String.valueOf(uid)});
5263 db.setTransactionSuccessful();
5264 }
5265 } finally {
5266 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005267 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005268 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5269 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005270 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005271 }
Fred Quintana56285a62010-12-02 14:20:51 -08005272
5273 static final private String stringArrayToString(String[] value) {
5274 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5275 }
5276
Amith Yamasani04e0d262012-02-14 11:50:53 -08005277 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5278 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005279 if (oldAccountsForType != null) {
5280 ArrayList<Account> newAccountsList = new ArrayList<Account>();
5281 for (Account curAccount : oldAccountsForType) {
5282 if (!curAccount.equals(account)) {
5283 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005284 }
5285 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005286 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005287 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005288 } else {
5289 Account[] newAccountsForType = new Account[newAccountsList.size()];
5290 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005291 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005292 }
Fred Quintana56285a62010-12-02 14:20:51 -08005293 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005294 accounts.userDataCache.remove(account);
5295 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005296 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005297 }
5298
5299 /**
5300 * This assumes that the caller has already checked that the account is not already present.
5301 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08005302 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5303 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005304 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5305 Account[] newAccountsForType = new Account[oldLength + 1];
5306 if (accountsForType != null) {
5307 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005308 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005309 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005310 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08005311 }
5312
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005313 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07005314 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005315 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07005316 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005317 return unfiltered;
5318 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005319 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005320 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005321 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005322 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005323 // otherwise return non-shared accounts only.
5324 // This might be a temporary way to specify a whitelist
5325 String whiteList = mContext.getResources().getString(
5326 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5327 for (String packageName : packages) {
5328 if (whiteList.contains(";" + packageName + ";")) {
5329 return unfiltered;
5330 }
5331 }
5332 ArrayList<Account> allowed = new ArrayList<Account>();
5333 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5334 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005335 String requiredAccountType = "";
5336 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005337 // If there's an explicit callingPackage specified, check if that package
5338 // opted in to see restricted accounts.
5339 if (callingPackage != null) {
5340 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005341 if (pi != null && pi.restrictedAccountType != null) {
5342 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005343 }
5344 } else {
5345 // Otherwise check if the callingUid has a package that has opted in
5346 for (String packageName : packages) {
5347 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5348 if (pi != null && pi.restrictedAccountType != null) {
5349 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005350 break;
5351 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005352 }
5353 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005354 } catch (NameNotFoundException nnfe) {
5355 }
5356 for (Account account : unfiltered) {
5357 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005358 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005359 } else {
5360 boolean found = false;
5361 for (Account shared : sharedAccounts) {
5362 if (shared.equals(account)) {
5363 found = true;
5364 break;
5365 }
5366 }
5367 if (!found) {
5368 allowed.add(account);
5369 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005370 }
5371 }
5372 Account[] filtered = new Account[allowed.size()];
5373 allowed.toArray(filtered);
5374 return filtered;
5375 } else {
5376 return unfiltered;
5377 }
5378 }
5379
Amith Yamasani27db4682013-03-30 17:07:47 -07005380 /*
5381 * packageName can be null. If not null, it should be used to filter out restricted accounts
5382 * that the package is not allowed to access.
5383 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005384 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07005385 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005386 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005387 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005388 if (accounts == null) {
5389 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005390 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005391 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07005392 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005393 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005394 } else {
5395 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005396 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005397 totalLength += accounts.length;
5398 }
5399 if (totalLength == 0) {
5400 return EMPTY_ACCOUNT_ARRAY;
5401 }
5402 Account[] accounts = new Account[totalLength];
5403 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005404 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005405 System.arraycopy(accountsOfType, 0, accounts, totalLength,
5406 accountsOfType.length);
5407 totalLength += accountsOfType.length;
5408 }
Amith Yamasani27db4682013-03-30 17:07:47 -07005409 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005410 }
5411 }
5412
Amith Yamasani04e0d262012-02-14 11:50:53 -08005413 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5414 Account account, String key, String value) {
5415 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005416 if (userDataForAccount == null) {
5417 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005418 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005419 }
5420 if (value == null) {
5421 userDataForAccount.remove(key);
5422 } else {
5423 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005424 }
5425 }
5426
Carlos Valdivia91979be2015-05-22 14:11:35 -07005427 protected String readCachedTokenInternal(
5428 UserAccounts accounts,
5429 Account account,
5430 String tokenType,
5431 String callingPackage,
5432 byte[] pkgSigDigest) {
5433 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005434 return accounts.accountTokenCaches.get(
5435 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005436 }
5437 }
5438
Amith Yamasani04e0d262012-02-14 11:50:53 -08005439 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5440 Account account, String key, String value) {
5441 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005442 if (authTokensForAccount == null) {
5443 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005444 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005445 }
5446 if (value == null) {
5447 authTokensForAccount.remove(key);
5448 } else {
5449 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005450 }
5451 }
5452
Amith Yamasani04e0d262012-02-14 11:50:53 -08005453 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5454 String authTokenType) {
5455 synchronized (accounts.cacheLock) {
5456 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005457 if (authTokensForAccount == null) {
5458 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005459 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005460 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005461 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005462 }
5463 return authTokensForAccount.get(authTokenType);
5464 }
5465 }
5466
Simranjit Kohli858511c2016-03-10 18:36:11 +00005467 protected String readUserDataInternalLocked(
5468 UserAccounts accounts, Account account, String key) {
5469 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
5470 if (userDataForAccount == null) {
5471 // need to populate the cache for this account
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005472 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Simranjit Kohli858511c2016-03-10 18:36:11 +00005473 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
5474 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005475 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005476 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005477 }
5478
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005479 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
5480 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005481 HashMap<String, String> userDataForAccount = new HashMap<>();
5482 Cursor cursor = db.query(CE_TABLE_EXTRAS,
Fred Quintana56285a62010-12-02 14:20:51 -08005483 COLUMNS_EXTRAS_KEY_AND_VALUE,
5484 SELECTION_USERDATA_BY_ACCOUNT,
5485 new String[]{account.name, account.type},
5486 null, null, null);
5487 try {
5488 while (cursor.moveToNext()) {
5489 final String tmpkey = cursor.getString(0);
5490 final String value = cursor.getString(1);
5491 userDataForAccount.put(tmpkey, value);
5492 }
5493 } finally {
5494 cursor.close();
5495 }
5496 return userDataForAccount;
5497 }
5498
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005499 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
5500 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005501 HashMap<String, String> authTokensForAccount = new HashMap<>();
5502 Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
Fred Quintana56285a62010-12-02 14:20:51 -08005503 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
5504 SELECTION_AUTHTOKENS_BY_ACCOUNT,
5505 new String[]{account.name, account.type},
5506 null, null, null);
5507 try {
5508 while (cursor.moveToNext()) {
5509 final String type = cursor.getString(0);
5510 final String authToken = cursor.getString(1);
5511 authTokensForAccount.put(type, authToken);
5512 }
5513 } finally {
5514 cursor.close();
5515 }
5516 return authTokensForAccount;
5517 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005518
5519 private Context getContextForUser(UserHandle user) {
5520 try {
5521 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5522 } catch (NameNotFoundException e) {
5523 // Default to mContext, not finding the package system is running as is unlikely.
5524 return mContext;
5525 }
5526 }
Sandra Kwan78812282015-11-04 11:19:47 -08005527
5528 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5529 try {
5530 response.onResult(result);
5531 } catch (RemoteException e) {
5532 // if the caller is dead then there is no one to care about remote
5533 // exceptions
5534 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5535 Log.v(TAG, "failure while notifying response", e);
5536 }
5537 }
5538 }
5539
5540 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5541 String errorMessage) {
5542 try {
5543 response.onError(errorCode, errorMessage);
5544 } catch (RemoteException e) {
5545 // if the caller is dead then there is no one to care about remote
5546 // exceptions
5547 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5548 Log.v(TAG, "failure while notifying response", e);
5549 }
5550 }
5551 }
Fred Quintana60307342009-03-24 22:48:12 -07005552}