blob: 8a0a62a033ed65750cab24db074bb3d1f2b659f8 [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;
Amith Yamasani67df64b2012-12-14 12:09:36 -080088import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080089import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070090import com.android.server.FgThread;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000091import com.android.server.LocalServices;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070092import com.google.android.collect.Lists;
93import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070094
Oscar Montemayora8529f62009-11-18 10:14:20 -080095import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070096import java.io.FileDescriptor;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070097import java.io.IOException;
Fred Quintanaa698f422009-04-08 19:14:54 -070098import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -080099import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700100import java.security.MessageDigest;
101import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700102import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700103import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800104import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700105import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700106import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700107import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700108import java.util.HashSet;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800109import java.util.Iterator;
Fred Quintana56285a62010-12-02 14:20:51 -0800110import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700111import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800112import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800113import java.util.Map.Entry;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700114import java.util.concurrent.atomic.AtomicInteger;
115import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700116
Fred Quintana60307342009-03-24 22:48:12 -0700117/**
118 * A system service that provides account, password, and authtoken management for all
119 * accounts on the device. Some of these calls are implemented with the help of the corresponding
120 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
121 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700122 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700123 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700124 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700125public class AccountManagerService
126 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800127 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Sandra Kwan78812282015-11-04 11:19:47 -0800128
Fred Quintana60307342009-03-24 22:48:12 -0700129 private static final String TAG = "AccountManagerService";
130
Fred Quintana60307342009-03-24 22:48:12 -0700131 private static final String DATABASE_NAME = "accounts.db";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700132 private static final int PRE_N_DATABASE_VERSION = 9;
133 private static final int CE_DATABASE_VERSION = 10;
134 private static final int DE_DATABASE_VERSION = 1;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700135
136 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700137
138 private final Context mContext;
139
Fred Quintana56285a62010-12-02 14:20:51 -0800140 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700141 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700142 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800143
Fred Quintana60307342009-03-24 22:48:12 -0700144 private final MessageHandler mMessageHandler;
145
146 // Messages that can be sent on mHandler
147 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700148 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700149
Fred Quintana56285a62010-12-02 14:20:51 -0800150 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700151
152 private static final String TABLE_ACCOUNTS = "accounts";
153 private static final String ACCOUNTS_ID = "_id";
154 private static final String ACCOUNTS_NAME = "name";
155 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700156 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700157 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700158 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800159 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
160 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700161
162 private static final String TABLE_AUTHTOKENS = "authtokens";
163 private static final String AUTHTOKENS_ID = "_id";
164 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
165 private static final String AUTHTOKENS_TYPE = "type";
166 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
167
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700168 private static final String TABLE_GRANTS = "grants";
169 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
170 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
171 private static final String GRANTS_GRANTEE_UID = "uid";
172
Fred Quintana60307342009-03-24 22:48:12 -0700173 private static final String TABLE_EXTRAS = "extras";
174 private static final String EXTRAS_ID = "_id";
175 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
176 private static final String EXTRAS_KEY = "key";
177 private static final String EXTRAS_VALUE = "value";
178
179 private static final String TABLE_META = "meta";
180 private static final String META_KEY = "key";
181 private static final String META_VALUE = "value";
182
Amith Yamasani67df64b2012-12-14 12:09:36 -0800183 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700184 private static final String SHARED_ACCOUNTS_ID = "_id";
185
186 private static final String PRE_N_DATABASE_NAME = "accounts.db";
187 private static final String CE_DATABASE_NAME = "accounts_ce.db";
188 private static final String DE_DATABASE_NAME = "accounts_de.db";
189 private static final String CE_DB_PREFIX = "ceDb.";
190 private static final String CE_TABLE_ACCOUNTS = CE_DB_PREFIX + TABLE_ACCOUNTS;
191 private static final String CE_TABLE_AUTHTOKENS = CE_DB_PREFIX + TABLE_AUTHTOKENS;
192 private static final String CE_TABLE_EXTRAS = CE_DB_PREFIX + TABLE_EXTRAS;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800193
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700194 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
195 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700196 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800197
Carlos Valdivia91979be2015-05-22 14:11:35 -0700198 static {
199 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
200 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
201 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700202
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700203 private static final String COUNT_OF_MATCHING_GRANTS = ""
204 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
205 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
206 + " AND " + GRANTS_GRANTEE_UID + "=?"
207 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
208 + " AND " + ACCOUNTS_NAME + "=?"
209 + " AND " + ACCOUNTS_TYPE + "=?";
210
Fred Quintana56285a62010-12-02 14:20:51 -0800211 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
212 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700213
Fred Quintana56285a62010-12-02 14:20:51 -0800214 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
215 AUTHTOKENS_AUTHTOKEN};
216
217 private static final String SELECTION_USERDATA_BY_ACCOUNT =
218 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
219 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
220
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800221 private static final String META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX =
222 "auth_uid_for_type:";
223 private static final String META_KEY_DELIMITER = ":";
224 private static final String SELECTION_META_BY_AUTHENTICATOR_TYPE = META_KEY + " LIKE ?";
225
Fred Quintanaa698f422009-04-08 19:14:54 -0700226 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700227 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
228
Amith Yamasani04e0d262012-02-14 11:50:53 -0800229 static class UserAccounts {
230 private final int userId;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700231 private final DeDatabaseHelper openHelper;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800232 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
233 credentialsPermissionNotificationIds =
234 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
235 private final HashMap<Account, Integer> signinRequiredNotificationIds =
236 new HashMap<Account, Integer>();
237 private final Object cacheLock = new Object();
238 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700239 private final HashMap<String, Account[]> accountCache =
240 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800241 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800242 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800243 new HashMap<Account, HashMap<String, String>>();
244 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800245 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800246 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700247
248 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700249 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700250
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700251 /**
252 * protected by the {@link #cacheLock}
253 *
254 * Caches the previous names associated with an account. Previous names
255 * should be cached because we expect that when an Account is renamed,
256 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
257 * want to know if the accounts they care about have been renamed.
258 *
259 * The previous names are wrapped in an {@link AtomicReference} so that
260 * we can distinguish between those accounts with no previous names and
261 * those whose previous names haven't been cached (yet).
262 */
263 private final HashMap<Account, AtomicReference<String>> previousNameCache =
264 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800265
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700266 private int debugDbInsertionPoint = -1;
267 private SQLiteStatement statementForLogging;
268
Amith Yamasani04e0d262012-02-14 11:50:53 -0800269 UserAccounts(Context context, int userId) {
270 this.userId = userId;
271 synchronized (cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700272 openHelper = DeDatabaseHelper.create(context, userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800273 }
274 }
275 }
276
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700277 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
278 private final SparseBooleanArray mUnlockedUsers = new SparseBooleanArray();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800279
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700280 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700281 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700282
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700283 /**
284 * This should only be called by system code. One should only call this after the service
285 * has started.
286 * @return a reference to the AccountManagerService instance
287 * @hide
288 */
289 public static AccountManagerService getSingleton() {
290 return sThis.get();
291 }
Fred Quintana60307342009-03-24 22:48:12 -0700292
Fred Quintana56285a62010-12-02 14:20:51 -0800293 public AccountManagerService(Context context) {
294 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700295 }
296
Fred Quintana56285a62010-12-02 14:20:51 -0800297 public AccountManagerService(Context context, PackageManager packageManager,
298 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700299 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800300 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700301 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700302
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700303 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700304
Fred Quintana56285a62010-12-02 14:20:51 -0800305 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800306 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700307
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700308 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800309
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800310 IntentFilter intentFilter = new IntentFilter();
311 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
312 intentFilter.addDataScheme("package");
313 mContext.registerReceiver(new BroadcastReceiver() {
314 @Override
315 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700316 // Don't delete accounts when updating a authenticator's
317 // package.
318 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700319 /* Purging data requires file io, don't block the main thread. This is probably
320 * less than ideal because we are introducing a race condition where old grants
321 * could be exercised until they are purged. But that race condition existed
322 * anyway with the broadcast receiver.
323 *
324 * Ideally, we would completely clear the cache, purge data from the database,
325 * and then rebuild the cache. All under the cache lock. But that change is too
326 * large at this point.
327 */
328 Runnable r = new Runnable() {
329 @Override
330 public void run() {
331 purgeOldGrantsAll();
332 }
333 };
334 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700335 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800336 }
337 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800338
Amith Yamasani13593602012-03-22 16:16:17 -0700339 IntentFilter userFilter = new IntentFilter();
340 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Fyodor Kupolov041232a2016-02-22 15:01:45 -0800341 userFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800342 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700343 @Override
344 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800345 String action = intent.getAction();
346 if (Intent.ACTION_USER_REMOVED.equals(action)) {
347 onUserRemoved(intent);
Fyodor Kupolov041232a2016-02-22 15:01:45 -0800348 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
349 onUserUnlocked(intent);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800350 }
Amith Yamasani13593602012-03-22 16:16:17 -0700351 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800352 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800353 }
354
Dianne Hackborn164371f2013-10-01 19:10:13 -0700355 @Override
356 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
357 throws RemoteException {
358 try {
359 return super.onTransact(code, data, reply, flags);
360 } catch (RuntimeException e) {
361 // The account manager only throws security exceptions, so let's
362 // log all others.
363 if (!(e instanceof SecurityException)) {
364 Slog.wtf(TAG, "Account Manager Crash", e);
365 }
366 throw e;
367 }
368 }
369
Kenny Root26ff6622012-07-30 12:58:03 -0700370 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700371 }
372
Amith Yamasani258848d2012-08-10 17:06:33 -0700373 private UserManager getUserManager() {
374 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700375 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700376 }
377 return mUserManager;
378 }
379
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700380 /**
381 * Validate internal set of accounts against installed authenticators for
382 * given user. Clears cached authenticators before validating.
383 */
384 public void validateAccounts(int userId) {
385 final UserAccounts accounts = getUserAccounts(userId);
386
387 // Invalidate user-specific cache to make sure we catch any
388 // removed authenticators.
389 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
390 }
391
392 /**
393 * Validate internal set of accounts against installed authenticators for
394 * given user. Clear cached authenticators before validating when requested.
395 */
396 private void validateAccountsInternal(
397 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700398 if (Log.isLoggable(TAG, Log.DEBUG)) {
399 Log.d(TAG, "validateAccountsInternal " + accounts.userId
400 + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
401 + " userLocked=" + mUnlockedUsers.get(accounts.userId));
402 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700403 if (invalidateAuthenticatorCache) {
404 mAuthenticatorCache.invalidateCache(accounts.userId);
405 }
406
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800407 final HashMap<String, Integer> knownAuth = new HashMap<>();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700408 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
409 mAuthenticatorCache.getAllServices(accounts.userId)) {
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800410 knownAuth.put(service.type.type, service.uid);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700411 }
412
Amith Yamasani04e0d262012-02-14 11:50:53 -0800413 synchronized (accounts.cacheLock) {
414 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800415 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800416
417 // Get a list of stored authenticator type and UID
418 Cursor metaCursor = db.query(
419 TABLE_META,
420 new String[] {META_KEY, META_VALUE},
421 SELECTION_META_BY_AUTHENTICATOR_TYPE,
422 new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
423 null /* groupBy */,
424 null /* having */,
425 META_KEY);
426 // Create a list of authenticator type whose previous uid no longer exists
427 HashSet<String> obsoleteAuthType = Sets.newHashSet();
428 try {
429 while (metaCursor.moveToNext()) {
430 String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
431 String uid = metaCursor.getString(1);
432 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uid)) {
433 // Should never happen.
434 Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
435 + ", uid empty: " + TextUtils.isEmpty(uid));
436 continue;
437 }
438 Integer knownUid = knownAuth.get(type);
439 if (knownUid != null && uid.equals(knownUid.toString())) {
440 // Remove it from the knownAuth list if it's unchanged.
441 knownAuth.remove(type);
442 } else {
443 // Only add it to the list if it no longer exists or uid different
444 obsoleteAuthType.add(type);
445 // And delete it from the TABLE_META
446 db.delete(
447 TABLE_META,
448 META_KEY + "=? AND " + META_VALUE + "=?",
449 new String[] {
450 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
451 uid}
452 );
453 }
454 }
455 } finally {
456 metaCursor.close();
457 }
458
459 // Add the newly registered authenticator to TABLE_META
460 Iterator<Entry<String, Integer>> iterator = knownAuth.entrySet().iterator();
461 while (iterator.hasNext()) {
462 Entry<String, Integer> entry = iterator.next();
463 ContentValues values = new ContentValues();
464 values.put(META_KEY,
465 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
466 values.put(META_VALUE, entry.getValue());
467 db.insert(TABLE_META, null, values);
468 }
469
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800470 Cursor cursor = db.query(TABLE_ACCOUNTS,
471 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800472 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800473 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800474 accounts.accountCache.clear();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700475 final HashMap<String, ArrayList<String>> accountNamesByType = new LinkedHashMap<>();
Fred Quintana56285a62010-12-02 14:20:51 -0800476 while (cursor.moveToNext()) {
477 final long accountId = cursor.getLong(0);
478 final String accountType = cursor.getString(1);
479 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700480
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800481 if (obsoleteAuthType.contains(accountType)) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700482 Slog.w(TAG, "deleting account " + accountName + " because type "
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800483 + accountType + "'s registered authenticator no longer exist.");
Fred Quintana56285a62010-12-02 14:20:51 -0800484 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
485 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700486
487 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
488 accountId, accounts);
489
Fred Quintana56285a62010-12-02 14:20:51 -0800490 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800491 accounts.userDataCache.remove(account);
492 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700493 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800494 } else {
495 ArrayList<String> accountNames = accountNamesByType.get(accountType);
496 if (accountNames == null) {
497 accountNames = new ArrayList<String>();
498 accountNamesByType.put(accountType, accountNames);
499 }
500 accountNames.add(accountName);
501 }
502 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700503 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800504 final String accountType = cur.getKey();
505 final ArrayList<String> accountNames = cur.getValue();
506 final Account[] accountsForType = new Account[accountNames.size()];
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700507 for (int i = 0; i < accountsForType.length; i++) {
508 accountsForType[i] = new Account(accountNames.get(i), accountType);
Fred Quintana56285a62010-12-02 14:20:51 -0800509 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800510 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800511 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800512 } finally {
513 cursor.close();
514 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800515 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800516 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800517 }
518 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700519 }
520
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800521 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
522 Context context,
523 int userId) {
524 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
525 HashMap<String, Integer> knownAuth = new HashMap<>();
526 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
527 .getAllServices(userId)) {
528 knownAuth.put(service.type.type, service.uid);
529 }
530 return knownAuth;
531 }
532
Amith Yamasani04e0d262012-02-14 11:50:53 -0800533 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700534 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800535 }
536
537 protected UserAccounts getUserAccounts(int userId) {
538 synchronized (mUsers) {
539 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700540 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800541 if (accounts == null) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700542 accounts = new UserAccounts(mContext, userId);
543 initializeDebugDbSizeAndCompileSqlStatementForLogging(
544 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800545 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700546 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700547 validateAccounts = true;
548 }
549 // open CE database if necessary
550 if (!accounts.openHelper.isCeDatabaseAttached() && mUnlockedUsers.get(userId)) {
551 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
552 synchronized (accounts.cacheLock) {
553 CeDatabaseHelper.create(mContext, userId);
554 accounts.openHelper.attachCeDatabase();
555 }
556 // TODO Synchronize accounts by removing CE account not available in DE
557 }
558 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700559 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800560 }
561 return accounts;
562 }
563 }
564
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700565 private void purgeOldGrantsAll() {
566 synchronized (mUsers) {
567 for (int i = 0; i < mUsers.size(); i++) {
568 purgeOldGrants(mUsers.valueAt(i));
569 }
570 }
571 }
572
573 private void purgeOldGrants(UserAccounts accounts) {
574 synchronized (accounts.cacheLock) {
575 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
576 final Cursor cursor = db.query(TABLE_GRANTS,
577 new String[]{GRANTS_GRANTEE_UID},
578 null, null, GRANTS_GRANTEE_UID, null, null);
579 try {
580 while (cursor.moveToNext()) {
581 final int uid = cursor.getInt(0);
582 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
583 if (packageExists) {
584 continue;
585 }
586 Log.d(TAG, "deleting grants for UID " + uid
587 + " because its package is no longer installed");
588 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
589 new String[]{Integer.toString(uid)});
590 }
591 } finally {
592 cursor.close();
593 }
594 }
595 }
596
Amith Yamasani13593602012-03-22 16:16:17 -0700597 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700598 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700599 if (userId < 1) return;
600
601 UserAccounts accounts;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700602 boolean userUnlocked;
Amith Yamasani13593602012-03-22 16:16:17 -0700603 synchronized (mUsers) {
604 accounts = mUsers.get(userId);
605 mUsers.remove(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700606 userUnlocked = mUnlockedUsers.get(userId);
607 mUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -0700608 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700609 if (accounts != null) {
610 synchronized (accounts.cacheLock) {
611 accounts.openHelper.close();
612 }
Amith Yamasani13593602012-03-22 16:16:17 -0700613 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700614 Log.i(TAG, "Removing database files for user " + userId);
615 File dbFile = new File(getDeDatabaseName(userId));
Amith Yamasani13593602012-03-22 16:16:17 -0700616
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700617 deleteDbFileWarnIfFailed(dbFile);
618 // Remove CE file if user is unlocked, or FBE is not enabled
619 boolean fbeEnabled = StorageManager.isFileEncryptedNativeOrEmulated();
620 if (!fbeEnabled || userUnlocked) {
621 File ceDb = new File(getCeDatabaseName(userId));
622 if (ceDb.exists()) {
623 deleteDbFileWarnIfFailed(ceDb);
624 }
625 }
626 }
627
628 private static void deleteDbFileWarnIfFailed(File dbFile) {
629 if (!SQLiteDatabase.deleteDatabase(dbFile)) {
630 Log.w(TAG, "Database at " + dbFile + " was not deleted successfully");
Amith Yamasani13593602012-03-22 16:16:17 -0700631 }
632 }
633
Fyodor Kupolov041232a2016-02-22 15:01:45 -0800634 private void onUserUnlocked(Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800635 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700636 if (Log.isLoggable(TAG, Log.VERBOSE)) {
637 Log.v(TAG, "onUserUnlocked " + userId);
638 }
639 synchronized (mUsers) {
640 mUnlockedUsers.put(userId, true);
641 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800642 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700643 syncSharedAccounts(userId);
644 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800645
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700646 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800647 // Check if there's a shared account that needs to be created as an account
648 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
649 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700650 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700651 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -0700652 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700653 : UserHandle.USER_SYSTEM;
654 if (parentUserId < 0) {
655 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
656 return;
657 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800658 for (Account sa : sharedAccounts) {
659 if (ArrayUtils.contains(accounts, sa)) continue;
660 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700661 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800662 }
663 }
664
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700665 @Override
666 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700667 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700668 }
669
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800670 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700671 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700672 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800673 if (Log.isLoggable(TAG, Log.VERBOSE)) {
674 Log.v(TAG, "getPassword: " + account
675 + ", caller's uid " + Binder.getCallingUid()
676 + ", pid " + Binder.getCallingPid());
677 }
Fred Quintana382601f2010-03-25 12:25:10 -0700678 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000679 int userId = UserHandle.getCallingUserId();
680 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700681 String msg = String.format(
682 "uid %s cannot get secrets for accounts of type: %s",
683 callingUid,
684 account.type);
685 throw new SecurityException(msg);
686 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700687 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700688 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700689 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800690 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700691 } finally {
692 restoreCallingIdentity(identityToken);
693 }
694 }
695
Amith Yamasani04e0d262012-02-14 11:50:53 -0800696 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700697 if (account == null) {
698 return null;
699 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700700 if (!isUserUnlocked(accounts.userId)) {
701 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
702 return null;
703 }
Fred Quintana31957f12009-10-21 13:43:10 -0700704
Amith Yamasani04e0d262012-02-14 11:50:53 -0800705 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700706 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
707 return CeDatabaseHelper.findAccountPasswordByNameAndType(db, account.name,
708 account.type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700709 }
710 }
711
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800712 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700713 public String getPreviousName(Account account) {
714 if (Log.isLoggable(TAG, Log.VERBOSE)) {
715 Log.v(TAG, "getPreviousName: " + account
716 + ", caller's uid " + Binder.getCallingUid()
717 + ", pid " + Binder.getCallingPid());
718 }
719 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700720 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700721 long identityToken = clearCallingIdentity();
722 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700723 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700724 return readPreviousNameInternal(accounts, account);
725 } finally {
726 restoreCallingIdentity(identityToken);
727 }
728 }
729
730 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
731 if (account == null) {
732 return null;
733 }
734 synchronized (accounts.cacheLock) {
735 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
736 if (previousNameRef == null) {
737 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
738 Cursor cursor = db.query(
739 TABLE_ACCOUNTS,
740 new String[]{ ACCOUNTS_PREVIOUS_NAME },
741 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
742 new String[] { account.name, account.type },
743 null,
744 null,
745 null);
746 try {
747 if (cursor.moveToNext()) {
748 String previousName = cursor.getString(0);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700749 previousNameRef = new AtomicReference<>(previousName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700750 accounts.previousNameCache.put(account, previousNameRef);
751 return previousName;
752 } else {
753 return null;
754 }
755 } finally {
756 cursor.close();
757 }
758 } else {
759 return previousNameRef.get();
760 }
761 }
762 }
763
764 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700765 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700766 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800767 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700768 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
769 account, key, callingUid, Binder.getCallingPid());
770 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800771 }
Fred Quintana382601f2010-03-25 12:25:10 -0700772 if (account == null) throw new IllegalArgumentException("account is null");
773 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000774 int userId = UserHandle.getCallingUserId();
775 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700776 String msg = String.format(
777 "uid %s cannot get user data for accounts of type: %s",
778 callingUid,
779 account.type);
780 throw new SecurityException(msg);
781 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700782 long identityToken = clearCallingIdentity();
783 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700784 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +0000785 synchronized (accounts.cacheLock) {
786 if (!accountExistsCacheLocked(accounts, account)) {
787 return null;
788 }
789 return readUserDataInternalLocked(accounts, account, key);
790 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700791 } finally {
792 restoreCallingIdentity(identityToken);
793 }
794 }
795
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800796 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100797 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700798 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800799 if (Log.isLoggable(TAG, Log.VERBOSE)) {
800 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100801 + "for user id " + userId
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700802 + "caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800803 + ", pid " + Binder.getCallingPid());
804 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100805 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700806 if (isCrossUser(callingUid, userId)) {
807 throw new SecurityException(
808 String.format(
809 "User %s tying to get authenticator types for %s" ,
810 UserHandle.getCallingUserId(),
811 userId));
812 }
813
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700814 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700815 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000816 return getAuthenticatorTypesInternal(userId);
817
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700818 } finally {
819 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700820 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700821 }
822
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000823 /**
824 * Should only be called inside of a clearCallingIdentity block.
825 */
826 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
827 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
828 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
829 AuthenticatorDescription[] types =
830 new AuthenticatorDescription[authenticatorCollection.size()];
831 int i = 0;
832 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
833 : authenticatorCollection) {
834 types[i] = authenticator.type;
835 i++;
836 }
837 return types;
838 }
839
840
841
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700842 private boolean isCrossUser(int callingUid, int userId) {
843 return (userId != UserHandle.getCallingUserId()
844 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100845 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700846 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
847 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100848 }
849
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700850 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700851 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600852 Bundle.setDefusable(extras, true);
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700853 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800854 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700855 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700856 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800857 + ", pid " + Binder.getCallingPid());
858 }
Fred Quintana382601f2010-03-25 12:25:10 -0700859 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000860 int userId = UserHandle.getCallingUserId();
861 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700862 String msg = String.format(
863 "uid %s cannot explicitly add accounts of type: %s",
864 callingUid,
865 account.type);
866 throw new SecurityException(msg);
867 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700868 /*
869 * Child users are not allowed to add accounts. Only the accounts that are
870 * shared by the parent profile can be added to child profile.
871 *
872 * TODO: Only allow accounts that were shared to be added by
873 * a limited user.
874 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700875
Fred Quintana60307342009-03-24 22:48:12 -0700876 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700877 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700878 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700879 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700880 return addAccountInternal(accounts, account, password, extras, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700881 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700882 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700883 }
884 }
885
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000886 @Override
887 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700888 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700889 int callingUid = Binder.getCallingUid();
890 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
891 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000892 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700893 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800894 final UserAccounts fromAccounts = getUserAccounts(userFrom);
895 final UserAccounts toAccounts = getUserAccounts(userTo);
896 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000897 if (response != null) {
898 Bundle result = new Bundle();
899 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
900 try {
901 response.onResult(result);
902 } catch (RemoteException e) {
903 Slog.w(TAG, "Failed to report error back to the client." + e);
904 }
905 }
906 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800907 }
908
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000909 Slog.d(TAG, "Copying account " + account.name
910 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800911 long identityToken = clearCallingIdentity();
912 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000913 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800914 false /* stripAuthTokenFromResult */, account.name,
915 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700916 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800917 protected String toDebugString(long now) {
918 return super.toDebugString(now) + ", getAccountCredentialsForClone"
919 + ", " + account.type;
920 }
921
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700922 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800923 public void run() throws RemoteException {
924 mAuthenticator.getAccountCredentialsForCloning(this, account);
925 }
926
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700927 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800928 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600929 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000930 if (result != null
931 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
932 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700933 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800934 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800935 super.onResult(result);
936 }
937 }
938 }.bind();
939 } finally {
940 restoreCallingIdentity(identityToken);
941 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800942 }
943
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800944 @Override
945 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700946 final int callingUid = Binder.getCallingUid();
947 if (Log.isLoggable(TAG, Log.VERBOSE)) {
948 String msg = String.format(
949 "accountAuthenticated( account: %s, callerUid: %s)",
950 account,
951 callingUid);
952 Log.v(TAG, msg);
953 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800954 if (account == null) {
955 throw new IllegalArgumentException("account is null");
956 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000957 int userId = UserHandle.getCallingUserId();
958 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700959 String msg = String.format(
960 "uid %s cannot notify authentication for accounts of type: %s",
961 callingUid,
962 account.type);
963 throw new SecurityException(msg);
964 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000965
Benjamin Franzb6c0ce42015-11-05 10:06:51 +0000966 if (!canUserModifyAccounts(userId, callingUid) ||
967 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800968 return false;
969 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000970
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700971 long identityToken = clearCallingIdentity();
972 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000973 UserAccounts accounts = getUserAccounts(userId);
974 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700975 } finally {
976 restoreCallingIdentity(identityToken);
977 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -0700978 }
979
980 private boolean updateLastAuthenticatedTime(Account account) {
981 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800982 synchronized (accounts.cacheLock) {
983 final ContentValues values = new ContentValues();
984 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
985 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
986 int i = db.update(
987 TABLE_ACCOUNTS,
988 values,
989 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
990 new String[] {
991 account.name, account.type
992 });
993 if (i > 0) {
994 return true;
995 }
996 }
997 return false;
998 }
999
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001000 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001001 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1002 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001003 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001004 long id = clearCallingIdentity();
1005 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001006 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001007 false /* stripAuthTokenFromResult */, account.name,
1008 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001009 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001010 protected String toDebugString(long now) {
1011 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1012 + ", " + account.type;
1013 }
1014
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001015 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001016 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001017 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001018 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001019 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -07001020 for (Account acc : getAccounts(parentUserId,
1021 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001022 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001023 mAuthenticator.addAccountFromCredentials(
1024 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001025 break;
1026 }
1027 }
1028 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001029 }
1030
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001031 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001032 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001033 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001034 // TODO: Anything to do if if succedded?
1035 // TODO: If it failed: Show error notification? Should we remove the shadow
1036 // account to avoid retries?
1037 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001038 }
1039
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001040 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001041 public void onError(int errorCode, String errorMessage) {
1042 super.onError(errorCode, errorMessage);
1043 // TODO: Show error notification to user
1044 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1045 }
1046
1047 }.bind();
1048 } finally {
1049 restoreCallingIdentity(id);
1050 }
1051 }
1052
Amith Yamasani04e0d262012-02-14 11:50:53 -08001053 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001054 Bundle extras, int callingUid) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001055 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001056 if (account == null) {
1057 return false;
1058 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001059 if (!isUserUnlocked(accounts.userId)) {
1060 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1061 + " is locked. callingUid=" + callingUid);
1062 return false;
1063 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001064 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001065 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001066 db.beginTransaction();
1067 try {
1068 long numMatches = DatabaseUtils.longForQuery(db,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001069 "select count(*) from " + CE_TABLE_ACCOUNTS
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001070 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1071 new String[]{account.name, account.type});
1072 if (numMatches > 0) {
1073 Log.w(TAG, "insertAccountIntoDatabase: " + account
1074 + ", skipping since the account already exists");
1075 return false;
1076 }
1077 ContentValues values = new ContentValues();
1078 values.put(ACCOUNTS_NAME, account.name);
1079 values.put(ACCOUNTS_TYPE, account.type);
1080 values.put(ACCOUNTS_PASSWORD, password);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001081 long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001082 if (accountId < 0) {
1083 Log.w(TAG, "insertAccountIntoDatabase: " + account
1084 + ", skipping the DB insert failed");
1085 return false;
1086 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001087 // Insert into DE table
1088 values = new ContentValues();
1089 values.put(ACCOUNTS_ID, accountId);
1090 values.put(ACCOUNTS_NAME, account.name);
1091 values.put(ACCOUNTS_TYPE, account.type);
1092 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1093 System.currentTimeMillis());
1094 if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1095 Log.w(TAG, "insertAccountIntoDatabase: " + account
1096 + ", skipping the DB insert failed");
1097 return false;
1098 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001099 if (extras != null) {
1100 for (String key : extras.keySet()) {
1101 final String value = extras.getString(key);
1102 if (insertExtraLocked(db, accountId, key, value) < 0) {
1103 Log.w(TAG, "insertAccountIntoDatabase: " + account
1104 + ", skipping since insertExtra failed for key " + key);
1105 return false;
1106 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001107 }
1108 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001109 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001110
1111 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1112 accounts, callingUid);
1113
Amith Yamasani04e0d262012-02-14 11:50:53 -08001114 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001115 } finally {
1116 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001117 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001118 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001119 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001120 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1121 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001122 }
1123 return true;
1124 }
1125
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001126 private boolean isUserUnlocked(int userId) {
1127 synchronized (mUsers) {
1128 return mUnlockedUsers.get(userId);
1129 }
1130 }
1131
Amith Yamasani5be347b2013-03-31 17:44:31 -07001132 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001133 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001134 * running, then clone the account too.
1135 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001136 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001137 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001138 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001139 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001140 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001141 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001142 addSharedAccountAsUser(account, user.id);
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001143 if (getUserManager().isUserUnlocked(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001144 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1145 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001146 }
1147 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001148 }
1149 }
1150
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001151 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -07001152 ContentValues values = new ContentValues();
1153 values.put(EXTRAS_KEY, key);
1154 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1155 values.put(EXTRAS_VALUE, value);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001156 return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
Fred Quintana60307342009-03-24 22:48:12 -07001157 }
1158
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001159 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001160 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001161 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001162 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001163 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1164 Log.v(TAG, "hasFeatures: " + account
1165 + ", response " + response
1166 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001167 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001168 + ", pid " + Binder.getCallingPid());
1169 }
Fred Quintana382601f2010-03-25 12:25:10 -07001170 if (response == null) throw new IllegalArgumentException("response is null");
1171 if (account == null) throw new IllegalArgumentException("account is null");
1172 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001173 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001174 checkReadAccountsPermitted(callingUid, account.type, userId,
1175 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001176
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001177 long identityToken = clearCallingIdentity();
1178 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001179 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001180 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001181 } finally {
1182 restoreCallingIdentity(identityToken);
1183 }
1184 }
1185
1186 private class TestFeaturesSession extends Session {
1187 private final String[] mFeatures;
1188 private final Account mAccount;
1189
Amith Yamasani04e0d262012-02-14 11:50:53 -08001190 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001191 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001192 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001193 true /* stripAuthTokenFromResult */, account.name,
1194 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001195 mFeatures = features;
1196 mAccount = account;
1197 }
1198
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001199 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001200 public void run() throws RemoteException {
1201 try {
1202 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1203 } catch (RemoteException e) {
1204 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1205 }
1206 }
1207
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001208 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001209 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001210 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001211 IAccountManagerResponse response = getResponseAndClose();
1212 if (response != null) {
1213 try {
1214 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001215 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001216 return;
1217 }
Fred Quintana56285a62010-12-02 14:20:51 -08001218 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1219 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1220 + response);
1221 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001222 final Bundle newResult = new Bundle();
1223 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1224 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1225 response.onResult(newResult);
1226 } catch (RemoteException e) {
1227 // if the caller is dead then there is no one to care about remote exceptions
1228 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1229 Log.v(TAG, "failure while notifying response", e);
1230 }
1231 }
1232 }
1233 }
1234
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001235 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001236 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001237 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001238 + ", " + mAccount
1239 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1240 }
1241 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001242
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001243 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001244 public void renameAccount(
1245 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001246 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001247 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1248 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001249 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001250 + ", pid " + Binder.getCallingPid());
1251 }
1252 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001253 int userId = UserHandle.getCallingUserId();
1254 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001255 String msg = String.format(
1256 "uid %s cannot rename accounts of type: %s",
1257 callingUid,
1258 accountToRename.type);
1259 throw new SecurityException(msg);
1260 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001261 long identityToken = clearCallingIdentity();
1262 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001263 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001264 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001265 Bundle result = new Bundle();
1266 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1267 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1268 try {
1269 response.onResult(result);
1270 } catch (RemoteException e) {
1271 Log.w(TAG, e.getMessage());
1272 }
1273 } finally {
1274 restoreCallingIdentity(identityToken);
1275 }
1276 }
1277
1278 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001279 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001280 Account resultAccount = null;
1281 /*
1282 * Cancel existing notifications. Let authenticators
1283 * re-post notifications as required. But we don't know if
1284 * the authenticators have bound their notifications to
1285 * now stale account name data.
1286 *
1287 * With a rename api, we might not need to do this anymore but it
1288 * shouldn't hurt.
1289 */
1290 cancelNotification(
1291 getSigninRequiredNotificationId(accounts, accountToRename),
1292 new UserHandle(accounts.userId));
1293 synchronized(accounts.credentialsPermissionNotificationIds) {
1294 for (Pair<Pair<Account, String>, Integer> pair:
1295 accounts.credentialsPermissionNotificationIds.keySet()) {
1296 if (accountToRename.equals(pair.first.first)) {
1297 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1298 cancelNotification(id, new UserHandle(accounts.userId));
1299 }
1300 }
1301 }
1302 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001303 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001304 db.beginTransaction();
1305 boolean isSuccessful = false;
1306 Account renamedAccount = new Account(newName, accountToRename.type);
1307 try {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001308 final long accountId = getAccountIdLocked(db, accountToRename);
1309 if (accountId >= 0) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001310 final ContentValues values = new ContentValues();
1311 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001312 final String[] argsAccountId = { String.valueOf(accountId) };
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001313 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1314 // Update NAME/PREVIOUS_NAME in DE accounts table
1315 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001316 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1317 db.setTransactionSuccessful();
1318 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001319 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1320 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001321 }
1322 } finally {
1323 db.endTransaction();
1324 if (isSuccessful) {
1325 /*
1326 * Database transaction was successful. Clean up cached
1327 * data associated with the account in the user profile.
1328 */
1329 insertAccountIntoCacheLocked(accounts, renamedAccount);
1330 /*
1331 * Extract the data and token caches before removing the
1332 * old account to preserve the user data associated with
1333 * the account.
1334 */
1335 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1336 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1337 removeAccountFromCacheLocked(accounts, accountToRename);
1338 /*
1339 * Update the cached data associated with the renamed
1340 * account.
1341 */
1342 accounts.userDataCache.put(renamedAccount, tmpData);
1343 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1344 accounts.previousNameCache.put(
1345 renamedAccount,
1346 new AtomicReference<String>(accountToRename.name));
1347 resultAccount = renamedAccount;
1348
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001349 int parentUserId = accounts.userId;
1350 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001351 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001352 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001353 * those users with which the account was shared.
1354 */
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001355 List<UserInfo> users = getUserManager().getUsers(true);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001356 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001357 if (user.isRestricted()
1358 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001359 renameSharedAccountAsUser(accountToRename, newName, user.id);
1360 }
1361 }
1362 }
1363 sendAccountsChangedBroadcast(accounts.userId);
1364 }
1365 }
1366 }
1367 return resultAccount;
1368 }
1369
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001370 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001371 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001372 return userInfo != null && userInfo.canHaveProfile();
1373 }
1374
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001375 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001376 public void removeAccount(IAccountManagerResponse response, Account account,
1377 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001378 removeAccountAsUser(
1379 response,
1380 account,
1381 expectActivityLaunch,
1382 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001383 }
1384
1385 @Override
1386 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001387 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001388 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001389 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1390 Log.v(TAG, "removeAccount: " + account
1391 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001392 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001393 + ", pid " + Binder.getCallingPid()
1394 + ", for user id " + userId);
1395 }
1396 if (response == null) throw new IllegalArgumentException("response is null");
1397 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001398 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001399 if (isCrossUser(callingUid, userId)) {
1400 throw new SecurityException(
1401 String.format(
1402 "User %s tying remove account for %s" ,
1403 UserHandle.getCallingUserId(),
1404 userId));
1405 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001406 /*
1407 * Only the system or authenticator should be allowed to remove accounts for that
1408 * authenticator. This will let users remove accounts (via Settings in the system) but not
1409 * arbitrary applications (like competing authenticators).
1410 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001411 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001412 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1413 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001414 String msg = String.format(
1415 "uid %s cannot remove accounts of type: %s",
1416 callingUid,
1417 account.type);
1418 throw new SecurityException(msg);
1419 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001420 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001421 try {
1422 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1423 "User cannot modify accounts");
1424 } catch (RemoteException re) {
1425 }
1426 return;
1427 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001428 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001429 try {
1430 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1431 "User cannot modify accounts of this type (policy).");
1432 } catch (RemoteException re) {
1433 }
1434 return;
1435 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001436 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001437 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001438 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001439 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001440 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001441 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001442 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001443 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001444 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001445 }
1446 }
1447 }
1448
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001449 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1450
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001451 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001452 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1453 } finally {
1454 restoreCallingIdentity(identityToken);
1455 }
1456 }
1457
1458 @Override
1459 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001460 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001461 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1462 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001463 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001464 + ", pid " + Binder.getCallingPid());
1465 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001466 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001467 if (account == null) {
1468 /*
1469 * Null accounts should result in returning false, as per
1470 * AccountManage.addAccountExplicitly(...) java doc.
1471 */
1472 Log.e(TAG, "account is null");
1473 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001474 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001475 String msg = String.format(
1476 "uid %s cannot explicitly add accounts of type: %s",
1477 callingUid,
1478 account.type);
1479 throw new SecurityException(msg);
1480 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001481 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001482 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001483 long identityToken = clearCallingIdentity();
1484 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001485 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001486 } finally {
1487 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001488 }
Fred Quintana60307342009-03-24 22:48:12 -07001489 }
1490
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001491 private class RemoveAccountSession extends Session {
1492 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001493 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001494 Account account, boolean expectActivityLaunch) {
1495 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001496 true /* stripAuthTokenFromResult */, account.name,
1497 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001498 mAccount = account;
1499 }
1500
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001501 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001502 protected String toDebugString(long now) {
1503 return super.toDebugString(now) + ", removeAccount"
1504 + ", account " + mAccount;
1505 }
1506
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001507 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001508 public void run() throws RemoteException {
1509 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1510 }
1511
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001512 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001513 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001514 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001515 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1516 && !result.containsKey(AccountManager.KEY_INTENT)) {
1517 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001518 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001519 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001520 }
1521 IAccountManagerResponse response = getResponseAndClose();
1522 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001523 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1524 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1525 + response);
1526 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001527 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001528 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001529 try {
1530 response.onResult(result2);
1531 } catch (RemoteException e) {
1532 // ignore
1533 }
1534 }
1535 }
1536 super.onResult(result);
1537 }
1538 }
1539
Amith Yamasani04e0d262012-02-14 11:50:53 -08001540 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001541 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001542 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001543 }
1544
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001545 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001546 // For now user is required to be unlocked. TODO: Handle both cases in the future
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001547 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001548 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001549 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001550 final long accountId = getAccountIdLocked(db, account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001551 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1552 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001553 new String[]{account.name, account.type});
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001554 // Delete from CE table
1555 db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1556 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001557 removeAccountFromCacheLocked(accounts, account);
1558 sendAccountsChangedBroadcast(accounts.userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001559
1560 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001561 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001562 long id = Binder.clearCallingIdentity();
1563 try {
1564 int parentUserId = accounts.userId;
1565 if (canHaveProfile(parentUserId)) {
1566 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001567 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001568 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001569 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001570 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001571 }
1572 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001573 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001574 } finally {
1575 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001576 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001577 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001578 }
1579
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001580 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001581 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001582 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001583 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1584 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001585 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001586 + ", pid " + Binder.getCallingPid());
1587 }
Fred Quintana382601f2010-03-25 12:25:10 -07001588 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1589 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001590 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001591 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001592 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001593 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001594 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001595 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001596 db.beginTransaction();
1597 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001598 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001599 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001600 db.setTransactionSuccessful();
1601 } finally {
1602 db.endTransaction();
1603 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001604 }
Fred Quintana60307342009-03-24 22:48:12 -07001605 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001606 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001607 }
1608 }
1609
Carlos Valdivia91979be2015-05-22 14:11:35 -07001610 private void invalidateCustomTokenLocked(
1611 UserAccounts accounts,
1612 String accountType,
1613 String authToken) {
1614 if (authToken == null || accountType == null) {
1615 return;
1616 }
1617 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001618 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001619 }
1620
Amith Yamasani04e0d262012-02-14 11:50:53 -08001621 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1622 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001623 if (authToken == null || accountType == null) {
1624 return;
1625 }
Fred Quintana33269202009-04-20 16:05:10 -07001626 Cursor cursor = db.rawQuery(
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001627 "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1628 + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1629 + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1630 + " FROM " + CE_TABLE_ACCOUNTS
1631 + " JOIN " + CE_TABLE_AUTHTOKENS
1632 + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1633 + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
1634 + " WHERE " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_AUTHTOKEN
1635 + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
Fred Quintana33269202009-04-20 16:05:10 -07001636 new String[]{authToken, accountType});
1637 try {
1638 while (cursor.moveToNext()) {
1639 long authTokenId = cursor.getLong(0);
1640 String accountName = cursor.getString(1);
1641 String authTokenType = cursor.getString(2);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001642 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001643 writeAuthTokenIntoCacheLocked(
1644 accounts,
1645 db,
1646 new Account(accountName, accountType),
1647 authTokenType,
1648 null);
Fred Quintana60307342009-03-24 22:48:12 -07001649 }
Fred Quintana33269202009-04-20 16:05:10 -07001650 } finally {
1651 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001652 }
1653 }
1654
Carlos Valdivia91979be2015-05-22 14:11:35 -07001655 private void saveCachedToken(
1656 UserAccounts accounts,
1657 Account account,
1658 String callerPkg,
1659 byte[] callerSigDigest,
1660 String tokenType,
1661 String token,
1662 long expiryMillis) {
1663
1664 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1665 return;
1666 }
1667 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001668 UserHandle.of(accounts.userId));
Carlos Valdivia91979be2015-05-22 14:11:35 -07001669 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001670 accounts.accountTokenCaches.put(
1671 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001672 }
1673 }
1674
Amith Yamasani04e0d262012-02-14 11:50:53 -08001675 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1676 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001677 if (account == null || type == null) {
1678 return false;
1679 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001680 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001681 UserHandle.of(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001682 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001683 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001684 db.beginTransaction();
1685 try {
1686 long accountId = getAccountIdLocked(db, account);
1687 if (accountId < 0) {
1688 return false;
1689 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001690 db.delete(CE_TABLE_AUTHTOKENS,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001691 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1692 new String[]{type});
1693 ContentValues values = new ContentValues();
1694 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1695 values.put(AUTHTOKENS_TYPE, type);
1696 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001697 if (db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001698 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001699 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001700 return true;
1701 }
Fred Quintana33269202009-04-20 16:05:10 -07001702 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001703 } finally {
1704 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001705 }
Fred Quintana60307342009-03-24 22:48:12 -07001706 }
1707 }
1708
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001709 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001710 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001711 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001712 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1713 Log.v(TAG, "peekAuthToken: " + account
1714 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001715 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001716 + ", pid " + Binder.getCallingPid());
1717 }
Fred Quintana382601f2010-03-25 12:25:10 -07001718 if (account == null) throw new IllegalArgumentException("account is null");
1719 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001720 int userId = UserHandle.getCallingUserId();
1721 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001722 String msg = String.format(
1723 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1724 callingUid,
1725 account.type);
1726 throw new SecurityException(msg);
1727 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001728 long identityToken = clearCallingIdentity();
1729 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001730 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001731 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001732 } finally {
1733 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001734 }
Fred Quintana60307342009-03-24 22:48:12 -07001735 }
1736
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001737 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001738 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001739 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001740 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1741 Log.v(TAG, "setAuthToken: " + account
1742 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001743 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001744 + ", pid " + Binder.getCallingPid());
1745 }
Fred Quintana382601f2010-03-25 12:25:10 -07001746 if (account == null) throw new IllegalArgumentException("account is null");
1747 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001748 int userId = UserHandle.getCallingUserId();
1749 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001750 String msg = String.format(
1751 "uid %s cannot set auth tokens associated with accounts of type: %s",
1752 callingUid,
1753 account.type);
1754 throw new SecurityException(msg);
1755 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001756 long identityToken = clearCallingIdentity();
1757 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001758 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001759 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001760 } finally {
1761 restoreCallingIdentity(identityToken);
1762 }
Fred Quintana60307342009-03-24 22:48:12 -07001763 }
1764
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001765 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001766 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001767 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001768 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1769 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001770 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001771 + ", pid " + Binder.getCallingPid());
1772 }
Fred Quintana382601f2010-03-25 12:25:10 -07001773 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001774 int userId = UserHandle.getCallingUserId();
1775 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001776 String msg = String.format(
1777 "uid %s cannot set secrets for accounts of type: %s",
1778 callingUid,
1779 account.type);
1780 throw new SecurityException(msg);
1781 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001782 long identityToken = clearCallingIdentity();
1783 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001784 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001785 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001786 } finally {
1787 restoreCallingIdentity(identityToken);
1788 }
Fred Quintana60307342009-03-24 22:48:12 -07001789 }
1790
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001791 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1792 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001793 if (account == null) {
1794 return;
1795 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001796 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001797 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001798 db.beginTransaction();
1799 try {
1800 final ContentValues values = new ContentValues();
1801 values.put(ACCOUNTS_PASSWORD, password);
1802 final long accountId = getAccountIdLocked(db, account);
1803 if (accountId >= 0) {
1804 final String[] argsAccountId = {String.valueOf(accountId)};
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001805 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1806 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001807 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001808 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001809 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001810
1811 String action = (password == null || password.length() == 0) ?
1812 DebugDbHelper.ACTION_CLEAR_PASSWORD
1813 : DebugDbHelper.ACTION_SET_PASSWORD;
1814 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001815 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001816 } finally {
1817 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001818 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001819 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001820 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001821 }
1822
Amith Yamasani04e0d262012-02-14 11:50:53 -08001823 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001824 Log.i(TAG, "the accounts changed, sending broadcast of "
1825 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001826 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001827 }
1828
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001829 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001830 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001831 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001832 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1833 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001834 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001835 + ", pid " + Binder.getCallingPid());
1836 }
Fred Quintana382601f2010-03-25 12:25:10 -07001837 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001838 int userId = UserHandle.getCallingUserId();
1839 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001840 String msg = String.format(
1841 "uid %s cannot clear passwords for accounts of type: %s",
1842 callingUid,
1843 account.type);
1844 throw new SecurityException(msg);
1845 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001846 long identityToken = clearCallingIdentity();
1847 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001848 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001849 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001850 } finally {
1851 restoreCallingIdentity(identityToken);
1852 }
Fred Quintana60307342009-03-24 22:48:12 -07001853 }
1854
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001855 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001856 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001857 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001858 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1859 Log.v(TAG, "setUserData: " + account
1860 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001861 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001862 + ", pid " + Binder.getCallingPid());
1863 }
Fred Quintana382601f2010-03-25 12:25:10 -07001864 if (key == null) throw new IllegalArgumentException("key is null");
1865 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001866 int userId = UserHandle.getCallingUserId();
1867 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001868 String msg = String.format(
1869 "uid %s cannot set user data for accounts of type: %s",
1870 callingUid,
1871 account.type);
1872 throw new SecurityException(msg);
1873 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001874 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001875 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001876 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00001877 synchronized (accounts.cacheLock) {
1878 if (!accountExistsCacheLocked(accounts, account)) {
1879 return;
1880 }
1881 setUserdataInternalLocked(accounts, account, key, value);
1882 }
Fred Quintana60307342009-03-24 22:48:12 -07001883 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001884 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001885 }
1886 }
1887
Simranjit Kohli858511c2016-03-10 18:36:11 +00001888 private boolean accountExistsCacheLocked(UserAccounts accounts, Account account) {
1889 if (accounts.accountCache.containsKey(account.type)) {
1890 for (Account acc : accounts.accountCache.get(account.type)) {
1891 if (acc.name.equals(account.name)) {
1892 return true;
1893 }
1894 }
1895 }
1896 return false;
1897 }
1898
1899 private void setUserdataInternalLocked(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001900 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001901 if (account == null || key == null) {
1902 return;
1903 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00001904 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1905 db.beginTransaction();
1906 try {
1907 long accountId = getAccountIdLocked(db, account);
1908 if (accountId < 0) {
1909 return;
1910 }
1911 long extrasId = getExtrasIdLocked(db, accountId, key);
1912 if (extrasId < 0) {
1913 extrasId = insertExtraLocked(db, accountId, key, value);
1914 if (extrasId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001915 return;
1916 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00001917 } else {
1918 ContentValues values = new ContentValues();
1919 values.put(EXTRAS_VALUE, value);
1920 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1921 return;
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001922 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001923 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00001924 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
1925 db.setTransactionSuccessful();
1926 } finally {
1927 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001928 }
1929 }
1930
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001931 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001932 if (result == null) {
1933 Log.e(TAG, "the result is unexpectedly null", new Exception());
1934 }
1935 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1936 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1937 + response);
1938 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001939 try {
1940 response.onResult(result);
1941 } catch (RemoteException e) {
1942 // if the caller is dead then there is no one to care about remote
1943 // exceptions
1944 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1945 Log.v(TAG, "failure while notifying response", e);
1946 }
1947 }
1948 }
1949
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001950 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001951 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1952 final String authTokenType)
1953 throws RemoteException {
1954 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001955 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1956
Fred Quintanad9640ec2012-05-23 12:37:00 -07001957 final int callingUid = getCallingUid();
1958 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001959 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001960 throw new SecurityException("can only call from system");
1961 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001962 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001963 long identityToken = clearCallingIdentity();
1964 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001965 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001966 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1967 false /* stripAuthTokenFromResult */, null /* accountName */,
1968 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001969 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001970 protected String toDebugString(long now) {
1971 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001972 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001973 + ", authTokenType " + authTokenType;
1974 }
1975
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001976 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001977 public void run() throws RemoteException {
1978 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1979 }
1980
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001981 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001982 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001983 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001984 if (result != null) {
1985 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1986 Bundle bundle = new Bundle();
1987 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1988 super.onResult(bundle);
1989 return;
1990 } else {
1991 super.onResult(result);
1992 }
1993 }
1994 }.bind();
1995 } finally {
1996 restoreCallingIdentity(identityToken);
1997 }
1998 }
1999
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002000 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002001 public void getAuthToken(
2002 IAccountManagerResponse response,
2003 final Account account,
2004 final String authTokenType,
2005 final boolean notifyOnAuthFailure,
2006 final boolean expectActivityLaunch,
2007 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002008 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002009 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2010 Log.v(TAG, "getAuthToken: " + account
2011 + ", response " + response
2012 + ", authTokenType " + authTokenType
2013 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2014 + ", expectActivityLaunch " + expectActivityLaunch
2015 + ", caller's uid " + Binder.getCallingUid()
2016 + ", pid " + Binder.getCallingPid());
2017 }
Fred Quintana382601f2010-03-25 12:25:10 -07002018 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002019 try {
2020 if (account == null) {
2021 Slog.w(TAG, "getAuthToken called with null account");
2022 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2023 return;
2024 }
2025 if (authTokenType == null) {
2026 Slog.w(TAG, "getAuthToken called with null authTokenType");
2027 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2028 return;
2029 }
2030 } catch (RemoteException e) {
2031 Slog.w(TAG, "Failed to report error back to the client." + e);
2032 return;
2033 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002034 int userId = UserHandle.getCallingUserId();
2035 long ident = Binder.clearCallingIdentity();
2036 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002037 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002038 try {
2039 accounts = getUserAccounts(userId);
2040 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2041 AuthenticatorDescription.newKey(account.type), accounts.userId);
2042 } finally {
2043 Binder.restoreCallingIdentity(ident);
2044 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002045
Costin Manolachea40c6302010-12-13 14:50:45 -08002046 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002047 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002048
2049 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002050 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002051 final boolean permissionGranted =
2052 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002053
Carlos Valdivia91979be2015-05-22 14:11:35 -07002054 // Get the calling package. We will use it for the purpose of caching.
2055 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002056 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002057 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002058 try {
2059 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2060 } finally {
2061 Binder.restoreCallingIdentity(ident);
2062 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002063 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2064 String msg = String.format(
2065 "Uid %s is attempting to illegally masquerade as package %s!",
2066 callerUid,
2067 callerPkg);
2068 throw new SecurityException(msg);
2069 }
2070
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002071 // let authenticator know the identity of the caller
2072 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2073 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002074
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002075 if (notifyOnAuthFailure) {
2076 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002077 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002078
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002079 long identityToken = clearCallingIdentity();
2080 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002081 // Distill the caller's package signatures into a single digest.
2082 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2083
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002084 // if the caller has permission, do the peek. otherwise go the more expensive
2085 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002086 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002087 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002088 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002089 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002090 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2091 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2092 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002093 onResult(response, result);
2094 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002095 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002096 }
2097
Carlos Valdivia91979be2015-05-22 14:11:35 -07002098 if (customTokens) {
2099 /*
2100 * Look up tokens in the new cache only if the loginOptions don't have parameters
2101 * outside of those expected to be injected by the AccountManager, e.g.
2102 * ANDORID_PACKAGE_NAME.
2103 */
2104 String token = readCachedTokenInternal(
2105 accounts,
2106 account,
2107 authTokenType,
2108 callerPkg,
2109 callerPkgSigDigest);
2110 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002111 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2112 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2113 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002114 Bundle result = new Bundle();
2115 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2116 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2117 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2118 onResult(response, result);
2119 return;
2120 }
2121 }
2122
Amith Yamasani04e0d262012-02-14 11:50:53 -08002123 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002124 false /* stripAuthTokenFromResult */, account.name,
2125 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002126 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002127 protected String toDebugString(long now) {
2128 if (loginOptions != null) loginOptions.keySet();
2129 return super.toDebugString(now) + ", getAuthToken"
2130 + ", " + account
2131 + ", authTokenType " + authTokenType
2132 + ", loginOptions " + loginOptions
2133 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2134 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002135
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002136 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002137 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002138 // If the caller doesn't have permission then create and return the
2139 // "grant permission" intent instead of the "getAuthToken" intent.
2140 if (!permissionGranted) {
2141 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2142 } else {
2143 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2144 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002145 }
2146
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002147 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002148 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002149 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002150 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002151 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002152 Intent intent = newGrantCredentialsPermissionIntent(
2153 account,
2154 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002155 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002156 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002157 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002158 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002159 onResult(bundle);
2160 return;
2161 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002162 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002163 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002164 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2165 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002166 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002167 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002168 "the type and name should not be empty");
2169 return;
2170 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002171 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002172 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002173 saveAuthTokenToDatabase(
2174 mAccounts,
2175 resultAccount,
2176 authTokenType,
2177 authToken);
2178 }
2179 long expiryMillis = result.getLong(
2180 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2181 if (customTokens
2182 && expiryMillis > System.currentTimeMillis()) {
2183 saveCachedToken(
2184 mAccounts,
2185 account,
2186 callerPkg,
2187 callerPkgSigDigest,
2188 authTokenType,
2189 authToken,
2190 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002191 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002192 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002193
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002194 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002195 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002196 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002197 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002198 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002199 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002200 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002201 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002202 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002203 }.bind();
2204 } finally {
2205 restoreCallingIdentity(identityToken);
2206 }
Fred Quintana60307342009-03-24 22:48:12 -07002207 }
2208
Carlos Valdivia91979be2015-05-22 14:11:35 -07002209 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2210 MessageDigest digester;
2211 try {
2212 digester = MessageDigest.getInstance("SHA-256");
2213 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2214 callerPkg, PackageManager.GET_SIGNATURES);
2215 for (Signature sig : pkgInfo.signatures) {
2216 digester.update(sig.toByteArray());
2217 }
2218 } catch (NoSuchAlgorithmException x) {
2219 Log.wtf(TAG, "SHA-256 should be available", x);
2220 digester = null;
2221 } catch (NameNotFoundException e) {
2222 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2223 digester = null;
2224 }
2225 return (digester == null) ? null : digester.digest();
2226 }
2227
Dianne Hackborn41203752012-08-31 14:05:51 -07002228 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2229 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002230 int uid = intent.getIntExtra(
2231 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2232 String authTokenType = intent.getStringExtra(
2233 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002234 final String titleAndSubtitle =
2235 mContext.getString(R.string.permission_request_notification_with_subtitle,
2236 account.name);
2237 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002238 String title = titleAndSubtitle;
2239 String subtitle = "";
2240 if (index > 0) {
2241 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002242 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002243 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002244 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002245 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002246 Notification n = new Notification.Builder(contextForUser)
2247 .setSmallIcon(android.R.drawable.stat_sys_warning)
2248 .setWhen(0)
2249 .setColor(contextForUser.getColor(
2250 com.android.internal.R.color.system_notification_accent_color))
2251 .setContentTitle(title)
2252 .setContentText(subtitle)
2253 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2254 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2255 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002256 installNotification(getCredentialPermissionNotificationId(
2257 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002258 }
2259
Costin Manolache5f383ad92010-12-02 16:44:46 -08002260 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002261 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002262
2263 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002264 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002265 // Since it was set in Eclair+ we can't change it without breaking apps using
2266 // the intent from a non-Activity context.
2267 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002268 intent.addCategory(
2269 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002270
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002271 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002272 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2273 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002274 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002275
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002276 return intent;
2277 }
2278
2279 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2280 int uid) {
2281 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002282 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002283 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002284 final Pair<Pair<Account, String>, Integer> key =
2285 new Pair<Pair<Account, String>, Integer>(
2286 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002287 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002288 if (id == null) {
2289 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002290 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002291 }
2292 }
2293 return id;
2294 }
2295
Amith Yamasani04e0d262012-02-14 11:50:53 -08002296 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002297 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002298 synchronized (accounts.signinRequiredNotificationIds) {
2299 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002300 if (id == null) {
2301 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002302 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002303 }
2304 }
2305 return id;
2306 }
2307
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002308 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002309 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002310 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002311 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002312 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002313 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2314 Log.v(TAG, "addAccount: accountType " + accountType
2315 + ", response " + response
2316 + ", authTokenType " + authTokenType
2317 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2318 + ", expectActivityLaunch " + expectActivityLaunch
2319 + ", caller's uid " + Binder.getCallingUid()
2320 + ", pid " + Binder.getCallingPid());
2321 }
Fred Quintana382601f2010-03-25 12:25:10 -07002322 if (response == null) throw new IllegalArgumentException("response is null");
2323 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002324
Amith Yamasani71e6c692013-03-24 17:39:28 -07002325 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002326 final int uid = Binder.getCallingUid();
2327 final int userId = UserHandle.getUserId(uid);
2328 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002329 try {
2330 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2331 "User is not allowed to add an account!");
2332 } catch (RemoteException re) {
2333 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002334 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002335 return;
2336 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002337 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002338 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002339 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2340 "User cannot modify accounts of this type (policy).");
2341 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002342 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002343 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2344 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002345 return;
2346 }
2347
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002348 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002349 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2350 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2351 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2352
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002353 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002354 long identityToken = clearCallingIdentity();
2355 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002356 UserAccounts accounts = getUserAccounts(usrId);
2357 logRecordWithUid(
2358 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002359 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002360 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002361 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002362 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002363 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002364 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002365 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002366 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002367
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002368 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002369 protected String toDebugString(long now) {
2370 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002371 + ", accountType " + accountType
2372 + ", requiredFeatures "
2373 + (requiredFeatures != null
2374 ? TextUtils.join(",", requiredFeatures)
2375 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002376 }
2377 }.bind();
2378 } finally {
2379 restoreCallingIdentity(identityToken);
2380 }
Fred Quintana60307342009-03-24 22:48:12 -07002381 }
2382
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002383 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002384 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2385 final String authTokenType, final String[] requiredFeatures,
2386 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002387 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002388 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002389 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2390 Log.v(TAG, "addAccount: accountType " + accountType
2391 + ", response " + response
2392 + ", authTokenType " + authTokenType
2393 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2394 + ", expectActivityLaunch " + expectActivityLaunch
2395 + ", caller's uid " + Binder.getCallingUid()
2396 + ", pid " + Binder.getCallingPid()
2397 + ", for user id " + userId);
2398 }
2399 if (response == null) throw new IllegalArgumentException("response is null");
2400 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002401 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002402 if (isCrossUser(callingUid, userId)) {
2403 throw new SecurityException(
2404 String.format(
2405 "User %s trying to add account for %s" ,
2406 UserHandle.getCallingUserId(),
2407 userId));
2408 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002409
2410 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002411 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002412 try {
2413 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2414 "User is not allowed to add an account!");
2415 } catch (RemoteException re) {
2416 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002417 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002418 return;
2419 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002420 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002421 try {
2422 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2423 "User cannot modify accounts of this type (policy).");
2424 } catch (RemoteException re) {
2425 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002426 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2427 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002428 return;
2429 }
2430
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002431 final int pid = Binder.getCallingPid();
2432 final int uid = Binder.getCallingUid();
2433 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2434 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2435 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2436
2437 long identityToken = clearCallingIdentity();
2438 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002439 UserAccounts accounts = getUserAccounts(userId);
2440 logRecordWithUid(
2441 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002442 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002443 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002444 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002445 @Override
2446 public void run() throws RemoteException {
2447 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2448 options);
2449 }
2450
2451 @Override
2452 protected String toDebugString(long now) {
2453 return super.toDebugString(now) + ", addAccount"
2454 + ", accountType " + accountType
2455 + ", requiredFeatures "
2456 + (requiredFeatures != null
2457 ? TextUtils.join(",", requiredFeatures)
2458 : null);
2459 }
2460 }.bind();
2461 } finally {
2462 restoreCallingIdentity(identityToken);
2463 }
2464 }
2465
Sandra Kwan78812282015-11-04 11:19:47 -08002466 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002467 public void startAddAccountSession(
2468 final IAccountManagerResponse response,
2469 final String accountType,
2470 final String authTokenType,
2471 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002472 final boolean expectActivityLaunch,
2473 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002474 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002475 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2476 Log.v(TAG,
2477 "startAddAccountSession: accountType " + accountType
2478 + ", response " + response
2479 + ", authTokenType " + authTokenType
2480 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2481 + ", expectActivityLaunch " + expectActivityLaunch
2482 + ", caller's uid " + Binder.getCallingUid()
2483 + ", pid " + Binder.getCallingPid());
2484 }
2485 if (response == null) {
2486 throw new IllegalArgumentException("response is null");
2487 }
2488 if (accountType == null) {
2489 throw new IllegalArgumentException("accountType is null");
2490 }
2491
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002492 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002493 // Only allow system to start session
2494 if (!isSystemUid(uid)) {
2495 String msg = String.format(
2496 "uid %s cannot stat add account session.",
2497 uid);
2498 throw new SecurityException(msg);
2499 }
2500
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002501 final int userId = UserHandle.getUserId(uid);
2502 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002503 try {
2504 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2505 "User is not allowed to add an account!");
2506 } catch (RemoteException re) {
2507 }
2508 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2509 return;
2510 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002511 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002512 try {
2513 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2514 "User cannot modify accounts of this type (policy).");
2515 } catch (RemoteException re) {
2516 }
2517 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2518 userId);
2519 return;
2520 }
Sandra Kwan78812282015-11-04 11:19:47 -08002521 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08002522 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2523 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2524 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2525
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002526 // Check to see if the Password should be included to the caller.
2527 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2528 boolean isPasswordForwardingAllowed = isPermitted(
2529 callerPkg, uid, Manifest.permission.GET_PASSWORD_PRIVILEGED);
2530
Sandra Kwan78812282015-11-04 11:19:47 -08002531 int usrId = UserHandle.getCallingUserId();
2532 long identityToken = clearCallingIdentity();
2533 try {
2534 UserAccounts accounts = getUserAccounts(usrId);
2535 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2536 TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002537 new StartAccountSession(
2538 accounts,
2539 response,
2540 accountType,
2541 expectActivityLaunch,
2542 null /* accountName */,
2543 false /* authDetailsRequired */,
2544 true /* updateLastAuthenticationTime */,
2545 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002546 @Override
2547 public void run() throws RemoteException {
2548 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2549 requiredFeatures, options);
2550 }
2551
2552 @Override
2553 protected String toDebugString(long now) {
2554 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2555 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2556 + accountType + ", requiredFeatures "
2557 + (requiredFeatures != null ? requiredFeaturesStr : null);
2558 }
2559 }.bind();
2560 } finally {
2561 restoreCallingIdentity(identityToken);
2562 }
2563 }
2564
2565 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2566 private abstract class StartAccountSession extends Session {
2567
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002568 private final boolean mIsPasswordForwardingAllowed;
2569
2570 public StartAccountSession(
2571 UserAccounts accounts,
2572 IAccountManagerResponse response,
2573 String accountType,
2574 boolean expectActivityLaunch,
2575 String accountName,
2576 boolean authDetailsRequired,
2577 boolean updateLastAuthenticationTime,
2578 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08002579 super(accounts, response, accountType, expectActivityLaunch,
2580 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2581 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002582 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08002583 }
2584
2585 @Override
2586 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002587 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002588 mNumResults++;
2589 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08002590 if (result != null
2591 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08002592 checkKeyIntent(
2593 Binder.getCallingUid(),
2594 intent);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002595 // Omit passwords if the caller isn't permitted to see them.
2596 if (!mIsPasswordForwardingAllowed) {
2597 result.remove(AccountManager.KEY_PASSWORD);
2598 }
Sandra Kwan78812282015-11-04 11:19:47 -08002599 }
Sandra Kwan78812282015-11-04 11:19:47 -08002600 IAccountManagerResponse response;
2601 if (mExpectActivityLaunch && result != null
2602 && result.containsKey(AccountManager.KEY_INTENT)) {
2603 response = mResponse;
2604 } else {
2605 response = getResponseAndClose();
2606 }
2607 if (response == null) {
2608 return;
2609 }
2610 if (result == null) {
2611 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2612 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2613 + response);
2614 }
2615 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2616 "null bundle returned");
2617 return;
2618 }
2619
2620 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2621 // All AccountManager error codes are greater
2622 // than 0
2623 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2624 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2625 return;
2626 }
2627
2628 // Strip auth token from result.
2629 result.remove(AccountManager.KEY_AUTHTOKEN);
2630
2631 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2632 Log.v(TAG,
2633 getClass().getSimpleName() + " calling onResult() on response " + response);
2634 }
2635
2636 // Get the session bundle created by authenticator. The
2637 // bundle contains data necessary for finishing the session
2638 // later. The session bundle will be encrypted here and
2639 // decrypted later when trying to finish the session.
2640 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2641 if (sessionBundle != null) {
2642 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2643 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08002644 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002645 Log.w(TAG, "Account type in session bundle doesn't match request.");
2646 }
2647 // Add accountType info to session bundle. This will
2648 // override any value set by authenticator.
2649 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2650
2651 // Encrypt session bundle before returning to caller.
2652 try {
2653 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2654 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2655 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2656 } catch (GeneralSecurityException e) {
2657 if (Log.isLoggable(TAG, Log.DEBUG)) {
2658 Log.v(TAG, "Failed to encrypt session bundle!", e);
2659 }
2660 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2661 "failed to encrypt session bundle");
2662 return;
2663 }
2664 }
2665
2666 sendResponse(response, result);
2667 }
2668 }
2669
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002670 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08002671 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002672 @NonNull Bundle sessionBundle,
2673 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002674 Bundle appInfo,
2675 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002676 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08002677 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002678 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2679 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002680 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002681 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08002682 + ", caller's uid " + callingUid
2683 + ", caller's user id " + UserHandle.getCallingUserId()
2684 + ", pid " + Binder.getCallingPid()
2685 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002686 }
2687 if (response == null) {
2688 throw new IllegalArgumentException("response is null");
2689 }
2690
2691 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2692 // Account type is added to it before encryption.
2693 if (sessionBundle == null || sessionBundle.size() == 0) {
2694 throw new IllegalArgumentException("sessionBundle is empty");
2695 }
2696
Sandra Kwan0b84b452016-01-20 15:25:42 -08002697 // Only allow the system process to finish session for other users
2698 if (isCrossUser(callingUid, userId)) {
2699 throw new SecurityException(
2700 String.format(
2701 "User %s trying to finish session for %s without cross user permission",
2702 UserHandle.getCallingUserId(),
2703 userId));
2704 }
2705
Sandra Kwana578d112015-12-16 16:01:43 -08002706 // Only allow system to finish session
Sandra Kwan0b84b452016-01-20 15:25:42 -08002707 if (!isSystemUid(callingUid)) {
Sandra Kwana578d112015-12-16 16:01:43 -08002708 String msg = String.format(
Sandra Kwan0b84b452016-01-20 15:25:42 -08002709 "uid %s cannot finish session because it's not system uid.",
2710 callingUid);
Sandra Kwana578d112015-12-16 16:01:43 -08002711 throw new SecurityException(msg);
2712 }
2713
Sandra Kwan0b84b452016-01-20 15:25:42 -08002714 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002715 sendErrorResponse(response,
2716 AccountManager.ERROR_CODE_USER_RESTRICTED,
2717 "User is not allowed to add an account!");
2718 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2719 return;
2720 }
2721
2722 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002723 final Bundle decryptedBundle;
2724 final String accountType;
2725 // First decrypt session bundle to get account type for checking permission.
2726 try {
2727 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2728 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2729 if (decryptedBundle == null) {
2730 sendErrorResponse(
2731 response,
2732 AccountManager.ERROR_CODE_BAD_REQUEST,
2733 "failed to decrypt session bundle");
2734 return;
2735 }
2736 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2737 // Account type cannot be null. This should not happen if session bundle was created
2738 // properly by #StartAccountSession.
2739 if (TextUtils.isEmpty(accountType)) {
2740 sendErrorResponse(
2741 response,
2742 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2743 "accountType is empty");
2744 return;
2745 }
2746
2747 // If by any chances, decryptedBundle contains colliding keys with
2748 // system info
2749 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2750 // update credentials flow, we should replace with the new values of the current call.
2751 if (appInfo != null) {
2752 decryptedBundle.putAll(appInfo);
2753 }
2754
2755 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08002756 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002757 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2758 } catch (GeneralSecurityException e) {
2759 if (Log.isLoggable(TAG, Log.DEBUG)) {
2760 Log.v(TAG, "Failed to decrypt session bundle!", e);
2761 }
2762 sendErrorResponse(
2763 response,
2764 AccountManager.ERROR_CODE_BAD_REQUEST,
2765 "failed to decrypt session bundle");
2766 return;
2767 }
2768
Sandra Kwan0b84b452016-01-20 15:25:42 -08002769 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002770 sendErrorResponse(
2771 response,
2772 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2773 "User cannot modify accounts of this type (policy).");
2774 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2775 userId);
2776 return;
2777 }
2778
2779 long identityToken = clearCallingIdentity();
2780 try {
2781 UserAccounts accounts = getUserAccounts(userId);
2782 logRecordWithUid(
2783 accounts,
2784 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2785 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002786 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002787 new Session(
2788 accounts,
2789 response,
2790 accountType,
2791 expectActivityLaunch,
2792 true /* stripAuthTokenFromResult */,
2793 null /* accountName */,
2794 false /* authDetailsRequired */,
2795 true /* updateLastAuthenticationTime */) {
2796 @Override
2797 public void run() throws RemoteException {
2798 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2799 }
2800
2801 @Override
2802 protected String toDebugString(long now) {
2803 return super.toDebugString(now)
2804 + ", finishSession"
2805 + ", accountType " + accountType;
2806 }
2807 }.bind();
2808 } finally {
2809 restoreCallingIdentity(identityToken);
2810 }
2811 }
2812
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002813 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002814 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2815 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2816 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2817 long identityToken = clearCallingIdentity();
2818 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002819 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002820 } finally {
2821 restoreCallingIdentity(identityToken);
2822 }
2823 }
2824
2825 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002826 public void confirmCredentialsAsUser(
2827 IAccountManagerResponse response,
2828 final Account account,
2829 final Bundle options,
2830 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002831 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002832 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002833 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002834 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2835 Log.v(TAG, "confirmCredentials: " + account
2836 + ", response " + response
2837 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002838 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002839 + ", pid " + Binder.getCallingPid());
2840 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002841 // Only allow the system process to read accounts of other users
2842 if (isCrossUser(callingUid, userId)) {
2843 throw new SecurityException(
2844 String.format(
2845 "User %s trying to confirm account credentials for %s" ,
2846 UserHandle.getCallingUserId(),
2847 userId));
2848 }
Fred Quintana382601f2010-03-25 12:25:10 -07002849 if (response == null) throw new IllegalArgumentException("response is null");
2850 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002851 long identityToken = clearCallingIdentity();
2852 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002853 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002854 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002855 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002856 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002857 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002858 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002859 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002860 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002861 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002862 protected String toDebugString(long now) {
2863 return super.toDebugString(now) + ", confirmCredentials"
2864 + ", " + account;
2865 }
2866 }.bind();
2867 } finally {
2868 restoreCallingIdentity(identityToken);
2869 }
Fred Quintana60307342009-03-24 22:48:12 -07002870 }
2871
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002872 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002873 public void updateCredentials(IAccountManagerResponse response, final Account account,
2874 final String authTokenType, final boolean expectActivityLaunch,
2875 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002876 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002877 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2878 Log.v(TAG, "updateCredentials: " + account
2879 + ", response " + response
2880 + ", authTokenType " + authTokenType
2881 + ", expectActivityLaunch " + expectActivityLaunch
2882 + ", caller's uid " + Binder.getCallingUid()
2883 + ", pid " + Binder.getCallingPid());
2884 }
Fred Quintana382601f2010-03-25 12:25:10 -07002885 if (response == null) throw new IllegalArgumentException("response is null");
2886 if (account == null) throw new IllegalArgumentException("account is null");
2887 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002888 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002889 long identityToken = clearCallingIdentity();
2890 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002891 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002892 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002893 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002894 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002895 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002896 public void run() throws RemoteException {
2897 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2898 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002899 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002900 protected String toDebugString(long now) {
2901 if (loginOptions != null) loginOptions.keySet();
2902 return super.toDebugString(now) + ", updateCredentials"
2903 + ", " + account
2904 + ", authTokenType " + authTokenType
2905 + ", loginOptions " + loginOptions;
2906 }
2907 }.bind();
2908 } finally {
2909 restoreCallingIdentity(identityToken);
2910 }
Fred Quintana60307342009-03-24 22:48:12 -07002911 }
2912
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002913 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002914 public void startUpdateCredentialsSession(
2915 IAccountManagerResponse response,
2916 final Account account,
2917 final String authTokenType,
2918 final boolean expectActivityLaunch,
2919 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002920 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08002921 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2922 Log.v(TAG,
2923 "startUpdateCredentialsSession: " + account + ", response " + response
2924 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
2925 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
2926 + ", pid " + Binder.getCallingPid());
2927 }
2928 if (response == null) {
2929 throw new IllegalArgumentException("response is null");
2930 }
2931 if (account == null) {
2932 throw new IllegalArgumentException("account is null");
2933 }
Sandra Kwana578d112015-12-16 16:01:43 -08002934
2935 final int uid = Binder.getCallingUid();
2936 // Only allow system to start session
2937 if (!isSystemUid(uid)) {
2938 String msg = String.format(
2939 "uid %s cannot start update credentials session.",
2940 uid);
2941 throw new SecurityException(msg);
2942 }
2943
Sandra Kwane68c37e2015-11-12 17:11:49 -08002944 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002945
2946 // Check to see if the Password should be included to the caller.
2947 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
2948 boolean isPasswordForwardingAllowed = isPermitted(
2949 callerPkg, uid, Manifest.permission.GET_PASSWORD_PRIVILEGED);
2950
Sandra Kwane68c37e2015-11-12 17:11:49 -08002951 long identityToken = clearCallingIdentity();
2952 try {
2953 UserAccounts accounts = getUserAccounts(userId);
2954 new StartAccountSession(
2955 accounts,
2956 response,
2957 account.type,
2958 expectActivityLaunch,
2959 account.name,
2960 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07002961 true /* updateLastCredentialTime */,
2962 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08002963 @Override
2964 public void run() throws RemoteException {
2965 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
2966 loginOptions);
2967 }
2968
2969 @Override
2970 protected String toDebugString(long now) {
2971 if (loginOptions != null)
2972 loginOptions.keySet();
2973 return super.toDebugString(now)
2974 + ", startUpdateCredentialsSession"
2975 + ", " + account
2976 + ", authTokenType " + authTokenType
2977 + ", loginOptions " + loginOptions;
2978 }
2979 }.bind();
2980 } finally {
2981 restoreCallingIdentity(identityToken);
2982 }
2983 }
2984
2985 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08002986 public void isCredentialsUpdateSuggested(
2987 IAccountManagerResponse response,
2988 final Account account,
2989 final String statusToken) {
2990 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2991 Log.v(TAG,
2992 "isCredentialsUpdateSuggested: " + account + ", response " + response
2993 + ", caller's uid " + Binder.getCallingUid()
2994 + ", pid " + Binder.getCallingPid());
2995 }
2996 if (response == null) {
2997 throw new IllegalArgumentException("response is null");
2998 }
2999 if (account == null) {
3000 throw new IllegalArgumentException("account is null");
3001 }
3002 if (TextUtils.isEmpty(statusToken)) {
3003 throw new IllegalArgumentException("status token is empty");
3004 }
3005
3006 int uid = Binder.getCallingUid();
3007 // Only allow system to start session
3008 if (!isSystemUid(uid)) {
3009 String msg = String.format(
3010 "uid %s cannot stat add account session.",
3011 uid);
3012 throw new SecurityException(msg);
3013 }
3014
3015 int usrId = UserHandle.getCallingUserId();
3016 long identityToken = clearCallingIdentity();
3017 try {
3018 UserAccounts accounts = getUserAccounts(usrId);
3019 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3020 false /* stripAuthTokenFromResult */, account.name,
3021 false /* authDetailsRequired */) {
3022 @Override
3023 protected String toDebugString(long now) {
3024 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3025 + ", " + account;
3026 }
3027
3028 @Override
3029 public void run() throws RemoteException {
3030 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3031 }
3032
3033 @Override
3034 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003035 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003036 IAccountManagerResponse response = getResponseAndClose();
3037 if (response == null) {
3038 return;
3039 }
3040
3041 if (result == null) {
3042 sendErrorResponse(
3043 response,
3044 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3045 "null bundle");
3046 return;
3047 }
3048
3049 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3050 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3051 + response);
3052 }
3053 // Check to see if an error occurred. We know if an error occurred because all
3054 // error codes are greater than 0.
3055 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3056 sendErrorResponse(response,
3057 result.getInt(AccountManager.KEY_ERROR_CODE),
3058 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3059 return;
3060 }
3061 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3062 sendErrorResponse(
3063 response,
3064 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3065 "no result in response");
3066 return;
3067 }
3068 final Bundle newResult = new Bundle();
3069 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3070 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3071 sendResponse(response, newResult);
3072 }
3073 }.bind();
3074 } finally {
3075 restoreCallingIdentity(identityToken);
3076 }
3077 }
3078
3079 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003080 public void editProperties(IAccountManagerResponse response, final String accountType,
3081 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003082 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003083 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3084 Log.v(TAG, "editProperties: accountType " + accountType
3085 + ", response " + response
3086 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003087 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003088 + ", pid " + Binder.getCallingPid());
3089 }
Fred Quintana382601f2010-03-25 12:25:10 -07003090 if (response == null) throw new IllegalArgumentException("response is null");
3091 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003092 int userId = UserHandle.getCallingUserId();
3093 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003094 String msg = String.format(
3095 "uid %s cannot edit authenticator properites for account type: %s",
3096 callingUid,
3097 accountType);
3098 throw new SecurityException(msg);
3099 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003100 long identityToken = clearCallingIdentity();
3101 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003102 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003103 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003104 true /* stripAuthTokenFromResult */, null /* accountName */,
3105 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003106 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003107 public void run() throws RemoteException {
3108 mAuthenticator.editProperties(this, mAccountType);
3109 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003110 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003111 protected String toDebugString(long now) {
3112 return super.toDebugString(now) + ", editProperties"
3113 + ", accountType " + accountType;
3114 }
3115 }.bind();
3116 } finally {
3117 restoreCallingIdentity(identityToken);
3118 }
Fred Quintana60307342009-03-24 22:48:12 -07003119 }
3120
Amith Yamasani12747872015-12-07 14:19:49 -08003121 @Override
3122 public boolean someUserHasAccount(@NonNull final Account account) {
3123 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3124 throw new SecurityException("Only system can check for accounts across users");
3125 }
3126 final long token = Binder.clearCallingIdentity();
3127 try {
3128 AccountAndUser[] allAccounts = getAllAccounts();
3129 for (int i = allAccounts.length - 1; i >= 0; i--) {
3130 if (allAccounts[i].account.equals(account)) {
3131 return true;
3132 }
3133 }
3134 return false;
3135 } finally {
3136 Binder.restoreCallingIdentity(token);
3137 }
3138 }
3139
Fred Quintana33269202009-04-20 16:05:10 -07003140 private class GetAccountsByTypeAndFeatureSession extends Session {
3141 private final String[] mFeatures;
3142 private volatile Account[] mAccountsOfType = null;
3143 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3144 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003145 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003146
Amith Yamasani04e0d262012-02-14 11:50:53 -08003147 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003148 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003149 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003150 true /* stripAuthTokenFromResult */, null /* accountName */,
3151 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003152 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003153 mFeatures = features;
3154 }
3155
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003156 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003157 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003158 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003159 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3160 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003161 }
Fred Quintana33269202009-04-20 16:05:10 -07003162 // check whether each account matches the requested features
3163 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
3164 mCurrentAccount = 0;
3165
3166 checkAccount();
3167 }
3168
3169 public void checkAccount() {
3170 if (mCurrentAccount >= mAccountsOfType.length) {
3171 sendResult();
3172 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003173 }
Fred Quintana33269202009-04-20 16:05:10 -07003174
Fred Quintana29e94b82010-03-10 12:11:51 -08003175 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3176 if (accountAuthenticator == null) {
3177 // It is possible that the authenticator has died, which is indicated by
3178 // mAuthenticator being set to null. If this happens then just abort.
3179 // There is no need to send back a result or error in this case since
3180 // that already happened when mAuthenticator was cleared.
3181 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3182 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3183 + " connected to the authenticator, " + toDebugString());
3184 }
3185 return;
3186 }
Fred Quintana33269202009-04-20 16:05:10 -07003187 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003188 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003189 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003190 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003191 }
3192 }
3193
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003194 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003195 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003196 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003197 mNumResults++;
3198 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003199 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003200 return;
3201 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003202 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003203 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3204 }
3205 mCurrentAccount++;
3206 checkAccount();
3207 }
3208
3209 public void sendResult() {
3210 IAccountManagerResponse response = getResponseAndClose();
3211 if (response != null) {
3212 try {
3213 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3214 for (int i = 0; i < accounts.length; i++) {
3215 accounts[i] = mAccountsWithFeatures.get(i);
3216 }
Fred Quintana56285a62010-12-02 14:20:51 -08003217 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3218 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3219 + response);
3220 }
Fred Quintana33269202009-04-20 16:05:10 -07003221 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003222 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003223 response.onResult(result);
3224 } catch (RemoteException e) {
3225 // if the caller is dead then there is no one to care about remote exceptions
3226 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3227 Log.v(TAG, "failure while notifying response", e);
3228 }
3229 }
3230 }
3231 }
3232
3233
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003234 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003235 protected String toDebugString(long now) {
3236 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3237 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3238 }
3239 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003240
Amith Yamasani04e0d262012-02-14 11:50:53 -08003241 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003242 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003243 * @hide
3244 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003245 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003246 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003247 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003248 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3249 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003250 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003251 return new Account[0];
3252 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003253 long identityToken = clearCallingIdentity();
3254 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003255 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003256 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003257 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003258 callingUid,
3259 null, // packageName
3260 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003261 } finally {
3262 restoreCallingIdentity(identityToken);
3263 }
3264 }
3265
Amith Yamasanif29f2362012-04-05 18:29:52 -07003266 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003267 * Returns accounts for all running users.
3268 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003269 * @hide
3270 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003271 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003272 public AccountAndUser[] getRunningAccounts() {
3273 final int[] runningUserIds;
3274 try {
3275 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3276 } catch (RemoteException e) {
3277 // Running in system_server; should never happen
3278 throw new RuntimeException(e);
3279 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003280 return getAccounts(runningUserIds);
3281 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003282
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003283 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003284 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003285 public AccountAndUser[] getAllAccounts() {
3286 final List<UserInfo> users = getUserManager().getUsers();
3287 final int[] userIds = new int[users.size()];
3288 for (int i = 0; i < userIds.length; i++) {
3289 userIds[i] = users.get(i).id;
3290 }
3291 return getAccounts(userIds);
3292 }
3293
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003294 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003295 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003296 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003297 for (int userId : userIds) {
3298 UserAccounts userAccounts = getUserAccounts(userId);
3299 if (userAccounts == null) continue;
3300 synchronized (userAccounts.cacheLock) {
3301 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3302 Binder.getCallingUid(), null);
3303 for (int a = 0; a < accounts.length; a++) {
3304 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003305 }
3306 }
3307 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003308
3309 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3310 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003311 }
3312
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003313 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003314 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003315 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3316 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003317 }
3318
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003319 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003320 private Account[] getAccountsAsUser(
3321 String type,
3322 int userId,
3323 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003324 int packageUid,
3325 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003326 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003327 // Only allow the system process to read accounts of other users
3328 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003329 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003330 && mContext.checkCallingOrSelfPermission(
3331 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3332 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003333 throw new SecurityException("User " + UserHandle.getCallingUserId()
3334 + " trying to get account for " + userId);
3335 }
3336
Fred Quintana56285a62010-12-02 14:20:51 -08003337 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3338 Log.v(TAG, "getAccounts: accountType " + type
3339 + ", caller's uid " + Binder.getCallingUid()
3340 + ", pid " + Binder.getCallingPid());
3341 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003342 // If the original calling app was using the framework account chooser activity, we'll
3343 // be passed in the original caller's uid here, which is what should be used for filtering.
3344 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3345 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003346 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003347 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003348
Svetoslavf3f02ac2015-09-08 14:36:35 -07003349 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3350 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003351 if (visibleAccountTypes.isEmpty()
3352 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003353 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003354 } else if (visibleAccountTypes.contains(type)) {
3355 // Prune the list down to just the requested type.
3356 visibleAccountTypes = new ArrayList<>();
3357 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003358 } // else aggregate all the visible accounts (it won't matter if the
3359 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003360
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003361 long identityToken = clearCallingIdentity();
3362 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003363 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003364 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003365 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003366 callingUid,
3367 callingPackage,
3368 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003369 } finally {
3370 restoreCallingIdentity(identityToken);
3371 }
3372 }
3373
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003374 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003375 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003376 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003377 int callingUid,
3378 String callingPackage,
3379 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003380 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003381 ArrayList<Account> visibleAccounts = new ArrayList<>();
3382 for (String visibleType : visibleAccountTypes) {
3383 Account[] accountsForType = getAccountsFromCacheLocked(
3384 userAccounts, visibleType, callingUid, callingPackage);
3385 if (accountsForType != null) {
3386 visibleAccounts.addAll(Arrays.asList(accountsForType));
3387 }
3388 }
3389 Account[] result = new Account[visibleAccounts.size()];
3390 for (int i = 0; i < visibleAccounts.size(); i++) {
3391 result[i] = visibleAccounts.get(i);
3392 }
3393 return result;
3394 }
3395 }
3396
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003397 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003398 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
3399 checkManageUsersPermission("addSharedAccountsFromParentUser");
3400 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3401 for (Account account : accounts) {
3402 addSharedAccountAsUser(account, userId);
3403 }
3404 }
3405
3406 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003407 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003408 UserAccounts accounts = getUserAccounts(userId);
3409 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003410 ContentValues values = new ContentValues();
3411 values.put(ACCOUNTS_NAME, account.name);
3412 values.put(ACCOUNTS_TYPE, account.type);
3413 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3414 new String[] {account.name, account.type});
3415 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3416 if (accountId < 0) {
3417 Log.w(TAG, "insertAccountIntoDatabase: " + account
3418 + ", skipping the DB insert failed");
3419 return false;
3420 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003421 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003422 return true;
3423 }
3424
3425 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003426 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3427 userId = handleIncomingUser(userId);
3428 UserAccounts accounts = getUserAccounts(userId);
3429 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003430 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003431 final ContentValues values = new ContentValues();
3432 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003433 int r = db.update(
3434 TABLE_SHARED_ACCOUNTS,
3435 values,
3436 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3437 new String[] { account.name, account.type });
3438 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003439 int callingUid = getCallingUid();
3440 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3441 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003442 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003443 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003444 }
3445 return r > 0;
3446 }
3447
3448 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003449 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003450 return removeSharedAccountAsUser(account, userId, getCallingUid());
3451 }
3452
3453 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003454 userId = handleIncomingUser(userId);
3455 UserAccounts accounts = getUserAccounts(userId);
3456 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003457 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003458 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3459 new String[] {account.name, account.type});
3460 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003461 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3462 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003463 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003464 }
3465 return r > 0;
3466 }
3467
3468 @Override
3469 public Account[] getSharedAccountsAsUser(int userId) {
3470 userId = handleIncomingUser(userId);
3471 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003472 ArrayList<Account> accountList = new ArrayList<>();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003473 Cursor cursor = null;
3474 try {
3475 cursor = accounts.openHelper.getReadableDatabase()
3476 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3477 null, null, null, null, null);
3478 if (cursor != null && cursor.moveToFirst()) {
3479 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3480 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3481 do {
3482 accountList.add(new Account(cursor.getString(nameIndex),
3483 cursor.getString(typeIndex)));
3484 } while (cursor.moveToNext());
3485 }
3486 } finally {
3487 if (cursor != null) {
3488 cursor.close();
3489 }
3490 }
3491 Account[] accountArray = new Account[accountList.size()];
3492 accountList.toArray(accountArray);
3493 return accountArray;
3494 }
3495
3496 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003497 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003498 public Account[] getAccounts(String type, String opPackageName) {
3499 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003500 }
3501
Amith Yamasani27db4682013-03-30 17:07:47 -07003502 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003503 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003504 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003505 int callingUid = Binder.getCallingUid();
3506 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3507 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3508 + callingUid + " with uid=" + uid);
3509 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003510 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3511 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003512 }
3513
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003514 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003515 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003516 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3517 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003518 int packageUid = -1;
3519 try {
3520 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07003521 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3522 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003523 } catch (RemoteException re) {
3524 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3525 return new Account[0];
3526 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003527 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3528 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003529 }
3530
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003531 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003532 public void getAccountsByFeatures(
3533 IAccountManagerResponse response,
3534 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003535 String[] features,
3536 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003537 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003538 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3539 Log.v(TAG, "getAccounts: accountType " + type
3540 + ", response " + response
3541 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003542 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003543 + ", pid " + Binder.getCallingPid());
3544 }
Fred Quintana382601f2010-03-25 12:25:10 -07003545 if (response == null) throw new IllegalArgumentException("response is null");
3546 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003547 int userId = UserHandle.getCallingUserId();
3548
Svetoslavf3f02ac2015-09-08 14:36:35 -07003549 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3550 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003551 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003552 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003553 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003554 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3555 try {
3556 response.onResult(result);
3557 } catch (RemoteException e) {
3558 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3559 }
3560 return;
3561 }
Fred Quintana33269202009-04-20 16:05:10 -07003562 long identityToken = clearCallingIdentity();
3563 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003564 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003565 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003566 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003567 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003568 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003569 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08003570 Bundle result = new Bundle();
3571 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3572 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003573 return;
3574 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003575 new GetAccountsByTypeAndFeatureSession(
3576 userAccounts,
3577 response,
3578 type,
3579 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003580 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07003581 } finally {
3582 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07003583 }
3584 }
3585
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003586 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3587 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3588 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3589 try {
3590 if (cursor.moveToNext()) {
3591 return cursor.getLong(0);
3592 }
3593 return -1;
3594 } finally {
3595 cursor.close();
3596 }
3597 }
3598
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003599 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07003600 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003601 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07003602 try {
3603 if (cursor.moveToNext()) {
3604 return cursor.getLong(0);
3605 }
3606 return -1;
3607 } finally {
3608 cursor.close();
3609 }
3610 }
3611
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003612 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003613 Cursor cursor = db.query(CE_TABLE_EXTRAS, new String[]{EXTRAS_ID},
Fred Quintana60307342009-03-24 22:48:12 -07003614 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3615 new String[]{key}, null, null, null);
3616 try {
3617 if (cursor.moveToNext()) {
3618 return cursor.getLong(0);
3619 }
3620 return -1;
3621 } finally {
3622 cursor.close();
3623 }
3624 }
3625
Fred Quintanaa698f422009-04-08 19:14:54 -07003626 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07003627 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07003628 IAccountManagerResponse mResponse;
3629 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003630 final boolean mExpectActivityLaunch;
3631 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003632 final String mAccountName;
3633 // Indicates if we need to add auth details(like last credential time)
3634 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003635 // If set, we need to update the last authenticated time. This is
3636 // currently
3637 // used on
3638 // successful confirming credentials.
3639 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07003640
Fred Quintana33269202009-04-20 16:05:10 -07003641 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07003642 private int mNumRequestContinued = 0;
3643 private int mNumErrors = 0;
3644
Fred Quintana60307342009-03-24 22:48:12 -07003645 IAccountAuthenticator mAuthenticator = null;
3646
Fred Quintana8570f742010-02-18 10:32:54 -08003647 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003648 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003649
Amith Yamasani04e0d262012-02-14 11:50:53 -08003650 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003651 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3652 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003653 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3654 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3655 }
3656
3657 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3658 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3659 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07003660 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003661 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07003662 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08003663 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003664 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07003665 mResponse = response;
3666 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003667 mExpectActivityLaunch = expectActivityLaunch;
3668 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003669 mAccountName = accountName;
3670 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003671 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003672
Fred Quintanaa698f422009-04-08 19:14:54 -07003673 synchronized (mSessions) {
3674 mSessions.put(toString(), this);
3675 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003676 if (response != null) {
3677 try {
3678 response.asBinder().linkToDeath(this, 0 /* flags */);
3679 } catch (RemoteException e) {
3680 mResponse = null;
3681 binderDied();
3682 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003683 }
Fred Quintana60307342009-03-24 22:48:12 -07003684 }
3685
Fred Quintanaa698f422009-04-08 19:14:54 -07003686 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07003687 if (mResponse == null) {
3688 // this session has already been closed
3689 return null;
3690 }
Fred Quintana60307342009-03-24 22:48:12 -07003691 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07003692 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07003693 return response;
3694 }
3695
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003696 /**
3697 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
3698 * security policy.
3699 *
3700 * In particular we want to make sure that the Authenticator doesn't try to trick users
3701 * into launching aribtrary intents on the device via by tricking to click authenticator
3702 * supplied entries in the system Settings app.
3703 */
3704 protected void checkKeyIntent(
3705 int authUid,
3706 Intent intent) throws SecurityException {
3707 long bid = Binder.clearCallingIdentity();
3708 try {
3709 PackageManager pm = mContext.getPackageManager();
3710 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3711 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
3712 int targetUid = targetActivityInfo.applicationInfo.uid;
3713 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid)) {
3714 String pkgName = targetActivityInfo.packageName;
3715 String activityName = targetActivityInfo.name;
3716 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
3717 + "does not share a signature with the supplying authenticator (%s).";
3718 throw new SecurityException(
3719 String.format(tmpl, activityName, pkgName, mAccountType));
3720 }
3721 } finally {
3722 Binder.restoreCallingIdentity(bid);
3723 }
3724 }
3725
Fred Quintanaa698f422009-04-08 19:14:54 -07003726 private void close() {
3727 synchronized (mSessions) {
3728 if (mSessions.remove(toString()) == null) {
3729 // the session was already closed, so bail out now
3730 return;
3731 }
3732 }
3733 if (mResponse != null) {
3734 // stop listening for response deaths
3735 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3736
3737 // clear this so that we don't accidentally send any further results
3738 mResponse = null;
3739 }
3740 cancelTimeout();
3741 unbind();
3742 }
3743
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003744 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003745 public void binderDied() {
3746 mResponse = null;
3747 close();
3748 }
3749
3750 protected String toDebugString() {
3751 return toDebugString(SystemClock.elapsedRealtime());
3752 }
3753
3754 protected String toDebugString(long now) {
3755 return "Session: expectLaunch " + mExpectActivityLaunch
3756 + ", connected " + (mAuthenticator != null)
3757 + ", stats (" + mNumResults + "/" + mNumRequestContinued
3758 + "/" + mNumErrors + ")"
3759 + ", lifetime " + ((now - mCreationTime) / 1000.0);
3760 }
3761
Fred Quintana60307342009-03-24 22:48:12 -07003762 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003763 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3764 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3765 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003766 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003767 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003768 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003769 }
3770 }
3771
3772 private void unbind() {
3773 if (mAuthenticator != null) {
3774 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003775 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003776 }
3777 }
3778
Fred Quintana60307342009-03-24 22:48:12 -07003779 public void cancelTimeout() {
3780 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3781 }
3782
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003783 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003784 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003785 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003786 try {
3787 run();
3788 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003789 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003790 "remote exception");
3791 }
Fred Quintana60307342009-03-24 22:48:12 -07003792 }
3793
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003794 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003795 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003796 mAuthenticator = null;
3797 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003798 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003799 try {
3800 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3801 "disconnected");
3802 } catch (RemoteException e) {
3803 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3804 Log.v(TAG, "Session.onServiceDisconnected: "
3805 + "caught RemoteException while responding", e);
3806 }
3807 }
Fred Quintana60307342009-03-24 22:48:12 -07003808 }
3809 }
3810
Fred Quintanab839afc2009-10-14 15:57:28 -07003811 public abstract void run() throws RemoteException;
3812
Fred Quintana60307342009-03-24 22:48:12 -07003813 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003814 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003815 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003816 try {
3817 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3818 "timeout");
3819 } catch (RemoteException e) {
3820 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3821 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3822 e);
3823 }
3824 }
Fred Quintana60307342009-03-24 22:48:12 -07003825 }
3826 }
3827
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003828 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003829 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003830 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07003831 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003832 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003833 if (result != null) {
3834 boolean isSuccessfulConfirmCreds = result.getBoolean(
3835 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003836 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003837 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3838 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003839 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003840 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3841 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003842 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003843 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003844 if (needUpdate || mAuthDetailsRequired) {
3845 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3846 if (needUpdate && accountPresent) {
3847 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3848 }
3849 if (mAuthDetailsRequired) {
3850 long lastAuthenticatedTime = -1;
3851 if (accountPresent) {
3852 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3853 mAccounts.openHelper.getReadableDatabase(),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003854 "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3855 + " FROM " +
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003856 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3857 + ACCOUNTS_TYPE + "=?",
3858 new String[] {
3859 mAccountName, mAccountType
3860 });
3861 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003862 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003863 lastAuthenticatedTime);
3864 }
3865 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003866 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003867 if (result != null
3868 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003869 checkKeyIntent(
3870 Binder.getCallingUid(),
3871 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003872 }
3873 if (result != null
3874 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003875 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3876 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003877 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3878 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003879 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3880 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003881 }
Fred Quintana60307342009-03-24 22:48:12 -07003882 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003883 IAccountManagerResponse response;
3884 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003885 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003886 response = mResponse;
3887 } else {
3888 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003889 }
Fred Quintana60307342009-03-24 22:48:12 -07003890 if (response != null) {
3891 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07003892 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08003893 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3894 Log.v(TAG, getClass().getSimpleName()
3895 + " calling onError() on response " + response);
3896 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003897 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07003898 "null bundle returned");
3899 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08003900 if (mStripAuthTokenFromResult) {
3901 result.remove(AccountManager.KEY_AUTHTOKEN);
3902 }
Fred Quintana56285a62010-12-02 14:20:51 -08003903 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3904 Log.v(TAG, getClass().getSimpleName()
3905 + " calling onResult() on response " + response);
3906 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003907 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3908 (intent == null)) {
3909 // All AccountManager error codes are greater than 0
3910 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3911 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3912 } else {
3913 response.onResult(result);
3914 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003915 }
Fred Quintana60307342009-03-24 22:48:12 -07003916 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003917 // if the caller is dead then there is no one to care about remote exceptions
3918 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3919 Log.v(TAG, "failure while notifying response", e);
3920 }
Fred Quintana60307342009-03-24 22:48:12 -07003921 }
3922 }
3923 }
Fred Quintana60307342009-03-24 22:48:12 -07003924
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003925 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003926 public void onRequestContinued() {
3927 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003928 }
3929
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003930 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003931 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003932 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003933 IAccountManagerResponse response = getResponseAndClose();
3934 if (response != null) {
3935 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003936 Log.v(TAG, getClass().getSimpleName()
3937 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003938 }
3939 try {
3940 response.onError(errorCode, errorMessage);
3941 } catch (RemoteException e) {
3942 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3943 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3944 }
3945 }
3946 } else {
3947 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3948 Log.v(TAG, "Session.onError: already closed");
3949 }
Fred Quintana60307342009-03-24 22:48:12 -07003950 }
3951 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003952
3953 /**
3954 * find the component name for the authenticator and initiate a bind
3955 * if no authenticator or the bind fails then return false, otherwise return true
3956 */
3957 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003958 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3959 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3960 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003961 if (authenticatorInfo == null) {
3962 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3963 Log.v(TAG, "there is no authenticator for " + authenticatorType
3964 + ", bailing out");
3965 }
3966 return false;
3967 }
3968
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07003969 final ActivityManager am = mContext.getSystemService(ActivityManager.class);
3970 if (am.isUserRunningAndLocked(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06003971 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07003972 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
3973 + " which isn't encryption aware");
3974 return false;
3975 }
3976
Fred Quintanab839afc2009-10-14 15:57:28 -07003977 Intent intent = new Intent();
3978 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3979 intent.setComponent(authenticatorInfo.componentName);
3980 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3981 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3982 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003983 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003984 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003985 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3986 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3987 }
3988 return false;
3989 }
3990
Fred Quintanab839afc2009-10-14 15:57:28 -07003991 return true;
3992 }
Fred Quintana60307342009-03-24 22:48:12 -07003993 }
3994
3995 private class MessageHandler extends Handler {
3996 MessageHandler(Looper looper) {
3997 super(looper);
3998 }
Costin Manolache3348f142009-09-29 18:58:36 -07003999
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004000 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004001 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004002 switch (msg.what) {
4003 case MESSAGE_TIMED_OUT:
4004 Session session = (Session)msg.obj;
4005 session.onTimedOut();
4006 break;
4007
Amith Yamasani5be347b2013-03-31 17:44:31 -07004008 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004009 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004010 break;
4011
Fred Quintana60307342009-03-24 22:48:12 -07004012 default:
4013 throw new IllegalStateException("unhandled message: " + msg.what);
4014 }
4015 }
4016 }
4017
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004018 static String getPreNDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07004019 File systemDir = Environment.getDataSystemDirectory();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004020 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
4021 PRE_N_DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004022 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07004023 // Migrate old file, if it exists, to the new location.
4024 // Make sure the new file doesn't already exist. A dummy file could have been
4025 // accidentally created in the old location, causing the new one to become corrupted
4026 // as well.
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004027 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07004028 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07004029 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07004030 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07004031 if (!userDir.exists()) {
4032 if (!userDir.mkdirs()) {
4033 throw new IllegalStateException("User dir cannot be created: " + userDir);
4034 }
4035 }
4036 if (!oldFile.renameTo(databaseFile)) {
4037 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
4038 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004039 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004040 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004041 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08004042 }
4043
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004044 static String getDeDatabaseName(int userId) {
4045 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
4046 DE_DATABASE_NAME);
4047 return databaseFile.getPath();
4048 }
4049
4050 static String getCeDatabaseName(int userId) {
4051 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4052 CE_DATABASE_NAME);
4053 return databaseFile.getPath();
4054 }
4055
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004056 private static class DebugDbHelper{
4057 private DebugDbHelper() {
4058 }
4059
4060 private static String TABLE_DEBUG = "debug_table";
4061
4062 // Columns for the table
4063 private static String ACTION_TYPE = "action_type";
4064 private static String TIMESTAMP = "time";
4065 private static String CALLER_UID = "caller_uid";
4066 private static String TABLE_NAME = "table_name";
4067 private static String KEY = "primary_key";
4068
4069 // These actions correspond to the occurrence of real actions. Since
4070 // these are called by the authenticators, the uid associated will be
4071 // of the authenticator.
4072 private static String ACTION_SET_PASSWORD = "action_set_password";
4073 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4074 private static String ACTION_ACCOUNT_ADD = "action_account_add";
4075 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
4076 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4077 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4078
4079 // These actions don't necessarily correspond to any action on
4080 // accountDb taking place. As an example, there might be a request for
4081 // addingAccount, which might not lead to addition of account on grounds
4082 // of bad authentication. We will still be logging it to keep track of
4083 // who called.
4084 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4085 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004086
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004087 //This action doesn't add account to accountdb. Account is only
4088 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08004089 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004090 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4091 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08004092
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004093 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4094
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004095 private static void createDebugTable(SQLiteDatabase db) {
4096 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4097 + ACCOUNTS_ID + " INTEGER,"
4098 + ACTION_TYPE + " TEXT NOT NULL, "
4099 + TIMESTAMP + " DATETIME,"
4100 + CALLER_UID + " INTEGER NOT NULL,"
4101 + TABLE_NAME + " TEXT NOT NULL,"
4102 + KEY + " INTEGER PRIMARY KEY)");
4103 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4104 }
4105 }
4106
4107 private void logRecord(UserAccounts accounts, String action, String tableName) {
4108 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4109 logRecord(db, action, tableName, -1, accounts);
4110 }
4111
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004112 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4113 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4114 logRecord(db, action, tableName, -1, accounts, uid);
4115 }
4116
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004117 /*
4118 * This function receives an opened writable database.
4119 */
4120 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4121 UserAccounts userAccount) {
4122 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4123 }
4124
4125 /*
4126 * This function receives an opened writable database.
4127 */
4128 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4129 UserAccounts userAccount, int callingUid) {
4130 SQLiteStatement logStatement = userAccount.statementForLogging;
4131 logStatement.bindLong(1, accountId);
4132 logStatement.bindString(2, action);
4133 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4134 logStatement.bindLong(4, callingUid);
4135 logStatement.bindString(5, tableName);
4136 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
4137 logStatement.execute();
4138 logStatement.clearBindings();
4139 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4140 % MAX_DEBUG_DB_SIZE;
4141 }
4142
4143 /*
4144 * This should only be called once to compile the sql statement for logging
4145 * and to find the insertion point.
4146 */
4147 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4148 UserAccounts userAccount) {
4149 // Initialize the count if not done earlier.
4150 int size = (int) getDebugTableRowCount(db);
4151 if (size >= MAX_DEBUG_DB_SIZE) {
4152 // Table is full, and we need to find the point where to insert.
4153 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4154 } else {
4155 userAccount.debugDbInsertionPoint = size;
4156 }
4157 compileSqlStatementForLogging(db, userAccount);
4158 }
4159
4160 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4161 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4162 + " VALUES (?,?,?,?,?,?)";
4163 userAccount.statementForLogging = db.compileStatement(sql);
4164 }
4165
4166 private long getDebugTableRowCount(SQLiteDatabase db) {
4167 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4168 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4169 }
4170
4171 /*
4172 * Finds the row key where the next insertion should take place. This should
4173 * be invoked only if the table has reached its full capacity.
4174 */
4175 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4176 // This query finds the smallest timestamp value (and if 2 records have
4177 // same timestamp, the choose the lower id).
4178 String queryCountDebugDbRows = new StringBuilder()
4179 .append("SELECT ").append(DebugDbHelper.KEY)
4180 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4181 .append(" ORDER BY ")
4182 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4183 .append(" LIMIT 1")
4184 .toString();
4185 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4186 }
4187
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004188 static class PreNDatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004189
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004190 private final Context mContext;
4191 private final int mUserId;
4192
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004193 public PreNDatabaseHelper(Context context, int userId) {
4194 super(context, AccountManagerService.getPreNDatabaseName(userId), null,
4195 PRE_N_DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004196 mContext = context;
4197 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004198 }
4199
4200 @Override
4201 public void onCreate(SQLiteDatabase db) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004202 // We use PreNDatabaseHelper only if pre-N db exists
4203 throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004204 }
4205
Amith Yamasani67df64b2012-12-14 12:09:36 -08004206 private void createSharedAccountsTable(SQLiteDatabase db) {
4207 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4208 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4209 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4210 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4211 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4212 }
4213
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004214 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4215 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4216 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4217 }
4218
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004219 private void addOldAccountNameColumn(SQLiteDatabase db) {
4220 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4221 }
4222
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004223 private void addDebugTable(SQLiteDatabase db) {
4224 DebugDbHelper.createDebugTable(db);
4225 }
4226
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004227 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004228 db.execSQL(""
4229 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4230 + " BEGIN"
4231 + " DELETE FROM " + TABLE_AUTHTOKENS
4232 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4233 + " DELETE FROM " + TABLE_EXTRAS
4234 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004235 + " DELETE FROM " + TABLE_GRANTS
4236 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004237 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004238 }
4239
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004240 private void createGrantsTable(SQLiteDatabase db) {
4241 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4242 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4243 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4244 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4245 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4246 + "," + GRANTS_GRANTEE_UID + "))");
4247 }
4248
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004249 private void populateMetaTableWithAuthTypeAndUID(
4250 SQLiteDatabase db,
4251 Map<String, Integer> authTypeAndUIDMap) {
4252 Iterator<Entry<String, Integer>> iterator = authTypeAndUIDMap.entrySet().iterator();
4253 while (iterator.hasNext()) {
4254 Entry<String, Integer> entry = iterator.next();
4255 ContentValues values = new ContentValues();
4256 values.put(META_KEY,
4257 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
4258 values.put(META_VALUE, entry.getValue());
4259 db.insert(TABLE_META, null, values);
4260 }
4261 }
4262
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004263 /**
4264 * Pre-N database may need an upgrade before splitting
4265 */
Fred Quintana60307342009-03-24 22:48:12 -07004266 @Override
4267 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004268 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004269
Fred Quintanaa698f422009-04-08 19:14:54 -07004270 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004271 // no longer need to do anything since the work is done
4272 // when upgrading from version 2
4273 oldVersion++;
4274 }
4275
4276 if (oldVersion == 2) {
4277 createGrantsTable(db);
4278 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4279 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004280 oldVersion++;
4281 }
Costin Manolache3348f142009-09-29 18:58:36 -07004282
4283 if (oldVersion == 3) {
4284 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4285 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4286 oldVersion++;
4287 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004288
4289 if (oldVersion == 4) {
4290 createSharedAccountsTable(db);
4291 oldVersion++;
4292 }
4293
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004294 if (oldVersion == 5) {
4295 addOldAccountNameColumn(db);
4296 oldVersion++;
4297 }
4298
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004299 if (oldVersion == 6) {
4300 addLastSuccessfullAuthenticatedTimeColumn(db);
4301 oldVersion++;
4302 }
4303
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004304 if (oldVersion == 7) {
4305 addDebugTable(db);
4306 oldVersion++;
4307 }
4308
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004309 if (oldVersion == 8) {
4310 populateMetaTableWithAuthTypeAndUID(
4311 db,
4312 AccountManagerService.getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
4313 oldVersion++;
4314 }
4315
Amith Yamasani67df64b2012-12-14 12:09:36 -08004316 if (oldVersion != newVersion) {
4317 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4318 }
Fred Quintana60307342009-03-24 22:48:12 -07004319 }
4320
4321 @Override
4322 public void onOpen(SQLiteDatabase db) {
4323 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4324 }
4325 }
4326
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004327 static class DeDatabaseHelper extends SQLiteOpenHelper {
4328
4329 private final int mUserId;
4330 private volatile boolean mCeAttached;
4331
4332 private DeDatabaseHelper(Context context, int userId) {
4333 super(context, getDeDatabaseName(userId), null, DE_DATABASE_VERSION);
4334 mUserId = userId;
4335 }
4336
4337 /**
4338 * This call needs to be made while the mCacheLock is held. The way to
4339 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4340 * @param db The database.
4341 */
4342 @Override
4343 public void onCreate(SQLiteDatabase db) {
4344 Log.i(TAG, "Creating DE database for user " + mUserId);
4345 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4346 + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4347 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4348 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4349 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4350 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4351 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4352
4353 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4354 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4355 + META_VALUE + " TEXT)");
4356
4357 createGrantsTable(db);
4358 createSharedAccountsTable(db);
4359 createAccountsDeletionTrigger(db);
4360 DebugDbHelper.createDebugTable(db);
4361 }
4362
4363 private void createSharedAccountsTable(SQLiteDatabase db) {
4364 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4365 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4366 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4367 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4368 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4369 }
4370
4371 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4372 db.execSQL(""
4373 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4374 + " BEGIN"
4375 + " DELETE FROM " + TABLE_GRANTS
4376 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4377 + " END");
4378 }
4379
4380 private void createGrantsTable(SQLiteDatabase db) {
4381 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4382 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4383 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4384 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4385 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4386 + "," + GRANTS_GRANTEE_UID + "))");
4387 }
4388
4389 @Override
4390 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4391 Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4392
4393 if (oldVersion != newVersion) {
4394 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4395 }
4396 }
4397
4398 public void attachCeDatabase() {
4399 File ceDbFile = new File(getCeDatabaseName(mUserId));
4400 SQLiteDatabase db = getWritableDatabase();
4401 db.execSQL("ATTACH DATABASE '" + ceDbFile.getPath()+ "' AS ceDb");
4402 mCeAttached = true;
4403 }
4404
4405 public boolean isCeDatabaseAttached() {
4406 return mCeAttached;
4407 }
4408
4409
4410 public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
4411 if(!mCeAttached) {
4412 Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user "
4413 + mUserId + " is still locked ", new Throwable());
4414 }
4415 return super.getReadableDatabase();
4416 }
4417
4418 public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
4419 if(!mCeAttached) {
4420 Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
4421 + " is still locked ", new Throwable());
4422 }
4423 return super.getWritableDatabase();
4424 }
4425
4426 @Override
4427 public void onOpen(SQLiteDatabase db) {
4428 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
4429 }
4430
4431 private void migratePreNDbToDe(File preNDbFile) {
4432 Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
4433 SQLiteDatabase db = getWritableDatabase();
4434 db.execSQL("ATTACH DATABASE '" + preNDbFile.getPath() + "' AS preNDb");
4435 db.beginTransaction();
4436 // Copy accounts fields
4437 db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
4438 + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4439 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4440 + ") "
4441 + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4442 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4443 + " FROM preNDb." + TABLE_ACCOUNTS);
4444 // Copy SHARED_ACCOUNTS
4445 db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
4446 + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
4447 "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4448 + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
4449 // Copy DEBUG_TABLE
4450 db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
4451 + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4452 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4453 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
4454 "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4455 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4456 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
4457 + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
4458 // Copy GRANTS
4459 db.execSQL("INSERT INTO " + TABLE_GRANTS
4460 + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4461 + GRANTS_GRANTEE_UID + ") " +
4462 "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4463 + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
4464 // Copy META
4465 db.execSQL("INSERT INTO " + TABLE_META
4466 + "(" + META_KEY + "," + META_VALUE + ") "
4467 + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
4468 db.setTransactionSuccessful();
4469 db.endTransaction();
4470
4471 db.execSQL("DETACH DATABASE preNDb");
4472 }
4473
4474 static DeDatabaseHelper create(Context context, int userId) {
4475 File oldDb = new File(getPreNDatabaseName(userId));
4476 File newDb = new File(getDeDatabaseName(userId));
4477 boolean newDbExists = newDb.exists();
4478 DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId);
4479 // If the db just created, and there is a legacy db, migrate it
4480 if (!newDbExists && oldDb.exists()) {
4481 // Migrate legacy db to the latest version - PRE_N_DATABASE_VERSION
4482 PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId);
4483 // Open the database to force upgrade if required
4484 preNDatabaseHelper.getWritableDatabase();
4485 preNDatabaseHelper.close();
4486 // Move data without SPII to DE
4487 deDatabaseHelper.migratePreNDbToDe(oldDb);
4488 }
4489 return deDatabaseHelper;
4490 }
4491 }
4492
4493 static class CeDatabaseHelper extends SQLiteOpenHelper {
4494
4495 public CeDatabaseHelper(Context context, int userId) {
4496 super(context, getCeDatabaseName(userId), null, CE_DATABASE_VERSION);
4497 }
4498
4499 /**
4500 * This call needs to be made while the mCacheLock is held.
4501 * @param db The database.
4502 */
4503 @Override
4504 public void onCreate(SQLiteDatabase db) {
4505 Log.i(TAG, "Creating CE database " + getDatabaseName());
4506 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4507 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4508 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4509 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4510 + ACCOUNTS_PASSWORD + " TEXT, "
4511 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4512
4513 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
4514 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4515 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4516 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
4517 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
4518 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
4519
4520 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
4521 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4522 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
4523 + EXTRAS_KEY + " TEXT NOT NULL, "
4524 + EXTRAS_VALUE + " TEXT, "
4525 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
4526
4527 createAccountsDeletionTrigger(db);
4528 }
4529
4530 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4531 db.execSQL(""
4532 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4533 + " BEGIN"
4534 + " DELETE FROM " + TABLE_AUTHTOKENS
4535 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4536 + " DELETE FROM " + TABLE_EXTRAS
4537 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4538 + " END");
4539 }
4540
4541 @Override
4542 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4543 Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
4544
4545 if (oldVersion == 9) {
4546 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4547 Log.v(TAG, "onUpgrade upgrading to v10");
4548 }
4549 db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
4550 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
4551 // Recreate the trigger, since the old one references the table to be removed
4552 db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
4553 createAccountsDeletionTrigger(db);
4554 db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
4555 db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
4556 oldVersion ++;
4557 }
4558
4559 if (oldVersion != newVersion) {
4560 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4561 }
4562 }
4563
4564 @Override
4565 public void onOpen(SQLiteDatabase db) {
4566 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
4567 }
4568
4569 static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
4570 String type) {
4571 Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
4572 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
4573 new String[]{name, type}, null, null, null);
4574 try {
4575 if (cursor.moveToNext()) {
4576 return cursor.getString(0);
4577 }
4578 return null;
4579 } finally {
4580 cursor.close();
4581 }
4582 }
4583
4584 /**
4585 * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
4586 * it also performs migration to the new CE database.
4587 * @param context
4588 * @param userId id of the user where the database is located
4589 */
4590 static CeDatabaseHelper create(Context context, int userId) {
4591
4592 File oldDatabaseFile = new File(getPreNDatabaseName(userId));
4593 File ceDatabaseFile = new File(getCeDatabaseName(userId));
4594 boolean newDbExists = ceDatabaseFile.exists();
4595 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4596 Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
4597 + oldDatabaseFile.exists() + " newDbExists=" + newDbExists);
4598 }
4599 boolean removeOldDb = false;
4600 if (!newDbExists && oldDatabaseFile.exists()) {
4601 removeOldDb = migratePreNDbToCe(oldDatabaseFile, ceDatabaseFile);
4602 }
4603 // Try to open and upgrade if necessary
4604 CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, userId);
4605 ceHelper.getWritableDatabase();
4606 ceHelper.close();
4607 if (removeOldDb) {
4608 // TODO STOPSHIP - backup file during testing. Remove file before the release
4609 Log.i(TAG, "Migration complete - creating backup of old db " + oldDatabaseFile);
4610 renameToBakFile(oldDatabaseFile);
4611 }
4612 return ceHelper;
4613 }
4614
4615 private static void renameToBakFile(File file) {
4616 File bakFile = new File(file.getPath() + ".bak");
4617 if (!file.renameTo(bakFile)) {
4618 Log.e(TAG, "Cannot move file to " + bakFile);
4619 }
4620 }
4621
4622 private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
4623 Log.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
4624 try {
4625 FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
4626 } catch (IOException e) {
4627 Log.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
4628 // Try to remove potentially damaged file if I/O error occurred
4629 deleteDbFileWarnIfFailed(ceDbFile);
4630 return false;
4631 }
4632 return true;
4633 }
4634 }
4635
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004636 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004637 return asBinder();
4638 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004639
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004640 /**
4641 * Searches array of arguments for the specified string
4642 * @param args array of argument strings
4643 * @param value value to search for
4644 * @return true if the value is contained in the array
4645 */
4646 private static boolean scanArgs(String[] args, String value) {
4647 if (args != null) {
4648 for (String arg : args) {
4649 if (value.equals(arg)) {
4650 return true;
4651 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004652 }
4653 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004654 return false;
4655 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004656
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004657 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004658 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07004659 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4660 != PackageManager.PERMISSION_GRANTED) {
4661 fout.println("Permission Denial: can't dump AccountsManager from from pid="
4662 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4663 + " without permission " + android.Manifest.permission.DUMP);
4664 return;
4665 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004666 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004667 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004668
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004669 final List<UserInfo> users = getUserManager().getUsers();
4670 for (UserInfo user : users) {
4671 ipw.println("User " + user + ":");
4672 ipw.increaseIndent();
4673 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4674 ipw.println();
4675 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08004676 }
4677 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004678
Amith Yamasani04e0d262012-02-14 11:50:53 -08004679 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4680 String[] args, boolean isCheckinRequest) {
4681 synchronized (userAccounts.cacheLock) {
4682 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004683
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004684 if (isCheckinRequest) {
4685 // This is a checkin request. *Only* upload the account types and the count of each.
4686 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4687 null, null, ACCOUNTS_TYPE, null, null);
4688 try {
4689 while (cursor.moveToNext()) {
4690 // print type,count
4691 fout.println(cursor.getString(0) + "," + cursor.getString(1));
4692 }
4693 } finally {
4694 if (cursor != null) {
4695 cursor.close();
4696 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004697 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004698 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004699 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07004700 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004701 fout.println("Accounts: " + accounts.length);
4702 for (Account account : accounts) {
4703 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004704 }
Fred Quintana307da1a2010-01-21 14:24:20 -08004705
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004706 // Add debug information.
4707 fout.println();
4708 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4709 null, null, null, null, DebugDbHelper.TIMESTAMP);
4710 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4711 fout.println("Accounts History");
4712 try {
4713 while (cursor.moveToNext()) {
4714 // print type,count
4715 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4716 cursor.getString(2) + "," + cursor.getString(3) + ","
4717 + cursor.getString(4) + "," + cursor.getString(5));
4718 }
4719 } finally {
4720 cursor.close();
4721 }
4722
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004723 fout.println();
4724 synchronized (mSessions) {
4725 final long now = SystemClock.elapsedRealtime();
4726 fout.println("Active Sessions: " + mSessions.size());
4727 for (Session session : mSessions.values()) {
4728 fout.println(" " + session.toDebugString(now));
4729 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004730 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004731
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004732 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004733 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004734 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004735 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004736 }
4737
Amith Yamasani04e0d262012-02-14 11:50:53 -08004738 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07004739 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004740 long identityToken = clearCallingIdentity();
4741 try {
4742 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4743 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4744 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004745
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004746 if (intent.getComponent() != null &&
4747 GrantCredentialsPermissionActivity.class.getName().equals(
4748 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004749 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004750 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004751 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004752 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004753 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004754 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07004755 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004756 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004757 Notification n = new Notification.Builder(contextForUser)
4758 .setWhen(0)
4759 .setSmallIcon(android.R.drawable.stat_sys_warning)
4760 .setColor(contextForUser.getColor(
4761 com.android.internal.R.color.system_notification_accent_color))
4762 .setContentTitle(String.format(notificationTitleFormat, account.name))
4763 .setContentText(message)
4764 .setContentIntent(PendingIntent.getActivityAsUser(
4765 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4766 null, user))
4767 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004768 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004769 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004770 } finally {
4771 restoreCallingIdentity(identityToken);
4772 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004773 }
4774
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004775 protected void installNotification(final int notificationId, final Notification n,
4776 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08004777 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004778 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08004779 }
4780
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004781 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004782 long identityToken = clearCallingIdentity();
4783 try {
4784 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004785 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004786 } finally {
4787 restoreCallingIdentity(identityToken);
4788 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004789 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004790
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004791 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
4792 for (String perm : permissions) {
4793 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
4794 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4795 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
4796 }
4797 final int opCode = AppOpsManager.permissionToOpCode(perm);
4798 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
4799 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
4800 return true;
4801 }
4802 }
4803 }
4804 return false;
4805 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004806
Amith Yamasani67df64b2012-12-14 12:09:36 -08004807 private int handleIncomingUser(int userId) {
4808 try {
4809 return ActivityManagerNative.getDefault().handleIncomingUser(
4810 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
4811 } catch (RemoteException re) {
4812 // Shouldn't happen, local.
4813 }
4814 return userId;
4815 }
4816
Christopher Tateccbf84f2013-05-08 15:25:41 -07004817 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004818 final int callingUserId = UserHandle.getUserId(callingUid);
4819
4820 final PackageManager userPackageManager;
4821 try {
4822 userPackageManager = mContext.createPackageContextAsUser(
4823 "android", 0, new UserHandle(callingUserId)).getPackageManager();
4824 } catch (NameNotFoundException e) {
4825 return false;
4826 }
4827
4828 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07004829 for (String name : packages) {
4830 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004831 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08004832 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08004833 && (packageInfo.applicationInfo.privateFlags
4834 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07004835 return true;
4836 }
4837 } catch (PackageManager.NameNotFoundException e) {
4838 return false;
4839 }
4840 }
4841 return false;
4842 }
4843
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004844 private boolean permissionIsGranted(
4845 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07004846 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07004847 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004848 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07004849 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08004850 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004851 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4852 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08004853 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004854 + ": is authenticator? " + fromAuthenticator
4855 + ", has explicit permission? " + hasExplicitGrants);
4856 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07004857 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004858 }
4859
Svetoslavf3f02ac2015-09-08 14:36:35 -07004860 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
4861 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004862 if (accountType == null) {
4863 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004864 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07004865 return getTypesVisibleToCaller(callingUid, userId,
4866 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004867 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004868 }
4869
4870 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
4871 if (accountType == null) {
4872 return false;
4873 } else {
4874 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
4875 }
4876 }
4877
Svetoslavf3f02ac2015-09-08 14:36:35 -07004878 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
4879 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004880 boolean isPermitted =
4881 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
4882 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004883 return getTypesForCaller(callingUid, userId, isPermitted);
4884 }
4885
4886 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
4887 return getTypesForCaller(callingUid, userId, false);
4888 }
4889
4890 private List<String> getTypesForCaller(
4891 int callingUid, int userId, boolean isOtherwisePermitted) {
4892 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004893 long identityToken = Binder.clearCallingIdentity();
4894 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
4895 try {
4896 serviceInfos = mAuthenticatorCache.getAllServices(userId);
4897 } finally {
4898 Binder.restoreCallingIdentity(identityToken);
4899 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004900 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004901 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004902 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
4903 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
4904 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004905 }
4906 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004907 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004908 }
4909
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004910 private boolean isAccountPresentForCaller(String accountName, String accountType) {
4911 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
4912 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
4913 if (account.name.equals(accountName)) {
4914 return true;
4915 }
4916 }
4917 }
4918 return false;
4919 }
4920
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004921 private static void checkManageUsersPermission(String message) {
4922 if (ActivityManager.checkComponentPermission(
4923 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
4924 != PackageManager.PERMISSION_GRANTED) {
4925 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
4926 }
4927 }
4928
Amith Yamasani04e0d262012-02-14 11:50:53 -08004929 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
4930 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004931 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004932 return true;
4933 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004934 UserAccounts accounts = getUserAccountsForCaller();
4935 synchronized (accounts.cacheLock) {
4936 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
4937 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004938 account.name, account.type};
4939 final boolean permissionGranted =
4940 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
4941 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
4942 // TODO: Skip this check when running automated tests. Replace this
4943 // with a more general solution.
4944 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08004945 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004946 + " but ignoring since device is in test harness.");
4947 return true;
4948 }
4949 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004950 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004951 }
4952
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004953 private boolean isSystemUid(int callingUid) {
4954 String[] packages = null;
4955 long ident = Binder.clearCallingIdentity();
4956 try {
4957 packages = mPackageManager.getPackagesForUid(callingUid);
4958 } finally {
4959 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004960 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004961 if (packages != null) {
4962 for (String name : packages) {
4963 try {
4964 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
4965 if (packageInfo != null
4966 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
4967 != 0) {
4968 return true;
4969 }
4970 } catch (PackageManager.NameNotFoundException e) {
4971 Log.w(TAG, String.format("Could not find package [%s]", name), e);
4972 }
4973 }
4974 } else {
4975 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004976 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004977 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00004978 }
4979
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004980 /** Succeeds if any of the specified permissions are granted. */
4981 private void checkReadAccountsPermitted(
4982 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004983 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004984 int userId,
4985 String opPackageName) {
4986 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004987 String msg = String.format(
4988 "caller uid %s cannot access %s accounts",
4989 callingUid,
4990 accountType);
4991 Log.w(TAG, " " + msg);
4992 throw new SecurityException(msg);
4993 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004994 }
4995
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004996 private boolean canUserModifyAccounts(int userId, int callingUid) {
4997 // the managing app can always modify accounts
4998 if (isProfileOwner(callingUid)) {
4999 return true;
5000 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005001 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5002 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5003 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005004 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005005 return true;
5006 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005007
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005008 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5009 // the managing app can always modify accounts
5010 if (isProfileOwner(callingUid)) {
5011 return true;
5012 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005013 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5014 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005015 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005016 if (typesArray == null) {
5017 return true;
5018 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005019 for (String forbiddenType : typesArray) {
5020 if (forbiddenType.equals(accountType)) {
5021 return false;
5022 }
5023 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005024 return true;
5025 }
5026
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005027 private boolean isProfileOwner(int uid) {
5028 final DevicePolicyManagerInternal dpmi =
5029 LocalServices.getService(DevicePolicyManagerInternal.class);
5030 return (dpmi != null)
5031 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5032 }
5033
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005034 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005035 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5036 throws RemoteException {
5037 final int callingUid = getCallingUid();
5038
Amith Yamasani27db4682013-03-30 17:07:47 -07005039 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005040 throw new SecurityException();
5041 }
5042
5043 if (value) {
5044 grantAppPermission(account, authTokenType, uid);
5045 } else {
5046 revokeAppPermission(account, authTokenType, uid);
5047 }
5048 }
5049
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005050 /**
5051 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5052 * <p>
5053 * Although this is public it can only be accessed via the AccountManagerService object
5054 * which is in the system. This means we don't need to protect it with permissions.
5055 * @hide
5056 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005057 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005058 if (account == null || authTokenType == null) {
5059 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005060 return;
5061 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005062 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005063 synchronized (accounts.cacheLock) {
5064 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005065 db.beginTransaction();
5066 try {
5067 long accountId = getAccountIdLocked(db, account);
5068 if (accountId >= 0) {
5069 ContentValues values = new ContentValues();
5070 values.put(GRANTS_ACCOUNTS_ID, accountId);
5071 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
5072 values.put(GRANTS_GRANTEE_UID, uid);
5073 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
5074 db.setTransactionSuccessful();
5075 }
5076 } finally {
5077 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005078 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005079 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005080 UserHandle.of(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005081 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005082 }
5083
5084 /**
5085 * Don't allow callers with the given uid permission to get credentials for
5086 * account/authTokenType.
5087 * <p>
5088 * Although this is public it can only be accessed via the AccountManagerService object
5089 * which is in the system. This means we don't need to protect it with permissions.
5090 * @hide
5091 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005092 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005093 if (account == null || authTokenType == null) {
5094 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005095 return;
5096 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005097 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005098 synchronized (accounts.cacheLock) {
5099 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005100 db.beginTransaction();
5101 try {
5102 long accountId = getAccountIdLocked(db, account);
5103 if (accountId >= 0) {
5104 db.delete(TABLE_GRANTS,
5105 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
5106 + GRANTS_GRANTEE_UID + "=?",
5107 new String[]{String.valueOf(accountId), authTokenType,
5108 String.valueOf(uid)});
5109 db.setTransactionSuccessful();
5110 }
5111 } finally {
5112 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005113 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005114 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5115 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005116 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005117 }
Fred Quintana56285a62010-12-02 14:20:51 -08005118
5119 static final private String stringArrayToString(String[] value) {
5120 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5121 }
5122
Amith Yamasani04e0d262012-02-14 11:50:53 -08005123 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5124 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005125 if (oldAccountsForType != null) {
5126 ArrayList<Account> newAccountsList = new ArrayList<Account>();
5127 for (Account curAccount : oldAccountsForType) {
5128 if (!curAccount.equals(account)) {
5129 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005130 }
5131 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005132 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005133 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005134 } else {
5135 Account[] newAccountsForType = new Account[newAccountsList.size()];
5136 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005137 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005138 }
Fred Quintana56285a62010-12-02 14:20:51 -08005139 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005140 accounts.userDataCache.remove(account);
5141 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005142 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005143 }
5144
5145 /**
5146 * This assumes that the caller has already checked that the account is not already present.
5147 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08005148 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5149 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005150 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5151 Account[] newAccountsForType = new Account[oldLength + 1];
5152 if (accountsForType != null) {
5153 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005154 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005155 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005156 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08005157 }
5158
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005159 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07005160 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005161 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07005162 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005163 return unfiltered;
5164 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005165 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005166 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005167 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005168 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005169 // otherwise return non-shared accounts only.
5170 // This might be a temporary way to specify a whitelist
5171 String whiteList = mContext.getResources().getString(
5172 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5173 for (String packageName : packages) {
5174 if (whiteList.contains(";" + packageName + ";")) {
5175 return unfiltered;
5176 }
5177 }
5178 ArrayList<Account> allowed = new ArrayList<Account>();
5179 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5180 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005181 String requiredAccountType = "";
5182 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005183 // If there's an explicit callingPackage specified, check if that package
5184 // opted in to see restricted accounts.
5185 if (callingPackage != null) {
5186 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005187 if (pi != null && pi.restrictedAccountType != null) {
5188 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005189 }
5190 } else {
5191 // Otherwise check if the callingUid has a package that has opted in
5192 for (String packageName : packages) {
5193 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5194 if (pi != null && pi.restrictedAccountType != null) {
5195 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005196 break;
5197 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005198 }
5199 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005200 } catch (NameNotFoundException nnfe) {
5201 }
5202 for (Account account : unfiltered) {
5203 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005204 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005205 } else {
5206 boolean found = false;
5207 for (Account shared : sharedAccounts) {
5208 if (shared.equals(account)) {
5209 found = true;
5210 break;
5211 }
5212 }
5213 if (!found) {
5214 allowed.add(account);
5215 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005216 }
5217 }
5218 Account[] filtered = new Account[allowed.size()];
5219 allowed.toArray(filtered);
5220 return filtered;
5221 } else {
5222 return unfiltered;
5223 }
5224 }
5225
Amith Yamasani27db4682013-03-30 17:07:47 -07005226 /*
5227 * packageName can be null. If not null, it should be used to filter out restricted accounts
5228 * that the package is not allowed to access.
5229 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005230 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07005231 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005232 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005233 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005234 if (accounts == null) {
5235 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005236 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005237 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07005238 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005239 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005240 } else {
5241 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005242 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005243 totalLength += accounts.length;
5244 }
5245 if (totalLength == 0) {
5246 return EMPTY_ACCOUNT_ARRAY;
5247 }
5248 Account[] accounts = new Account[totalLength];
5249 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005250 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005251 System.arraycopy(accountsOfType, 0, accounts, totalLength,
5252 accountsOfType.length);
5253 totalLength += accountsOfType.length;
5254 }
Amith Yamasani27db4682013-03-30 17:07:47 -07005255 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005256 }
5257 }
5258
Amith Yamasani04e0d262012-02-14 11:50:53 -08005259 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5260 Account account, String key, String value) {
5261 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005262 if (userDataForAccount == null) {
5263 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005264 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005265 }
5266 if (value == null) {
5267 userDataForAccount.remove(key);
5268 } else {
5269 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005270 }
5271 }
5272
Carlos Valdivia91979be2015-05-22 14:11:35 -07005273 protected String readCachedTokenInternal(
5274 UserAccounts accounts,
5275 Account account,
5276 String tokenType,
5277 String callingPackage,
5278 byte[] pkgSigDigest) {
5279 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005280 return accounts.accountTokenCaches.get(
5281 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005282 }
5283 }
5284
Amith Yamasani04e0d262012-02-14 11:50:53 -08005285 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5286 Account account, String key, String value) {
5287 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005288 if (authTokensForAccount == null) {
5289 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005290 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005291 }
5292 if (value == null) {
5293 authTokensForAccount.remove(key);
5294 } else {
5295 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005296 }
5297 }
5298
Amith Yamasani04e0d262012-02-14 11:50:53 -08005299 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5300 String authTokenType) {
5301 synchronized (accounts.cacheLock) {
5302 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005303 if (authTokensForAccount == null) {
5304 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005305 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005306 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005307 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005308 }
5309 return authTokensForAccount.get(authTokenType);
5310 }
5311 }
5312
Simranjit Kohli858511c2016-03-10 18:36:11 +00005313 protected String readUserDataInternalLocked(
5314 UserAccounts accounts, Account account, String key) {
5315 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
5316 if (userDataForAccount == null) {
5317 // need to populate the cache for this account
5318 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
5319 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
5320 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005321 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005322 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005323 }
5324
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005325 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
5326 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005327 HashMap<String, String> userDataForAccount = new HashMap<>();
5328 Cursor cursor = db.query(CE_TABLE_EXTRAS,
Fred Quintana56285a62010-12-02 14:20:51 -08005329 COLUMNS_EXTRAS_KEY_AND_VALUE,
5330 SELECTION_USERDATA_BY_ACCOUNT,
5331 new String[]{account.name, account.type},
5332 null, null, null);
5333 try {
5334 while (cursor.moveToNext()) {
5335 final String tmpkey = cursor.getString(0);
5336 final String value = cursor.getString(1);
5337 userDataForAccount.put(tmpkey, value);
5338 }
5339 } finally {
5340 cursor.close();
5341 }
5342 return userDataForAccount;
5343 }
5344
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005345 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
5346 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005347 HashMap<String, String> authTokensForAccount = new HashMap<>();
5348 Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
Fred Quintana56285a62010-12-02 14:20:51 -08005349 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
5350 SELECTION_AUTHTOKENS_BY_ACCOUNT,
5351 new String[]{account.name, account.type},
5352 null, null, null);
5353 try {
5354 while (cursor.moveToNext()) {
5355 final String type = cursor.getString(0);
5356 final String authToken = cursor.getString(1);
5357 authTokensForAccount.put(type, authToken);
5358 }
5359 } finally {
5360 cursor.close();
5361 }
5362 return authTokensForAccount;
5363 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005364
5365 private Context getContextForUser(UserHandle user) {
5366 try {
5367 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5368 } catch (NameNotFoundException e) {
5369 // Default to mContext, not finding the package system is running as is unlikely.
5370 return mContext;
5371 }
5372 }
Sandra Kwan78812282015-11-04 11:19:47 -08005373
5374 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5375 try {
5376 response.onResult(result);
5377 } catch (RemoteException e) {
5378 // if the caller is dead then there is no one to care about remote
5379 // exceptions
5380 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5381 Log.v(TAG, "failure while notifying response", e);
5382 }
5383 }
5384 }
5385
5386 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5387 String errorMessage) {
5388 try {
5389 response.onError(errorCode, errorMessage);
5390 } catch (RemoteException e) {
5391 // if the caller is dead then there is no one to care about remote
5392 // exceptions
5393 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5394 Log.v(TAG, "failure while notifying response", e);
5395 }
5396 }
5397 }
Fred Quintana60307342009-03-24 22:48:12 -07005398}