blob: bb323031c011aea4a36138356a865df124897e31 [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 Kohli27d0e1f2016-02-25 21:15:02 +0000785 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700786 } finally {
787 restoreCallingIdentity(identityToken);
788 }
789 }
790
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800791 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100792 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700793 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800794 if (Log.isLoggable(TAG, Log.VERBOSE)) {
795 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100796 + "for user id " + userId
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700797 + "caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800798 + ", pid " + Binder.getCallingPid());
799 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100800 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700801 if (isCrossUser(callingUid, userId)) {
802 throw new SecurityException(
803 String.format(
804 "User %s tying to get authenticator types for %s" ,
805 UserHandle.getCallingUserId(),
806 userId));
807 }
808
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700809 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700810 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000811 return getAuthenticatorTypesInternal(userId);
812
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700813 } finally {
814 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700815 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700816 }
817
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000818 /**
819 * Should only be called inside of a clearCallingIdentity block.
820 */
821 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
822 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
823 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
824 AuthenticatorDescription[] types =
825 new AuthenticatorDescription[authenticatorCollection.size()];
826 int i = 0;
827 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
828 : authenticatorCollection) {
829 types[i] = authenticator.type;
830 i++;
831 }
832 return types;
833 }
834
835
836
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700837 private boolean isCrossUser(int callingUid, int userId) {
838 return (userId != UserHandle.getCallingUserId()
839 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100840 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700841 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
842 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100843 }
844
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700845 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700846 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600847 Bundle.setDefusable(extras, true);
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700848 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800849 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700850 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700851 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800852 + ", pid " + Binder.getCallingPid());
853 }
Fred Quintana382601f2010-03-25 12:25:10 -0700854 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000855 int userId = UserHandle.getCallingUserId();
856 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700857 String msg = String.format(
858 "uid %s cannot explicitly add accounts of type: %s",
859 callingUid,
860 account.type);
861 throw new SecurityException(msg);
862 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700863 /*
864 * Child users are not allowed to add accounts. Only the accounts that are
865 * shared by the parent profile can be added to child profile.
866 *
867 * TODO: Only allow accounts that were shared to be added by
868 * a limited user.
869 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700870
Fred Quintana60307342009-03-24 22:48:12 -0700871 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700872 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700873 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700874 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700875 return addAccountInternal(accounts, account, password, extras, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700876 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700877 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700878 }
879 }
880
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000881 @Override
882 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700883 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700884 int callingUid = Binder.getCallingUid();
885 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
886 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000887 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700888 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800889 final UserAccounts fromAccounts = getUserAccounts(userFrom);
890 final UserAccounts toAccounts = getUserAccounts(userTo);
891 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000892 if (response != null) {
893 Bundle result = new Bundle();
894 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
895 try {
896 response.onResult(result);
897 } catch (RemoteException e) {
898 Slog.w(TAG, "Failed to report error back to the client." + e);
899 }
900 }
901 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800902 }
903
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000904 Slog.d(TAG, "Copying account " + account.name
905 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800906 long identityToken = clearCallingIdentity();
907 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000908 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800909 false /* stripAuthTokenFromResult */, account.name,
910 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700911 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800912 protected String toDebugString(long now) {
913 return super.toDebugString(now) + ", getAccountCredentialsForClone"
914 + ", " + account.type;
915 }
916
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700917 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800918 public void run() throws RemoteException {
919 mAuthenticator.getAccountCredentialsForCloning(this, account);
920 }
921
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700922 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800923 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600924 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000925 if (result != null
926 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
927 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700928 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800929 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800930 super.onResult(result);
931 }
932 }
933 }.bind();
934 } finally {
935 restoreCallingIdentity(identityToken);
936 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800937 }
938
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800939 @Override
940 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700941 final int callingUid = Binder.getCallingUid();
942 if (Log.isLoggable(TAG, Log.VERBOSE)) {
943 String msg = String.format(
944 "accountAuthenticated( account: %s, callerUid: %s)",
945 account,
946 callingUid);
947 Log.v(TAG, msg);
948 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800949 if (account == null) {
950 throw new IllegalArgumentException("account is null");
951 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000952 int userId = UserHandle.getCallingUserId();
953 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700954 String msg = String.format(
955 "uid %s cannot notify authentication for accounts of type: %s",
956 callingUid,
957 account.type);
958 throw new SecurityException(msg);
959 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000960
Benjamin Franzb6c0ce42015-11-05 10:06:51 +0000961 if (!canUserModifyAccounts(userId, callingUid) ||
962 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800963 return false;
964 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000965
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700966 long identityToken = clearCallingIdentity();
967 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000968 UserAccounts accounts = getUserAccounts(userId);
969 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700970 } finally {
971 restoreCallingIdentity(identityToken);
972 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -0700973 }
974
975 private boolean updateLastAuthenticatedTime(Account account) {
976 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800977 synchronized (accounts.cacheLock) {
978 final ContentValues values = new ContentValues();
979 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
980 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
981 int i = db.update(
982 TABLE_ACCOUNTS,
983 values,
984 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
985 new String[] {
986 account.name, account.type
987 });
988 if (i > 0) {
989 return true;
990 }
991 }
992 return false;
993 }
994
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000995 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700996 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
997 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600998 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800999 long id = clearCallingIdentity();
1000 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001001 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001002 false /* stripAuthTokenFromResult */, account.name,
1003 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001004 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001005 protected String toDebugString(long now) {
1006 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1007 + ", " + account.type;
1008 }
1009
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001010 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001011 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001012 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001013 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001014 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -07001015 for (Account acc : getAccounts(parentUserId,
1016 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001017 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001018 mAuthenticator.addAccountFromCredentials(
1019 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001020 break;
1021 }
1022 }
1023 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001024 }
1025
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001026 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001027 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001028 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001029 // TODO: Anything to do if if succedded?
1030 // TODO: If it failed: Show error notification? Should we remove the shadow
1031 // account to avoid retries?
1032 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001033 }
1034
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001035 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001036 public void onError(int errorCode, String errorMessage) {
1037 super.onError(errorCode, errorMessage);
1038 // TODO: Show error notification to user
1039 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1040 }
1041
1042 }.bind();
1043 } finally {
1044 restoreCallingIdentity(id);
1045 }
1046 }
1047
Amith Yamasani04e0d262012-02-14 11:50:53 -08001048 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001049 Bundle extras, int callingUid) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001050 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001051 if (account == null) {
1052 return false;
1053 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001054 if (!isUserUnlocked(accounts.userId)) {
1055 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1056 + " is locked. callingUid=" + callingUid);
1057 return false;
1058 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001059 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001060 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001061 db.beginTransaction();
1062 try {
1063 long numMatches = DatabaseUtils.longForQuery(db,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001064 "select count(*) from " + CE_TABLE_ACCOUNTS
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001065 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1066 new String[]{account.name, account.type});
1067 if (numMatches > 0) {
1068 Log.w(TAG, "insertAccountIntoDatabase: " + account
1069 + ", skipping since the account already exists");
1070 return false;
1071 }
1072 ContentValues values = new ContentValues();
1073 values.put(ACCOUNTS_NAME, account.name);
1074 values.put(ACCOUNTS_TYPE, account.type);
1075 values.put(ACCOUNTS_PASSWORD, password);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001076 long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001077 if (accountId < 0) {
1078 Log.w(TAG, "insertAccountIntoDatabase: " + account
1079 + ", skipping the DB insert failed");
1080 return false;
1081 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001082 // Insert into DE table
1083 values = new ContentValues();
1084 values.put(ACCOUNTS_ID, accountId);
1085 values.put(ACCOUNTS_NAME, account.name);
1086 values.put(ACCOUNTS_TYPE, account.type);
1087 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1088 System.currentTimeMillis());
1089 if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1090 Log.w(TAG, "insertAccountIntoDatabase: " + account
1091 + ", skipping the DB insert failed");
1092 return false;
1093 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001094 if (extras != null) {
1095 for (String key : extras.keySet()) {
1096 final String value = extras.getString(key);
1097 if (insertExtraLocked(db, accountId, key, value) < 0) {
1098 Log.w(TAG, "insertAccountIntoDatabase: " + account
1099 + ", skipping since insertExtra failed for key " + key);
1100 return false;
1101 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001102 }
1103 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001104 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001105
1106 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1107 accounts, callingUid);
1108
Amith Yamasani04e0d262012-02-14 11:50:53 -08001109 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001110 } finally {
1111 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001112 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001113 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001114 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001115 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1116 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001117 }
1118 return true;
1119 }
1120
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001121 private boolean isUserUnlocked(int userId) {
1122 synchronized (mUsers) {
1123 return mUnlockedUsers.get(userId);
1124 }
1125 }
1126
Amith Yamasani5be347b2013-03-31 17:44:31 -07001127 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001128 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001129 * running, then clone the account too.
1130 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001131 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001132 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001133 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001134 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001135 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001136 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001137 addSharedAccountAsUser(account, user.id);
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001138 if (getUserManager().isUserUnlocked(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001139 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1140 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001141 }
1142 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001143 }
1144 }
1145
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001146 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -07001147 ContentValues values = new ContentValues();
1148 values.put(EXTRAS_KEY, key);
1149 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1150 values.put(EXTRAS_VALUE, value);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001151 return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
Fred Quintana60307342009-03-24 22:48:12 -07001152 }
1153
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001154 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001155 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001156 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001157 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001158 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1159 Log.v(TAG, "hasFeatures: " + account
1160 + ", response " + response
1161 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001162 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001163 + ", pid " + Binder.getCallingPid());
1164 }
Fred Quintana382601f2010-03-25 12:25:10 -07001165 if (response == null) throw new IllegalArgumentException("response is null");
1166 if (account == null) throw new IllegalArgumentException("account is null");
1167 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001168 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001169 checkReadAccountsPermitted(callingUid, account.type, userId,
1170 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001171
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001172 long identityToken = clearCallingIdentity();
1173 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001174 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001175 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001176 } finally {
1177 restoreCallingIdentity(identityToken);
1178 }
1179 }
1180
1181 private class TestFeaturesSession extends Session {
1182 private final String[] mFeatures;
1183 private final Account mAccount;
1184
Amith Yamasani04e0d262012-02-14 11:50:53 -08001185 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001186 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001187 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001188 true /* stripAuthTokenFromResult */, account.name,
1189 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001190 mFeatures = features;
1191 mAccount = account;
1192 }
1193
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001194 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001195 public void run() throws RemoteException {
1196 try {
1197 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1198 } catch (RemoteException e) {
1199 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1200 }
1201 }
1202
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001203 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001204 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001205 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001206 IAccountManagerResponse response = getResponseAndClose();
1207 if (response != null) {
1208 try {
1209 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001210 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001211 return;
1212 }
Fred Quintana56285a62010-12-02 14:20:51 -08001213 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1214 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1215 + response);
1216 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001217 final Bundle newResult = new Bundle();
1218 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1219 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1220 response.onResult(newResult);
1221 } catch (RemoteException e) {
1222 // if the caller is dead then there is no one to care about remote exceptions
1223 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1224 Log.v(TAG, "failure while notifying response", e);
1225 }
1226 }
1227 }
1228 }
1229
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001230 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001231 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001232 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001233 + ", " + mAccount
1234 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1235 }
1236 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001237
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001238 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001239 public void renameAccount(
1240 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001241 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001242 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1243 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001244 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001245 + ", pid " + Binder.getCallingPid());
1246 }
1247 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001248 int userId = UserHandle.getCallingUserId();
1249 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001250 String msg = String.format(
1251 "uid %s cannot rename accounts of type: %s",
1252 callingUid,
1253 accountToRename.type);
1254 throw new SecurityException(msg);
1255 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001256 long identityToken = clearCallingIdentity();
1257 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001258 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001259 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001260 Bundle result = new Bundle();
1261 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1262 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1263 try {
1264 response.onResult(result);
1265 } catch (RemoteException e) {
1266 Log.w(TAG, e.getMessage());
1267 }
1268 } finally {
1269 restoreCallingIdentity(identityToken);
1270 }
1271 }
1272
1273 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001274 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001275 Account resultAccount = null;
1276 /*
1277 * Cancel existing notifications. Let authenticators
1278 * re-post notifications as required. But we don't know if
1279 * the authenticators have bound their notifications to
1280 * now stale account name data.
1281 *
1282 * With a rename api, we might not need to do this anymore but it
1283 * shouldn't hurt.
1284 */
1285 cancelNotification(
1286 getSigninRequiredNotificationId(accounts, accountToRename),
1287 new UserHandle(accounts.userId));
1288 synchronized(accounts.credentialsPermissionNotificationIds) {
1289 for (Pair<Pair<Account, String>, Integer> pair:
1290 accounts.credentialsPermissionNotificationIds.keySet()) {
1291 if (accountToRename.equals(pair.first.first)) {
1292 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1293 cancelNotification(id, new UserHandle(accounts.userId));
1294 }
1295 }
1296 }
1297 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001298 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001299 db.beginTransaction();
1300 boolean isSuccessful = false;
1301 Account renamedAccount = new Account(newName, accountToRename.type);
1302 try {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001303 final long accountId = getAccountIdLocked(db, accountToRename);
1304 if (accountId >= 0) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001305 final ContentValues values = new ContentValues();
1306 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001307 final String[] argsAccountId = { String.valueOf(accountId) };
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001308 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1309 // Update NAME/PREVIOUS_NAME in DE accounts table
1310 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001311 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1312 db.setTransactionSuccessful();
1313 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001314 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1315 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001316 }
1317 } finally {
1318 db.endTransaction();
1319 if (isSuccessful) {
1320 /*
1321 * Database transaction was successful. Clean up cached
1322 * data associated with the account in the user profile.
1323 */
1324 insertAccountIntoCacheLocked(accounts, renamedAccount);
1325 /*
1326 * Extract the data and token caches before removing the
1327 * old account to preserve the user data associated with
1328 * the account.
1329 */
1330 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1331 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1332 removeAccountFromCacheLocked(accounts, accountToRename);
1333 /*
1334 * Update the cached data associated with the renamed
1335 * account.
1336 */
1337 accounts.userDataCache.put(renamedAccount, tmpData);
1338 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1339 accounts.previousNameCache.put(
1340 renamedAccount,
1341 new AtomicReference<String>(accountToRename.name));
1342 resultAccount = renamedAccount;
1343
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001344 int parentUserId = accounts.userId;
1345 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001346 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001347 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001348 * those users with which the account was shared.
1349 */
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001350 List<UserInfo> users = getUserManager().getUsers(true);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001351 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001352 if (user.isRestricted()
1353 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001354 renameSharedAccountAsUser(accountToRename, newName, user.id);
1355 }
1356 }
1357 }
1358 sendAccountsChangedBroadcast(accounts.userId);
1359 }
1360 }
1361 }
1362 return resultAccount;
1363 }
1364
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001365 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001366 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001367 return userInfo != null && userInfo.canHaveProfile();
1368 }
1369
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001370 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001371 public void removeAccount(IAccountManagerResponse response, Account account,
1372 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001373 removeAccountAsUser(
1374 response,
1375 account,
1376 expectActivityLaunch,
1377 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001378 }
1379
1380 @Override
1381 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001382 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001383 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001384 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1385 Log.v(TAG, "removeAccount: " + account
1386 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001387 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001388 + ", pid " + Binder.getCallingPid()
1389 + ", for user id " + userId);
1390 }
1391 if (response == null) throw new IllegalArgumentException("response is null");
1392 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001393 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001394 if (isCrossUser(callingUid, userId)) {
1395 throw new SecurityException(
1396 String.format(
1397 "User %s tying remove account for %s" ,
1398 UserHandle.getCallingUserId(),
1399 userId));
1400 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001401 /*
1402 * Only the system or authenticator should be allowed to remove accounts for that
1403 * authenticator. This will let users remove accounts (via Settings in the system) but not
1404 * arbitrary applications (like competing authenticators).
1405 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001406 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001407 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1408 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001409 String msg = String.format(
1410 "uid %s cannot remove accounts of type: %s",
1411 callingUid,
1412 account.type);
1413 throw new SecurityException(msg);
1414 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001415 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001416 try {
1417 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1418 "User cannot modify accounts");
1419 } catch (RemoteException re) {
1420 }
1421 return;
1422 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001423 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001424 try {
1425 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1426 "User cannot modify accounts of this type (policy).");
1427 } catch (RemoteException re) {
1428 }
1429 return;
1430 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001431 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001432 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001433 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001434 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001435 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001436 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001437 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001438 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001439 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001440 }
1441 }
1442 }
1443
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001444 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1445
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001446 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001447 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1448 } finally {
1449 restoreCallingIdentity(identityToken);
1450 }
1451 }
1452
1453 @Override
1454 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001455 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001456 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1457 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001458 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001459 + ", pid " + Binder.getCallingPid());
1460 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001461 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001462 if (account == null) {
1463 /*
1464 * Null accounts should result in returning false, as per
1465 * AccountManage.addAccountExplicitly(...) java doc.
1466 */
1467 Log.e(TAG, "account is null");
1468 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001469 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001470 String msg = String.format(
1471 "uid %s cannot explicitly add accounts of type: %s",
1472 callingUid,
1473 account.type);
1474 throw new SecurityException(msg);
1475 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001476 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001477 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001478 long identityToken = clearCallingIdentity();
1479 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001480 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001481 } finally {
1482 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001483 }
Fred Quintana60307342009-03-24 22:48:12 -07001484 }
1485
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001486 private class RemoveAccountSession extends Session {
1487 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001488 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001489 Account account, boolean expectActivityLaunch) {
1490 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001491 true /* stripAuthTokenFromResult */, account.name,
1492 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001493 mAccount = account;
1494 }
1495
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001496 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001497 protected String toDebugString(long now) {
1498 return super.toDebugString(now) + ", removeAccount"
1499 + ", account " + mAccount;
1500 }
1501
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001502 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001503 public void run() throws RemoteException {
1504 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1505 }
1506
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001507 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001508 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001509 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001510 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1511 && !result.containsKey(AccountManager.KEY_INTENT)) {
1512 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001513 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001514 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001515 }
1516 IAccountManagerResponse response = getResponseAndClose();
1517 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001518 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1519 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1520 + response);
1521 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001522 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001523 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001524 try {
1525 response.onResult(result2);
1526 } catch (RemoteException e) {
1527 // ignore
1528 }
1529 }
1530 }
1531 super.onResult(result);
1532 }
1533 }
1534
Amith Yamasani04e0d262012-02-14 11:50:53 -08001535 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001536 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001537 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001538 }
1539
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001540 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001541 // For now user is required to be unlocked. TODO: Handle both cases in the future
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001542 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001543 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001544 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001545 final long accountId = getAccountIdLocked(db, account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001546 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1547 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001548 new String[]{account.name, account.type});
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001549 // Delete from CE table
1550 db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1551 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001552 removeAccountFromCacheLocked(accounts, account);
1553 sendAccountsChangedBroadcast(accounts.userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001554
1555 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001556 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001557 long id = Binder.clearCallingIdentity();
1558 try {
1559 int parentUserId = accounts.userId;
1560 if (canHaveProfile(parentUserId)) {
1561 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001562 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001563 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001564 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001565 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001566 }
1567 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001568 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001569 } finally {
1570 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001571 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001572 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001573 }
1574
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001575 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001576 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001577 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001578 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1579 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001580 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001581 + ", pid " + Binder.getCallingPid());
1582 }
Fred Quintana382601f2010-03-25 12:25:10 -07001583 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1584 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001585 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001586 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001587 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001588 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001589 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001590 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001591 db.beginTransaction();
1592 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001593 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001594 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001595 db.setTransactionSuccessful();
1596 } finally {
1597 db.endTransaction();
1598 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001599 }
Fred Quintana60307342009-03-24 22:48:12 -07001600 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001601 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001602 }
1603 }
1604
Carlos Valdivia91979be2015-05-22 14:11:35 -07001605 private void invalidateCustomTokenLocked(
1606 UserAccounts accounts,
1607 String accountType,
1608 String authToken) {
1609 if (authToken == null || accountType == null) {
1610 return;
1611 }
1612 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001613 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001614 }
1615
Amith Yamasani04e0d262012-02-14 11:50:53 -08001616 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1617 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001618 if (authToken == null || accountType == null) {
1619 return;
1620 }
Fred Quintana33269202009-04-20 16:05:10 -07001621 Cursor cursor = db.rawQuery(
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001622 "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1623 + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1624 + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1625 + " FROM " + CE_TABLE_ACCOUNTS
1626 + " JOIN " + CE_TABLE_AUTHTOKENS
1627 + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1628 + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
1629 + " WHERE " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_AUTHTOKEN
1630 + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
Fred Quintana33269202009-04-20 16:05:10 -07001631 new String[]{authToken, accountType});
1632 try {
1633 while (cursor.moveToNext()) {
1634 long authTokenId = cursor.getLong(0);
1635 String accountName = cursor.getString(1);
1636 String authTokenType = cursor.getString(2);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001637 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001638 writeAuthTokenIntoCacheLocked(
1639 accounts,
1640 db,
1641 new Account(accountName, accountType),
1642 authTokenType,
1643 null);
Fred Quintana60307342009-03-24 22:48:12 -07001644 }
Fred Quintana33269202009-04-20 16:05:10 -07001645 } finally {
1646 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001647 }
1648 }
1649
Carlos Valdivia91979be2015-05-22 14:11:35 -07001650 private void saveCachedToken(
1651 UserAccounts accounts,
1652 Account account,
1653 String callerPkg,
1654 byte[] callerSigDigest,
1655 String tokenType,
1656 String token,
1657 long expiryMillis) {
1658
1659 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1660 return;
1661 }
1662 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001663 UserHandle.of(accounts.userId));
Carlos Valdivia91979be2015-05-22 14:11:35 -07001664 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001665 accounts.accountTokenCaches.put(
1666 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001667 }
1668 }
1669
Amith Yamasani04e0d262012-02-14 11:50:53 -08001670 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1671 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001672 if (account == null || type == null) {
1673 return false;
1674 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001675 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001676 UserHandle.of(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001677 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001678 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001679 db.beginTransaction();
1680 try {
1681 long accountId = getAccountIdLocked(db, account);
1682 if (accountId < 0) {
1683 return false;
1684 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001685 db.delete(CE_TABLE_AUTHTOKENS,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001686 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1687 new String[]{type});
1688 ContentValues values = new ContentValues();
1689 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1690 values.put(AUTHTOKENS_TYPE, type);
1691 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001692 if (db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001693 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001694 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001695 return true;
1696 }
Fred Quintana33269202009-04-20 16:05:10 -07001697 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001698 } finally {
1699 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001700 }
Fred Quintana60307342009-03-24 22:48:12 -07001701 }
1702 }
1703
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001704 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001705 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001706 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001707 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1708 Log.v(TAG, "peekAuthToken: " + account
1709 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001710 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001711 + ", pid " + Binder.getCallingPid());
1712 }
Fred Quintana382601f2010-03-25 12:25:10 -07001713 if (account == null) throw new IllegalArgumentException("account is null");
1714 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001715 int userId = UserHandle.getCallingUserId();
1716 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001717 String msg = String.format(
1718 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1719 callingUid,
1720 account.type);
1721 throw new SecurityException(msg);
1722 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001723 long identityToken = clearCallingIdentity();
1724 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001725 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001726 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001727 } finally {
1728 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001729 }
Fred Quintana60307342009-03-24 22:48:12 -07001730 }
1731
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001732 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001733 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001734 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001735 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1736 Log.v(TAG, "setAuthToken: " + account
1737 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001738 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001739 + ", pid " + Binder.getCallingPid());
1740 }
Fred Quintana382601f2010-03-25 12:25:10 -07001741 if (account == null) throw new IllegalArgumentException("account is null");
1742 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001743 int userId = UserHandle.getCallingUserId();
1744 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001745 String msg = String.format(
1746 "uid %s cannot set auth tokens associated with accounts of type: %s",
1747 callingUid,
1748 account.type);
1749 throw new SecurityException(msg);
1750 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001751 long identityToken = clearCallingIdentity();
1752 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001753 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001754 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001755 } finally {
1756 restoreCallingIdentity(identityToken);
1757 }
Fred Quintana60307342009-03-24 22:48:12 -07001758 }
1759
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001760 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001761 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001762 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001763 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1764 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001765 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001766 + ", pid " + Binder.getCallingPid());
1767 }
Fred Quintana382601f2010-03-25 12:25:10 -07001768 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001769 int userId = UserHandle.getCallingUserId();
1770 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001771 String msg = String.format(
1772 "uid %s cannot set secrets for accounts of type: %s",
1773 callingUid,
1774 account.type);
1775 throw new SecurityException(msg);
1776 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001777 long identityToken = clearCallingIdentity();
1778 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001779 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001780 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001781 } finally {
1782 restoreCallingIdentity(identityToken);
1783 }
Fred Quintana60307342009-03-24 22:48:12 -07001784 }
1785
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001786 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1787 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001788 if (account == null) {
1789 return;
1790 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001791 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001792 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001793 db.beginTransaction();
1794 try {
1795 final ContentValues values = new ContentValues();
1796 values.put(ACCOUNTS_PASSWORD, password);
1797 final long accountId = getAccountIdLocked(db, account);
1798 if (accountId >= 0) {
1799 final String[] argsAccountId = {String.valueOf(accountId)};
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001800 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1801 db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001802 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001803 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001804 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001805
1806 String action = (password == null || password.length() == 0) ?
1807 DebugDbHelper.ACTION_CLEAR_PASSWORD
1808 : DebugDbHelper.ACTION_SET_PASSWORD;
1809 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001810 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001811 } finally {
1812 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001813 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001814 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001815 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001816 }
1817
Amith Yamasani04e0d262012-02-14 11:50:53 -08001818 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001819 Log.i(TAG, "the accounts changed, sending broadcast of "
1820 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001821 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001822 }
1823
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001824 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001825 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001826 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001827 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1828 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001829 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001830 + ", pid " + Binder.getCallingPid());
1831 }
Fred Quintana382601f2010-03-25 12:25:10 -07001832 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001833 int userId = UserHandle.getCallingUserId();
1834 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001835 String msg = String.format(
1836 "uid %s cannot clear passwords for accounts of type: %s",
1837 callingUid,
1838 account.type);
1839 throw new SecurityException(msg);
1840 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001841 long identityToken = clearCallingIdentity();
1842 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001843 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001844 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001845 } finally {
1846 restoreCallingIdentity(identityToken);
1847 }
Fred Quintana60307342009-03-24 22:48:12 -07001848 }
1849
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001850 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001851 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001852 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001853 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1854 Log.v(TAG, "setUserData: " + account
1855 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001856 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001857 + ", pid " + Binder.getCallingPid());
1858 }
Fred Quintana382601f2010-03-25 12:25:10 -07001859 if (key == null) throw new IllegalArgumentException("key is null");
1860 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001861 int userId = UserHandle.getCallingUserId();
1862 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001863 String msg = String.format(
1864 "uid %s cannot set user data for accounts of type: %s",
1865 callingUid,
1866 account.type);
1867 throw new SecurityException(msg);
1868 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001869 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001870 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001871 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001872 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001873 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001874 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001875 }
1876 }
1877
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001878 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001879 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001880 if (account == null || key == null) {
1881 return;
1882 }
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001883 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001884 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001885 db.beginTransaction();
1886 try {
1887 long accountId = getAccountIdLocked(db, account);
1888 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001889 return;
1890 }
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001891 long extrasId = getExtrasIdLocked(db, accountId, key);
1892 if (extrasId < 0 ) {
1893 extrasId = insertExtraLocked(db, accountId, key, value);
1894 if (extrasId < 0) {
1895 return;
1896 }
1897 } else {
1898 ContentValues values = new ContentValues();
1899 values.put(EXTRAS_VALUE, value);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001900 if (1 != db.update(CE_TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001901 return;
1902 }
Simranjit Singh Kohlia666d742015-08-07 13:34:09 -07001903
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001904 }
1905 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
1906 db.setTransactionSuccessful();
1907 } finally {
1908 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001909 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001910 }
1911 }
1912
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001913 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001914 if (result == null) {
1915 Log.e(TAG, "the result is unexpectedly null", new Exception());
1916 }
1917 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1918 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1919 + response);
1920 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001921 try {
1922 response.onResult(result);
1923 } catch (RemoteException e) {
1924 // if the caller is dead then there is no one to care about remote
1925 // exceptions
1926 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1927 Log.v(TAG, "failure while notifying response", e);
1928 }
1929 }
1930 }
1931
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001932 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001933 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1934 final String authTokenType)
1935 throws RemoteException {
1936 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001937 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1938
Fred Quintanad9640ec2012-05-23 12:37:00 -07001939 final int callingUid = getCallingUid();
1940 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001941 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001942 throw new SecurityException("can only call from system");
1943 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001944 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001945 long identityToken = clearCallingIdentity();
1946 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001947 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001948 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1949 false /* stripAuthTokenFromResult */, null /* accountName */,
1950 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001951 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001952 protected String toDebugString(long now) {
1953 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001954 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001955 + ", authTokenType " + authTokenType;
1956 }
1957
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001958 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001959 public void run() throws RemoteException {
1960 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1961 }
1962
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001963 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001964 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001965 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001966 if (result != null) {
1967 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1968 Bundle bundle = new Bundle();
1969 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1970 super.onResult(bundle);
1971 return;
1972 } else {
1973 super.onResult(result);
1974 }
1975 }
1976 }.bind();
1977 } finally {
1978 restoreCallingIdentity(identityToken);
1979 }
1980 }
1981
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001982 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07001983 public void getAuthToken(
1984 IAccountManagerResponse response,
1985 final Account account,
1986 final String authTokenType,
1987 final boolean notifyOnAuthFailure,
1988 final boolean expectActivityLaunch,
1989 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001990 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08001991 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1992 Log.v(TAG, "getAuthToken: " + account
1993 + ", response " + response
1994 + ", authTokenType " + authTokenType
1995 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1996 + ", expectActivityLaunch " + expectActivityLaunch
1997 + ", caller's uid " + Binder.getCallingUid()
1998 + ", pid " + Binder.getCallingPid());
1999 }
Fred Quintana382601f2010-03-25 12:25:10 -07002000 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002001 try {
2002 if (account == null) {
2003 Slog.w(TAG, "getAuthToken called with null account");
2004 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2005 return;
2006 }
2007 if (authTokenType == null) {
2008 Slog.w(TAG, "getAuthToken called with null authTokenType");
2009 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2010 return;
2011 }
2012 } catch (RemoteException e) {
2013 Slog.w(TAG, "Failed to report error back to the client." + e);
2014 return;
2015 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002016 int userId = UserHandle.getCallingUserId();
2017 long ident = Binder.clearCallingIdentity();
2018 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002019 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002020 try {
2021 accounts = getUserAccounts(userId);
2022 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2023 AuthenticatorDescription.newKey(account.type), accounts.userId);
2024 } finally {
2025 Binder.restoreCallingIdentity(ident);
2026 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002027
Costin Manolachea40c6302010-12-13 14:50:45 -08002028 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002029 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002030
2031 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002032 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002033 final boolean permissionGranted =
2034 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002035
Carlos Valdivia91979be2015-05-22 14:11:35 -07002036 // Get the calling package. We will use it for the purpose of caching.
2037 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002038 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002039 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002040 try {
2041 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2042 } finally {
2043 Binder.restoreCallingIdentity(ident);
2044 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002045 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2046 String msg = String.format(
2047 "Uid %s is attempting to illegally masquerade as package %s!",
2048 callerUid,
2049 callerPkg);
2050 throw new SecurityException(msg);
2051 }
2052
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002053 // let authenticator know the identity of the caller
2054 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2055 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002056
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002057 if (notifyOnAuthFailure) {
2058 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002059 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002060
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002061 long identityToken = clearCallingIdentity();
2062 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002063 // Distill the caller's package signatures into a single digest.
2064 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2065
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002066 // if the caller has permission, do the peek. otherwise go the more expensive
2067 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002068 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002069 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002070 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002071 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002072 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2073 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2074 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002075 onResult(response, result);
2076 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002077 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002078 }
2079
Carlos Valdivia91979be2015-05-22 14:11:35 -07002080 if (customTokens) {
2081 /*
2082 * Look up tokens in the new cache only if the loginOptions don't have parameters
2083 * outside of those expected to be injected by the AccountManager, e.g.
2084 * ANDORID_PACKAGE_NAME.
2085 */
2086 String token = readCachedTokenInternal(
2087 accounts,
2088 account,
2089 authTokenType,
2090 callerPkg,
2091 callerPkgSigDigest);
2092 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002093 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2094 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2095 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002096 Bundle result = new Bundle();
2097 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2098 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2099 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2100 onResult(response, result);
2101 return;
2102 }
2103 }
2104
Amith Yamasani04e0d262012-02-14 11:50:53 -08002105 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002106 false /* stripAuthTokenFromResult */, account.name,
2107 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002108 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002109 protected String toDebugString(long now) {
2110 if (loginOptions != null) loginOptions.keySet();
2111 return super.toDebugString(now) + ", getAuthToken"
2112 + ", " + account
2113 + ", authTokenType " + authTokenType
2114 + ", loginOptions " + loginOptions
2115 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2116 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002117
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002118 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002119 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002120 // If the caller doesn't have permission then create and return the
2121 // "grant permission" intent instead of the "getAuthToken" intent.
2122 if (!permissionGranted) {
2123 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2124 } else {
2125 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2126 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002127 }
2128
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002129 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002130 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002131 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002132 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002133 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002134 Intent intent = newGrantCredentialsPermissionIntent(
2135 account,
2136 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002137 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002138 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002139 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002140 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002141 onResult(bundle);
2142 return;
2143 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002144 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002145 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002146 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2147 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002148 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002149 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002150 "the type and name should not be empty");
2151 return;
2152 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002153 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002154 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002155 saveAuthTokenToDatabase(
2156 mAccounts,
2157 resultAccount,
2158 authTokenType,
2159 authToken);
2160 }
2161 long expiryMillis = result.getLong(
2162 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2163 if (customTokens
2164 && expiryMillis > System.currentTimeMillis()) {
2165 saveCachedToken(
2166 mAccounts,
2167 account,
2168 callerPkg,
2169 callerPkgSigDigest,
2170 authTokenType,
2171 authToken,
2172 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002173 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002174 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002175
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002176 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002177 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002178 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002179 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002180 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002181 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002182 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002183 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002184 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002185 }.bind();
2186 } finally {
2187 restoreCallingIdentity(identityToken);
2188 }
Fred Quintana60307342009-03-24 22:48:12 -07002189 }
2190
Carlos Valdivia91979be2015-05-22 14:11:35 -07002191 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2192 MessageDigest digester;
2193 try {
2194 digester = MessageDigest.getInstance("SHA-256");
2195 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2196 callerPkg, PackageManager.GET_SIGNATURES);
2197 for (Signature sig : pkgInfo.signatures) {
2198 digester.update(sig.toByteArray());
2199 }
2200 } catch (NoSuchAlgorithmException x) {
2201 Log.wtf(TAG, "SHA-256 should be available", x);
2202 digester = null;
2203 } catch (NameNotFoundException e) {
2204 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2205 digester = null;
2206 }
2207 return (digester == null) ? null : digester.digest();
2208 }
2209
Dianne Hackborn41203752012-08-31 14:05:51 -07002210 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2211 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002212 int uid = intent.getIntExtra(
2213 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2214 String authTokenType = intent.getStringExtra(
2215 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002216 final String titleAndSubtitle =
2217 mContext.getString(R.string.permission_request_notification_with_subtitle,
2218 account.name);
2219 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002220 String title = titleAndSubtitle;
2221 String subtitle = "";
2222 if (index > 0) {
2223 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002224 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002225 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002226 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002227 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002228 Notification n = new Notification.Builder(contextForUser)
2229 .setSmallIcon(android.R.drawable.stat_sys_warning)
2230 .setWhen(0)
2231 .setColor(contextForUser.getColor(
2232 com.android.internal.R.color.system_notification_accent_color))
2233 .setContentTitle(title)
2234 .setContentText(subtitle)
2235 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2236 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2237 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002238 installNotification(getCredentialPermissionNotificationId(
2239 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002240 }
2241
Costin Manolache5f383ad92010-12-02 16:44:46 -08002242 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002243 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002244
2245 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002246 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002247 // Since it was set in Eclair+ we can't change it without breaking apps using
2248 // the intent from a non-Activity context.
2249 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002250 intent.addCategory(
2251 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002252
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002253 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002254 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2255 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002256 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002257
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002258 return intent;
2259 }
2260
2261 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2262 int uid) {
2263 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002264 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002265 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002266 final Pair<Pair<Account, String>, Integer> key =
2267 new Pair<Pair<Account, String>, Integer>(
2268 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002269 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002270 if (id == null) {
2271 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002272 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002273 }
2274 }
2275 return id;
2276 }
2277
Amith Yamasani04e0d262012-02-14 11:50:53 -08002278 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002279 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002280 synchronized (accounts.signinRequiredNotificationIds) {
2281 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002282 if (id == null) {
2283 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002284 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002285 }
2286 }
2287 return id;
2288 }
2289
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002290 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002291 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002292 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002293 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002294 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002295 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2296 Log.v(TAG, "addAccount: accountType " + accountType
2297 + ", response " + response
2298 + ", authTokenType " + authTokenType
2299 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2300 + ", expectActivityLaunch " + expectActivityLaunch
2301 + ", caller's uid " + Binder.getCallingUid()
2302 + ", pid " + Binder.getCallingPid());
2303 }
Fred Quintana382601f2010-03-25 12:25:10 -07002304 if (response == null) throw new IllegalArgumentException("response is null");
2305 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002306
Amith Yamasani71e6c692013-03-24 17:39:28 -07002307 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002308 final int uid = Binder.getCallingUid();
2309 final int userId = UserHandle.getUserId(uid);
2310 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002311 try {
2312 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2313 "User is not allowed to add an account!");
2314 } catch (RemoteException re) {
2315 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002316 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002317 return;
2318 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002319 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002320 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002321 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2322 "User cannot modify accounts of this type (policy).");
2323 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002324 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002325 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2326 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002327 return;
2328 }
2329
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002330 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002331 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2332 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2333 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2334
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002335 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002336 long identityToken = clearCallingIdentity();
2337 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002338 UserAccounts accounts = getUserAccounts(usrId);
2339 logRecordWithUid(
2340 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002341 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002342 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002343 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002344 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002345 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002346 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002347 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002348 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002349
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002350 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002351 protected String toDebugString(long now) {
2352 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002353 + ", accountType " + accountType
2354 + ", requiredFeatures "
2355 + (requiredFeatures != null
2356 ? TextUtils.join(",", requiredFeatures)
2357 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002358 }
2359 }.bind();
2360 } finally {
2361 restoreCallingIdentity(identityToken);
2362 }
Fred Quintana60307342009-03-24 22:48:12 -07002363 }
2364
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002365 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002366 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2367 final String authTokenType, final String[] requiredFeatures,
2368 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002369 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002370 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002371 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2372 Log.v(TAG, "addAccount: accountType " + accountType
2373 + ", response " + response
2374 + ", authTokenType " + authTokenType
2375 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2376 + ", expectActivityLaunch " + expectActivityLaunch
2377 + ", caller's uid " + Binder.getCallingUid()
2378 + ", pid " + Binder.getCallingPid()
2379 + ", for user id " + userId);
2380 }
2381 if (response == null) throw new IllegalArgumentException("response is null");
2382 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002383 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002384 if (isCrossUser(callingUid, userId)) {
2385 throw new SecurityException(
2386 String.format(
2387 "User %s trying to add account for %s" ,
2388 UserHandle.getCallingUserId(),
2389 userId));
2390 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002391
2392 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002393 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002394 try {
2395 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2396 "User is not allowed to add an account!");
2397 } catch (RemoteException re) {
2398 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002399 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002400 return;
2401 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002402 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002403 try {
2404 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2405 "User cannot modify accounts of this type (policy).");
2406 } catch (RemoteException re) {
2407 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002408 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2409 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002410 return;
2411 }
2412
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002413 final int pid = Binder.getCallingPid();
2414 final int uid = Binder.getCallingUid();
2415 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2416 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2417 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2418
2419 long identityToken = clearCallingIdentity();
2420 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002421 UserAccounts accounts = getUserAccounts(userId);
2422 logRecordWithUid(
2423 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002424 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002425 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002426 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002427 @Override
2428 public void run() throws RemoteException {
2429 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2430 options);
2431 }
2432
2433 @Override
2434 protected String toDebugString(long now) {
2435 return super.toDebugString(now) + ", addAccount"
2436 + ", accountType " + accountType
2437 + ", requiredFeatures "
2438 + (requiredFeatures != null
2439 ? TextUtils.join(",", requiredFeatures)
2440 : null);
2441 }
2442 }.bind();
2443 } finally {
2444 restoreCallingIdentity(identityToken);
2445 }
2446 }
2447
Sandra Kwan78812282015-11-04 11:19:47 -08002448 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002449 public void startAddAccountSession(
2450 final IAccountManagerResponse response,
2451 final String accountType,
2452 final String authTokenType,
2453 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002454 final boolean expectActivityLaunch,
2455 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002456 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002457 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2458 Log.v(TAG,
2459 "startAddAccountSession: accountType " + accountType
2460 + ", response " + response
2461 + ", authTokenType " + authTokenType
2462 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2463 + ", expectActivityLaunch " + expectActivityLaunch
2464 + ", caller's uid " + Binder.getCallingUid()
2465 + ", pid " + Binder.getCallingPid());
2466 }
2467 if (response == null) {
2468 throw new IllegalArgumentException("response is null");
2469 }
2470 if (accountType == null) {
2471 throw new IllegalArgumentException("accountType is null");
2472 }
2473
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002474 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002475 // Only allow system to start session
2476 if (!isSystemUid(uid)) {
2477 String msg = String.format(
2478 "uid %s cannot stat add account session.",
2479 uid);
2480 throw new SecurityException(msg);
2481 }
2482
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002483 final int userId = UserHandle.getUserId(uid);
2484 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002485 try {
2486 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2487 "User is not allowed to add an account!");
2488 } catch (RemoteException re) {
2489 }
2490 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2491 return;
2492 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002493 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002494 try {
2495 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2496 "User cannot modify accounts of this type (policy).");
2497 } catch (RemoteException re) {
2498 }
2499 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2500 userId);
2501 return;
2502 }
2503
2504 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08002505 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2506 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2507 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2508
2509 int usrId = UserHandle.getCallingUserId();
2510 long identityToken = clearCallingIdentity();
2511 try {
2512 UserAccounts accounts = getUserAccounts(usrId);
2513 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2514 TABLE_ACCOUNTS, uid);
2515 new StartAccountSession(accounts, response, accountType, expectActivityLaunch,
2516 null /* accountName */, false /* authDetailsRequired */,
2517 true /* updateLastAuthenticationTime */) {
2518 @Override
2519 public void run() throws RemoteException {
2520 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2521 requiredFeatures, options);
2522 }
2523
2524 @Override
2525 protected String toDebugString(long now) {
2526 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2527 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2528 + accountType + ", requiredFeatures "
2529 + (requiredFeatures != null ? requiredFeaturesStr : null);
2530 }
2531 }.bind();
2532 } finally {
2533 restoreCallingIdentity(identityToken);
2534 }
2535 }
2536
2537 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2538 private abstract class StartAccountSession extends Session {
2539
2540 public StartAccountSession(UserAccounts accounts, IAccountManagerResponse response,
2541 String accountType, boolean expectActivityLaunch, String accountName,
2542 boolean authDetailsRequired, boolean updateLastAuthenticationTime) {
2543 super(accounts, response, accountType, expectActivityLaunch,
2544 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2545 updateLastAuthenticationTime);
2546 }
2547
2548 @Override
2549 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002550 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08002551 mNumResults++;
2552 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08002553 if (result != null
2554 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08002555 checkKeyIntent(
2556 Binder.getCallingUid(),
2557 intent);
Sandra Kwan78812282015-11-04 11:19:47 -08002558 }
Sandra Kwan78812282015-11-04 11:19:47 -08002559 IAccountManagerResponse response;
2560 if (mExpectActivityLaunch && result != null
2561 && result.containsKey(AccountManager.KEY_INTENT)) {
2562 response = mResponse;
2563 } else {
2564 response = getResponseAndClose();
2565 }
2566 if (response == null) {
2567 return;
2568 }
2569 if (result == null) {
2570 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2571 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2572 + response);
2573 }
2574 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2575 "null bundle returned");
2576 return;
2577 }
2578
2579 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2580 // All AccountManager error codes are greater
2581 // than 0
2582 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2583 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2584 return;
2585 }
2586
2587 // Strip auth token from result.
2588 result.remove(AccountManager.KEY_AUTHTOKEN);
2589
2590 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2591 Log.v(TAG,
2592 getClass().getSimpleName() + " calling onResult() on response " + response);
2593 }
2594
2595 // Get the session bundle created by authenticator. The
2596 // bundle contains data necessary for finishing the session
2597 // later. The session bundle will be encrypted here and
2598 // decrypted later when trying to finish the session.
2599 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2600 if (sessionBundle != null) {
2601 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2602 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08002603 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002604 Log.w(TAG, "Account type in session bundle doesn't match request.");
2605 }
2606 // Add accountType info to session bundle. This will
2607 // override any value set by authenticator.
2608 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2609
2610 // Encrypt session bundle before returning to caller.
2611 try {
2612 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2613 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2614 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2615 } catch (GeneralSecurityException e) {
2616 if (Log.isLoggable(TAG, Log.DEBUG)) {
2617 Log.v(TAG, "Failed to encrypt session bundle!", e);
2618 }
2619 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2620 "failed to encrypt session bundle");
2621 return;
2622 }
2623 }
2624
2625 sendResponse(response, result);
2626 }
2627 }
2628
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002629 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08002630 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002631 @NonNull Bundle sessionBundle,
2632 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002633 Bundle appInfo,
2634 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002635 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08002636 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002637 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2638 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002639 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002640 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08002641 + ", caller's uid " + callingUid
2642 + ", caller's user id " + UserHandle.getCallingUserId()
2643 + ", pid " + Binder.getCallingPid()
2644 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002645 }
2646 if (response == null) {
2647 throw new IllegalArgumentException("response is null");
2648 }
2649
2650 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2651 // Account type is added to it before encryption.
2652 if (sessionBundle == null || sessionBundle.size() == 0) {
2653 throw new IllegalArgumentException("sessionBundle is empty");
2654 }
2655
Sandra Kwan0b84b452016-01-20 15:25:42 -08002656 // Only allow the system process to finish session for other users
2657 if (isCrossUser(callingUid, userId)) {
2658 throw new SecurityException(
2659 String.format(
2660 "User %s trying to finish session for %s without cross user permission",
2661 UserHandle.getCallingUserId(),
2662 userId));
2663 }
2664
Sandra Kwana578d112015-12-16 16:01:43 -08002665 // Only allow system to finish session
Sandra Kwan0b84b452016-01-20 15:25:42 -08002666 if (!isSystemUid(callingUid)) {
Sandra Kwana578d112015-12-16 16:01:43 -08002667 String msg = String.format(
Sandra Kwan0b84b452016-01-20 15:25:42 -08002668 "uid %s cannot finish session because it's not system uid.",
2669 callingUid);
Sandra Kwana578d112015-12-16 16:01:43 -08002670 throw new SecurityException(msg);
2671 }
2672
Sandra Kwan0b84b452016-01-20 15:25:42 -08002673 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002674 sendErrorResponse(response,
2675 AccountManager.ERROR_CODE_USER_RESTRICTED,
2676 "User is not allowed to add an account!");
2677 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2678 return;
2679 }
2680
2681 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002682 final Bundle decryptedBundle;
2683 final String accountType;
2684 // First decrypt session bundle to get account type for checking permission.
2685 try {
2686 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2687 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2688 if (decryptedBundle == null) {
2689 sendErrorResponse(
2690 response,
2691 AccountManager.ERROR_CODE_BAD_REQUEST,
2692 "failed to decrypt session bundle");
2693 return;
2694 }
2695 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2696 // Account type cannot be null. This should not happen if session bundle was created
2697 // properly by #StartAccountSession.
2698 if (TextUtils.isEmpty(accountType)) {
2699 sendErrorResponse(
2700 response,
2701 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2702 "accountType is empty");
2703 return;
2704 }
2705
2706 // If by any chances, decryptedBundle contains colliding keys with
2707 // system info
2708 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2709 // update credentials flow, we should replace with the new values of the current call.
2710 if (appInfo != null) {
2711 decryptedBundle.putAll(appInfo);
2712 }
2713
2714 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08002715 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002716 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2717 } catch (GeneralSecurityException e) {
2718 if (Log.isLoggable(TAG, Log.DEBUG)) {
2719 Log.v(TAG, "Failed to decrypt session bundle!", e);
2720 }
2721 sendErrorResponse(
2722 response,
2723 AccountManager.ERROR_CODE_BAD_REQUEST,
2724 "failed to decrypt session bundle");
2725 return;
2726 }
2727
Sandra Kwan0b84b452016-01-20 15:25:42 -08002728 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002729 sendErrorResponse(
2730 response,
2731 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2732 "User cannot modify accounts of this type (policy).");
2733 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2734 userId);
2735 return;
2736 }
2737
2738 long identityToken = clearCallingIdentity();
2739 try {
2740 UserAccounts accounts = getUserAccounts(userId);
2741 logRecordWithUid(
2742 accounts,
2743 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2744 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002745 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002746 new Session(
2747 accounts,
2748 response,
2749 accountType,
2750 expectActivityLaunch,
2751 true /* stripAuthTokenFromResult */,
2752 null /* accountName */,
2753 false /* authDetailsRequired */,
2754 true /* updateLastAuthenticationTime */) {
2755 @Override
2756 public void run() throws RemoteException {
2757 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2758 }
2759
2760 @Override
2761 protected String toDebugString(long now) {
2762 return super.toDebugString(now)
2763 + ", finishSession"
2764 + ", accountType " + accountType;
2765 }
2766 }.bind();
2767 } finally {
2768 restoreCallingIdentity(identityToken);
2769 }
2770 }
2771
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002772 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002773 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2774 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2775 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2776 long identityToken = clearCallingIdentity();
2777 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002778 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002779 } finally {
2780 restoreCallingIdentity(identityToken);
2781 }
2782 }
2783
2784 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002785 public void confirmCredentialsAsUser(
2786 IAccountManagerResponse response,
2787 final Account account,
2788 final Bundle options,
2789 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002790 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002791 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002792 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002793 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2794 Log.v(TAG, "confirmCredentials: " + account
2795 + ", response " + response
2796 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002797 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002798 + ", pid " + Binder.getCallingPid());
2799 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002800 // Only allow the system process to read accounts of other users
2801 if (isCrossUser(callingUid, userId)) {
2802 throw new SecurityException(
2803 String.format(
2804 "User %s trying to confirm account credentials for %s" ,
2805 UserHandle.getCallingUserId(),
2806 userId));
2807 }
Fred Quintana382601f2010-03-25 12:25:10 -07002808 if (response == null) throw new IllegalArgumentException("response is null");
2809 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002810 long identityToken = clearCallingIdentity();
2811 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002812 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002813 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002814 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002815 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002816 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002817 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002818 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002819 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002820 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002821 protected String toDebugString(long now) {
2822 return super.toDebugString(now) + ", confirmCredentials"
2823 + ", " + account;
2824 }
2825 }.bind();
2826 } finally {
2827 restoreCallingIdentity(identityToken);
2828 }
Fred Quintana60307342009-03-24 22:48:12 -07002829 }
2830
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002831 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002832 public void updateCredentials(IAccountManagerResponse response, final Account account,
2833 final String authTokenType, final boolean expectActivityLaunch,
2834 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002835 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002836 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2837 Log.v(TAG, "updateCredentials: " + account
2838 + ", response " + response
2839 + ", authTokenType " + authTokenType
2840 + ", expectActivityLaunch " + expectActivityLaunch
2841 + ", caller's uid " + Binder.getCallingUid()
2842 + ", pid " + Binder.getCallingPid());
2843 }
Fred Quintana382601f2010-03-25 12:25:10 -07002844 if (response == null) throw new IllegalArgumentException("response is null");
2845 if (account == null) throw new IllegalArgumentException("account is null");
2846 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002847 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002848 long identityToken = clearCallingIdentity();
2849 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002850 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002851 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002852 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002853 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002854 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002855 public void run() throws RemoteException {
2856 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2857 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002858 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002859 protected String toDebugString(long now) {
2860 if (loginOptions != null) loginOptions.keySet();
2861 return super.toDebugString(now) + ", updateCredentials"
2862 + ", " + account
2863 + ", authTokenType " + authTokenType
2864 + ", loginOptions " + loginOptions;
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
Sandra Kwane68c37e2015-11-12 17:11:49 -08002873 public void startUpdateCredentialsSession(
2874 IAccountManagerResponse response,
2875 final Account account,
2876 final String authTokenType,
2877 final boolean expectActivityLaunch,
2878 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002879 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08002880 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2881 Log.v(TAG,
2882 "startUpdateCredentialsSession: " + account + ", response " + response
2883 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
2884 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
2885 + ", pid " + Binder.getCallingPid());
2886 }
2887 if (response == null) {
2888 throw new IllegalArgumentException("response is null");
2889 }
2890 if (account == null) {
2891 throw new IllegalArgumentException("account is null");
2892 }
Sandra Kwana578d112015-12-16 16:01:43 -08002893
2894 final int uid = Binder.getCallingUid();
2895 // Only allow system to start session
2896 if (!isSystemUid(uid)) {
2897 String msg = String.format(
2898 "uid %s cannot start update credentials session.",
2899 uid);
2900 throw new SecurityException(msg);
2901 }
2902
Sandra Kwane68c37e2015-11-12 17:11:49 -08002903 int userId = UserHandle.getCallingUserId();
2904 long identityToken = clearCallingIdentity();
2905 try {
2906 UserAccounts accounts = getUserAccounts(userId);
2907 new StartAccountSession(
2908 accounts,
2909 response,
2910 account.type,
2911 expectActivityLaunch,
2912 account.name,
2913 false /* authDetailsRequired */,
2914 true /* updateLastCredentialTime */) {
2915 @Override
2916 public void run() throws RemoteException {
2917 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
2918 loginOptions);
2919 }
2920
2921 @Override
2922 protected String toDebugString(long now) {
2923 if (loginOptions != null)
2924 loginOptions.keySet();
2925 return super.toDebugString(now)
2926 + ", startUpdateCredentialsSession"
2927 + ", " + account
2928 + ", authTokenType " + authTokenType
2929 + ", loginOptions " + loginOptions;
2930 }
2931 }.bind();
2932 } finally {
2933 restoreCallingIdentity(identityToken);
2934 }
2935 }
2936
2937 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08002938 public void isCredentialsUpdateSuggested(
2939 IAccountManagerResponse response,
2940 final Account account,
2941 final String statusToken) {
2942 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2943 Log.v(TAG,
2944 "isCredentialsUpdateSuggested: " + account + ", response " + response
2945 + ", caller's uid " + Binder.getCallingUid()
2946 + ", pid " + Binder.getCallingPid());
2947 }
2948 if (response == null) {
2949 throw new IllegalArgumentException("response is null");
2950 }
2951 if (account == null) {
2952 throw new IllegalArgumentException("account is null");
2953 }
2954 if (TextUtils.isEmpty(statusToken)) {
2955 throw new IllegalArgumentException("status token is empty");
2956 }
2957
2958 int uid = Binder.getCallingUid();
2959 // Only allow system to start session
2960 if (!isSystemUid(uid)) {
2961 String msg = String.format(
2962 "uid %s cannot stat add account session.",
2963 uid);
2964 throw new SecurityException(msg);
2965 }
2966
2967 int usrId = UserHandle.getCallingUserId();
2968 long identityToken = clearCallingIdentity();
2969 try {
2970 UserAccounts accounts = getUserAccounts(usrId);
2971 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
2972 false /* stripAuthTokenFromResult */, account.name,
2973 false /* authDetailsRequired */) {
2974 @Override
2975 protected String toDebugString(long now) {
2976 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
2977 + ", " + account;
2978 }
2979
2980 @Override
2981 public void run() throws RemoteException {
2982 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
2983 }
2984
2985 @Override
2986 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002987 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08002988 IAccountManagerResponse response = getResponseAndClose();
2989 if (response == null) {
2990 return;
2991 }
2992
2993 if (result == null) {
2994 sendErrorResponse(
2995 response,
2996 AccountManager.ERROR_CODE_INVALID_RESPONSE,
2997 "null bundle");
2998 return;
2999 }
3000
3001 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3002 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3003 + response);
3004 }
3005 // Check to see if an error occurred. We know if an error occurred because all
3006 // error codes are greater than 0.
3007 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3008 sendErrorResponse(response,
3009 result.getInt(AccountManager.KEY_ERROR_CODE),
3010 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3011 return;
3012 }
3013 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3014 sendErrorResponse(
3015 response,
3016 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3017 "no result in response");
3018 return;
3019 }
3020 final Bundle newResult = new Bundle();
3021 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3022 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3023 sendResponse(response, newResult);
3024 }
3025 }.bind();
3026 } finally {
3027 restoreCallingIdentity(identityToken);
3028 }
3029 }
3030
3031 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003032 public void editProperties(IAccountManagerResponse response, final String accountType,
3033 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003034 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003035 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3036 Log.v(TAG, "editProperties: accountType " + accountType
3037 + ", response " + response
3038 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003039 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003040 + ", pid " + Binder.getCallingPid());
3041 }
Fred Quintana382601f2010-03-25 12:25:10 -07003042 if (response == null) throw new IllegalArgumentException("response is null");
3043 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003044 int userId = UserHandle.getCallingUserId();
3045 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003046 String msg = String.format(
3047 "uid %s cannot edit authenticator properites for account type: %s",
3048 callingUid,
3049 accountType);
3050 throw new SecurityException(msg);
3051 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003052 long identityToken = clearCallingIdentity();
3053 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003054 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003055 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003056 true /* stripAuthTokenFromResult */, null /* accountName */,
3057 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003058 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003059 public void run() throws RemoteException {
3060 mAuthenticator.editProperties(this, mAccountType);
3061 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003062 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003063 protected String toDebugString(long now) {
3064 return super.toDebugString(now) + ", editProperties"
3065 + ", accountType " + accountType;
3066 }
3067 }.bind();
3068 } finally {
3069 restoreCallingIdentity(identityToken);
3070 }
Fred Quintana60307342009-03-24 22:48:12 -07003071 }
3072
Amith Yamasani12747872015-12-07 14:19:49 -08003073 @Override
3074 public boolean someUserHasAccount(@NonNull final Account account) {
3075 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3076 throw new SecurityException("Only system can check for accounts across users");
3077 }
3078 final long token = Binder.clearCallingIdentity();
3079 try {
3080 AccountAndUser[] allAccounts = getAllAccounts();
3081 for (int i = allAccounts.length - 1; i >= 0; i--) {
3082 if (allAccounts[i].account.equals(account)) {
3083 return true;
3084 }
3085 }
3086 return false;
3087 } finally {
3088 Binder.restoreCallingIdentity(token);
3089 }
3090 }
3091
Fred Quintana33269202009-04-20 16:05:10 -07003092 private class GetAccountsByTypeAndFeatureSession extends Session {
3093 private final String[] mFeatures;
3094 private volatile Account[] mAccountsOfType = null;
3095 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3096 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003097 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003098
Amith Yamasani04e0d262012-02-14 11:50:53 -08003099 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003100 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003101 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003102 true /* stripAuthTokenFromResult */, null /* accountName */,
3103 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003104 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003105 mFeatures = features;
3106 }
3107
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003108 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003109 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003110 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003111 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3112 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003113 }
Fred Quintana33269202009-04-20 16:05:10 -07003114 // check whether each account matches the requested features
3115 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
3116 mCurrentAccount = 0;
3117
3118 checkAccount();
3119 }
3120
3121 public void checkAccount() {
3122 if (mCurrentAccount >= mAccountsOfType.length) {
3123 sendResult();
3124 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003125 }
Fred Quintana33269202009-04-20 16:05:10 -07003126
Fred Quintana29e94b82010-03-10 12:11:51 -08003127 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3128 if (accountAuthenticator == null) {
3129 // It is possible that the authenticator has died, which is indicated by
3130 // mAuthenticator being set to null. If this happens then just abort.
3131 // There is no need to send back a result or error in this case since
3132 // that already happened when mAuthenticator was cleared.
3133 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3134 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3135 + " connected to the authenticator, " + toDebugString());
3136 }
3137 return;
3138 }
Fred Quintana33269202009-04-20 16:05:10 -07003139 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003140 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003141 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003142 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003143 }
3144 }
3145
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003146 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003147 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003148 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003149 mNumResults++;
3150 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003151 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003152 return;
3153 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003154 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003155 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3156 }
3157 mCurrentAccount++;
3158 checkAccount();
3159 }
3160
3161 public void sendResult() {
3162 IAccountManagerResponse response = getResponseAndClose();
3163 if (response != null) {
3164 try {
3165 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3166 for (int i = 0; i < accounts.length; i++) {
3167 accounts[i] = mAccountsWithFeatures.get(i);
3168 }
Fred Quintana56285a62010-12-02 14:20:51 -08003169 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3170 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3171 + response);
3172 }
Fred Quintana33269202009-04-20 16:05:10 -07003173 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003174 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003175 response.onResult(result);
3176 } catch (RemoteException e) {
3177 // if the caller is dead then there is no one to care about remote exceptions
3178 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3179 Log.v(TAG, "failure while notifying response", e);
3180 }
3181 }
3182 }
3183 }
3184
3185
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003186 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003187 protected String toDebugString(long now) {
3188 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3189 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3190 }
3191 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003192
Amith Yamasani04e0d262012-02-14 11:50:53 -08003193 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003194 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003195 * @hide
3196 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003197 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003198 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003199 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003200 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3201 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003202 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003203 return new Account[0];
3204 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003205 long identityToken = clearCallingIdentity();
3206 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003207 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003208 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003209 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003210 callingUid,
3211 null, // packageName
3212 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003213 } finally {
3214 restoreCallingIdentity(identityToken);
3215 }
3216 }
3217
Amith Yamasanif29f2362012-04-05 18:29:52 -07003218 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003219 * Returns accounts for all running users.
3220 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003221 * @hide
3222 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003223 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003224 public AccountAndUser[] getRunningAccounts() {
3225 final int[] runningUserIds;
3226 try {
3227 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3228 } catch (RemoteException e) {
3229 // Running in system_server; should never happen
3230 throw new RuntimeException(e);
3231 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003232 return getAccounts(runningUserIds);
3233 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003234
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003235 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003236 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003237 public AccountAndUser[] getAllAccounts() {
3238 final List<UserInfo> users = getUserManager().getUsers();
3239 final int[] userIds = new int[users.size()];
3240 for (int i = 0; i < userIds.length; i++) {
3241 userIds[i] = users.get(i).id;
3242 }
3243 return getAccounts(userIds);
3244 }
3245
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003246 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003247 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003248 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003249 for (int userId : userIds) {
3250 UserAccounts userAccounts = getUserAccounts(userId);
3251 if (userAccounts == null) continue;
3252 synchronized (userAccounts.cacheLock) {
3253 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3254 Binder.getCallingUid(), null);
3255 for (int a = 0; a < accounts.length; a++) {
3256 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003257 }
3258 }
3259 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003260
3261 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3262 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003263 }
3264
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003265 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003266 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003267 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3268 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003269 }
3270
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003271 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003272 private Account[] getAccountsAsUser(
3273 String type,
3274 int userId,
3275 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003276 int packageUid,
3277 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003278 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003279 // Only allow the system process to read accounts of other users
3280 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003281 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003282 && mContext.checkCallingOrSelfPermission(
3283 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3284 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003285 throw new SecurityException("User " + UserHandle.getCallingUserId()
3286 + " trying to get account for " + userId);
3287 }
3288
Fred Quintana56285a62010-12-02 14:20:51 -08003289 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3290 Log.v(TAG, "getAccounts: accountType " + type
3291 + ", caller's uid " + Binder.getCallingUid()
3292 + ", pid " + Binder.getCallingPid());
3293 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003294 // If the original calling app was using the framework account chooser activity, we'll
3295 // be passed in the original caller's uid here, which is what should be used for filtering.
3296 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3297 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003298 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003299 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003300
Svetoslavf3f02ac2015-09-08 14:36:35 -07003301 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3302 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003303 if (visibleAccountTypes.isEmpty()
3304 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003305 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003306 } else if (visibleAccountTypes.contains(type)) {
3307 // Prune the list down to just the requested type.
3308 visibleAccountTypes = new ArrayList<>();
3309 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003310 } // else aggregate all the visible accounts (it won't matter if the
3311 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003312
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003313 long identityToken = clearCallingIdentity();
3314 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003315 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003316 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003317 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003318 callingUid,
3319 callingPackage,
3320 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003321 } finally {
3322 restoreCallingIdentity(identityToken);
3323 }
3324 }
3325
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003326 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003327 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003328 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003329 int callingUid,
3330 String callingPackage,
3331 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003332 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003333 ArrayList<Account> visibleAccounts = new ArrayList<>();
3334 for (String visibleType : visibleAccountTypes) {
3335 Account[] accountsForType = getAccountsFromCacheLocked(
3336 userAccounts, visibleType, callingUid, callingPackage);
3337 if (accountsForType != null) {
3338 visibleAccounts.addAll(Arrays.asList(accountsForType));
3339 }
3340 }
3341 Account[] result = new Account[visibleAccounts.size()];
3342 for (int i = 0; i < visibleAccounts.size(); i++) {
3343 result[i] = visibleAccounts.get(i);
3344 }
3345 return result;
3346 }
3347 }
3348
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003349 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003350 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
3351 checkManageUsersPermission("addSharedAccountsFromParentUser");
3352 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3353 for (Account account : accounts) {
3354 addSharedAccountAsUser(account, userId);
3355 }
3356 }
3357
3358 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003359 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003360 UserAccounts accounts = getUserAccounts(userId);
3361 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003362 ContentValues values = new ContentValues();
3363 values.put(ACCOUNTS_NAME, account.name);
3364 values.put(ACCOUNTS_TYPE, account.type);
3365 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3366 new String[] {account.name, account.type});
3367 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3368 if (accountId < 0) {
3369 Log.w(TAG, "insertAccountIntoDatabase: " + account
3370 + ", skipping the DB insert failed");
3371 return false;
3372 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003373 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003374 return true;
3375 }
3376
3377 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003378 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3379 userId = handleIncomingUser(userId);
3380 UserAccounts accounts = getUserAccounts(userId);
3381 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003382 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003383 final ContentValues values = new ContentValues();
3384 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003385 int r = db.update(
3386 TABLE_SHARED_ACCOUNTS,
3387 values,
3388 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3389 new String[] { account.name, account.type });
3390 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003391 int callingUid = getCallingUid();
3392 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3393 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003394 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003395 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003396 }
3397 return r > 0;
3398 }
3399
3400 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003401 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003402 return removeSharedAccountAsUser(account, userId, getCallingUid());
3403 }
3404
3405 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003406 userId = handleIncomingUser(userId);
3407 UserAccounts accounts = getUserAccounts(userId);
3408 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003409 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003410 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3411 new String[] {account.name, account.type});
3412 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003413 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3414 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003415 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003416 }
3417 return r > 0;
3418 }
3419
3420 @Override
3421 public Account[] getSharedAccountsAsUser(int userId) {
3422 userId = handleIncomingUser(userId);
3423 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003424 ArrayList<Account> accountList = new ArrayList<>();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003425 Cursor cursor = null;
3426 try {
3427 cursor = accounts.openHelper.getReadableDatabase()
3428 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3429 null, null, null, null, null);
3430 if (cursor != null && cursor.moveToFirst()) {
3431 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3432 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3433 do {
3434 accountList.add(new Account(cursor.getString(nameIndex),
3435 cursor.getString(typeIndex)));
3436 } while (cursor.moveToNext());
3437 }
3438 } finally {
3439 if (cursor != null) {
3440 cursor.close();
3441 }
3442 }
3443 Account[] accountArray = new Account[accountList.size()];
3444 accountList.toArray(accountArray);
3445 return accountArray;
3446 }
3447
3448 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003449 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003450 public Account[] getAccounts(String type, String opPackageName) {
3451 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003452 }
3453
Amith Yamasani27db4682013-03-30 17:07:47 -07003454 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003455 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003456 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003457 int callingUid = Binder.getCallingUid();
3458 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3459 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3460 + callingUid + " with uid=" + uid);
3461 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003462 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3463 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003464 }
3465
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003466 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003467 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003468 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3469 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003470 int packageUid = -1;
3471 try {
3472 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07003473 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3474 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003475 } catch (RemoteException re) {
3476 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3477 return new Account[0];
3478 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003479 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3480 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003481 }
3482
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003483 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003484 public void getAccountsByFeatures(
3485 IAccountManagerResponse response,
3486 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003487 String[] features,
3488 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003489 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003490 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3491 Log.v(TAG, "getAccounts: accountType " + type
3492 + ", response " + response
3493 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003494 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003495 + ", pid " + Binder.getCallingPid());
3496 }
Fred Quintana382601f2010-03-25 12:25:10 -07003497 if (response == null) throw new IllegalArgumentException("response is null");
3498 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003499 int userId = UserHandle.getCallingUserId();
3500
Svetoslavf3f02ac2015-09-08 14:36:35 -07003501 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3502 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003503 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003504 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003505 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003506 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3507 try {
3508 response.onResult(result);
3509 } catch (RemoteException e) {
3510 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3511 }
3512 return;
3513 }
Fred Quintana33269202009-04-20 16:05:10 -07003514 long identityToken = clearCallingIdentity();
3515 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003516 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003517 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003518 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003519 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003520 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003521 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08003522 Bundle result = new Bundle();
3523 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3524 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003525 return;
3526 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003527 new GetAccountsByTypeAndFeatureSession(
3528 userAccounts,
3529 response,
3530 type,
3531 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003532 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07003533 } finally {
3534 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07003535 }
3536 }
3537
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003538 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3539 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3540 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3541 try {
3542 if (cursor.moveToNext()) {
3543 return cursor.getLong(0);
3544 }
3545 return -1;
3546 } finally {
3547 cursor.close();
3548 }
3549 }
3550
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003551 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07003552 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003553 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07003554 try {
3555 if (cursor.moveToNext()) {
3556 return cursor.getLong(0);
3557 }
3558 return -1;
3559 } finally {
3560 cursor.close();
3561 }
3562 }
3563
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003564 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003565 Cursor cursor = db.query(CE_TABLE_EXTRAS, new String[]{EXTRAS_ID},
Fred Quintana60307342009-03-24 22:48:12 -07003566 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3567 new String[]{key}, null, null, null);
3568 try {
3569 if (cursor.moveToNext()) {
3570 return cursor.getLong(0);
3571 }
3572 return -1;
3573 } finally {
3574 cursor.close();
3575 }
3576 }
3577
Fred Quintanaa698f422009-04-08 19:14:54 -07003578 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07003579 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07003580 IAccountManagerResponse mResponse;
3581 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003582 final boolean mExpectActivityLaunch;
3583 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003584 final String mAccountName;
3585 // Indicates if we need to add auth details(like last credential time)
3586 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003587 // If set, we need to update the last authenticated time. This is
3588 // currently
3589 // used on
3590 // successful confirming credentials.
3591 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07003592
Fred Quintana33269202009-04-20 16:05:10 -07003593 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07003594 private int mNumRequestContinued = 0;
3595 private int mNumErrors = 0;
3596
Fred Quintana60307342009-03-24 22:48:12 -07003597 IAccountAuthenticator mAuthenticator = null;
3598
Fred Quintana8570f742010-02-18 10:32:54 -08003599 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003600 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003601
Amith Yamasani04e0d262012-02-14 11:50:53 -08003602 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003603 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3604 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003605 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3606 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3607 }
3608
3609 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3610 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3611 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07003612 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003613 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07003614 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08003615 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003616 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07003617 mResponse = response;
3618 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003619 mExpectActivityLaunch = expectActivityLaunch;
3620 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003621 mAccountName = accountName;
3622 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003623 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003624
Fred Quintanaa698f422009-04-08 19:14:54 -07003625 synchronized (mSessions) {
3626 mSessions.put(toString(), this);
3627 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003628 if (response != null) {
3629 try {
3630 response.asBinder().linkToDeath(this, 0 /* flags */);
3631 } catch (RemoteException e) {
3632 mResponse = null;
3633 binderDied();
3634 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003635 }
Fred Quintana60307342009-03-24 22:48:12 -07003636 }
3637
Fred Quintanaa698f422009-04-08 19:14:54 -07003638 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07003639 if (mResponse == null) {
3640 // this session has already been closed
3641 return null;
3642 }
Fred Quintana60307342009-03-24 22:48:12 -07003643 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07003644 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07003645 return response;
3646 }
3647
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003648 /**
3649 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
3650 * security policy.
3651 *
3652 * In particular we want to make sure that the Authenticator doesn't try to trick users
3653 * into launching aribtrary intents on the device via by tricking to click authenticator
3654 * supplied entries in the system Settings app.
3655 */
3656 protected void checkKeyIntent(
3657 int authUid,
3658 Intent intent) throws SecurityException {
3659 long bid = Binder.clearCallingIdentity();
3660 try {
3661 PackageManager pm = mContext.getPackageManager();
3662 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3663 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
3664 int targetUid = targetActivityInfo.applicationInfo.uid;
3665 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid)) {
3666 String pkgName = targetActivityInfo.packageName;
3667 String activityName = targetActivityInfo.name;
3668 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
3669 + "does not share a signature with the supplying authenticator (%s).";
3670 throw new SecurityException(
3671 String.format(tmpl, activityName, pkgName, mAccountType));
3672 }
3673 } finally {
3674 Binder.restoreCallingIdentity(bid);
3675 }
3676 }
3677
Fred Quintanaa698f422009-04-08 19:14:54 -07003678 private void close() {
3679 synchronized (mSessions) {
3680 if (mSessions.remove(toString()) == null) {
3681 // the session was already closed, so bail out now
3682 return;
3683 }
3684 }
3685 if (mResponse != null) {
3686 // stop listening for response deaths
3687 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3688
3689 // clear this so that we don't accidentally send any further results
3690 mResponse = null;
3691 }
3692 cancelTimeout();
3693 unbind();
3694 }
3695
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003696 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003697 public void binderDied() {
3698 mResponse = null;
3699 close();
3700 }
3701
3702 protected String toDebugString() {
3703 return toDebugString(SystemClock.elapsedRealtime());
3704 }
3705
3706 protected String toDebugString(long now) {
3707 return "Session: expectLaunch " + mExpectActivityLaunch
3708 + ", connected " + (mAuthenticator != null)
3709 + ", stats (" + mNumResults + "/" + mNumRequestContinued
3710 + "/" + mNumErrors + ")"
3711 + ", lifetime " + ((now - mCreationTime) / 1000.0);
3712 }
3713
Fred Quintana60307342009-03-24 22:48:12 -07003714 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003715 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3716 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3717 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003718 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003719 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003720 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003721 }
3722 }
3723
3724 private void unbind() {
3725 if (mAuthenticator != null) {
3726 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003727 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003728 }
3729 }
3730
Fred Quintana60307342009-03-24 22:48:12 -07003731 public void cancelTimeout() {
3732 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3733 }
3734
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003735 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003736 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003737 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003738 try {
3739 run();
3740 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003741 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003742 "remote exception");
3743 }
Fred Quintana60307342009-03-24 22:48:12 -07003744 }
3745
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003746 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003747 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003748 mAuthenticator = null;
3749 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003750 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003751 try {
3752 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3753 "disconnected");
3754 } catch (RemoteException e) {
3755 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3756 Log.v(TAG, "Session.onServiceDisconnected: "
3757 + "caught RemoteException while responding", e);
3758 }
3759 }
Fred Quintana60307342009-03-24 22:48:12 -07003760 }
3761 }
3762
Fred Quintanab839afc2009-10-14 15:57:28 -07003763 public abstract void run() throws RemoteException;
3764
Fred Quintana60307342009-03-24 22:48:12 -07003765 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003766 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003767 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003768 try {
3769 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3770 "timeout");
3771 } catch (RemoteException e) {
3772 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3773 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3774 e);
3775 }
3776 }
Fred Quintana60307342009-03-24 22:48:12 -07003777 }
3778 }
3779
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003780 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003781 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003782 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07003783 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003784 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003785 if (result != null) {
3786 boolean isSuccessfulConfirmCreds = result.getBoolean(
3787 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003788 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003789 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3790 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003791 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003792 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3793 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003794 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003795 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003796 if (needUpdate || mAuthDetailsRequired) {
3797 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3798 if (needUpdate && accountPresent) {
3799 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3800 }
3801 if (mAuthDetailsRequired) {
3802 long lastAuthenticatedTime = -1;
3803 if (accountPresent) {
3804 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3805 mAccounts.openHelper.getReadableDatabase(),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003806 "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3807 + " FROM " +
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003808 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3809 + ACCOUNTS_TYPE + "=?",
3810 new String[] {
3811 mAccountName, mAccountType
3812 });
3813 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003814 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003815 lastAuthenticatedTime);
3816 }
3817 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003818 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003819 if (result != null
3820 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003821 checkKeyIntent(
3822 Binder.getCallingUid(),
3823 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003824 }
3825 if (result != null
3826 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003827 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3828 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003829 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3830 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003831 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3832 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003833 }
Fred Quintana60307342009-03-24 22:48:12 -07003834 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003835 IAccountManagerResponse response;
3836 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003837 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003838 response = mResponse;
3839 } else {
3840 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003841 }
Fred Quintana60307342009-03-24 22:48:12 -07003842 if (response != null) {
3843 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07003844 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08003845 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3846 Log.v(TAG, getClass().getSimpleName()
3847 + " calling onError() on response " + response);
3848 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003849 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07003850 "null bundle returned");
3851 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08003852 if (mStripAuthTokenFromResult) {
3853 result.remove(AccountManager.KEY_AUTHTOKEN);
3854 }
Fred Quintana56285a62010-12-02 14:20:51 -08003855 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3856 Log.v(TAG, getClass().getSimpleName()
3857 + " calling onResult() on response " + response);
3858 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003859 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3860 (intent == null)) {
3861 // All AccountManager error codes are greater than 0
3862 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3863 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3864 } else {
3865 response.onResult(result);
3866 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003867 }
Fred Quintana60307342009-03-24 22:48:12 -07003868 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003869 // if the caller is dead then there is no one to care about remote exceptions
3870 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3871 Log.v(TAG, "failure while notifying response", e);
3872 }
Fred Quintana60307342009-03-24 22:48:12 -07003873 }
3874 }
3875 }
Fred Quintana60307342009-03-24 22:48:12 -07003876
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003877 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003878 public void onRequestContinued() {
3879 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003880 }
3881
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003882 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003883 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003884 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003885 IAccountManagerResponse response = getResponseAndClose();
3886 if (response != null) {
3887 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003888 Log.v(TAG, getClass().getSimpleName()
3889 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003890 }
3891 try {
3892 response.onError(errorCode, errorMessage);
3893 } catch (RemoteException e) {
3894 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3895 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3896 }
3897 }
3898 } else {
3899 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3900 Log.v(TAG, "Session.onError: already closed");
3901 }
Fred Quintana60307342009-03-24 22:48:12 -07003902 }
3903 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003904
3905 /**
3906 * find the component name for the authenticator and initiate a bind
3907 * if no authenticator or the bind fails then return false, otherwise return true
3908 */
3909 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003910 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3911 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3912 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003913 if (authenticatorInfo == null) {
3914 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3915 Log.v(TAG, "there is no authenticator for " + authenticatorType
3916 + ", bailing out");
3917 }
3918 return false;
3919 }
3920
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07003921 final ActivityManager am = mContext.getSystemService(ActivityManager.class);
3922 if (am.isUserRunningAndLocked(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06003923 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07003924 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
3925 + " which isn't encryption aware");
3926 return false;
3927 }
3928
Fred Quintanab839afc2009-10-14 15:57:28 -07003929 Intent intent = new Intent();
3930 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3931 intent.setComponent(authenticatorInfo.componentName);
3932 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3933 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3934 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003935 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003936 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003937 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3938 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3939 }
3940 return false;
3941 }
3942
Fred Quintanab839afc2009-10-14 15:57:28 -07003943 return true;
3944 }
Fred Quintana60307342009-03-24 22:48:12 -07003945 }
3946
3947 private class MessageHandler extends Handler {
3948 MessageHandler(Looper looper) {
3949 super(looper);
3950 }
Costin Manolache3348f142009-09-29 18:58:36 -07003951
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003952 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003953 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07003954 switch (msg.what) {
3955 case MESSAGE_TIMED_OUT:
3956 Session session = (Session)msg.obj;
3957 session.onTimedOut();
3958 break;
3959
Amith Yamasani5be347b2013-03-31 17:44:31 -07003960 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00003961 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07003962 break;
3963
Fred Quintana60307342009-03-24 22:48:12 -07003964 default:
3965 throw new IllegalStateException("unhandled message: " + msg.what);
3966 }
3967 }
3968 }
3969
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003970 static String getPreNDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07003971 File systemDir = Environment.getDataSystemDirectory();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003972 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
3973 PRE_N_DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003974 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07003975 // Migrate old file, if it exists, to the new location.
3976 // Make sure the new file doesn't already exist. A dummy file could have been
3977 // accidentally created in the old location, causing the new one to become corrupted
3978 // as well.
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003979 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07003980 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07003981 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07003982 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07003983 if (!userDir.exists()) {
3984 if (!userDir.mkdirs()) {
3985 throw new IllegalStateException("User dir cannot be created: " + userDir);
3986 }
3987 }
3988 if (!oldFile.renameTo(databaseFile)) {
3989 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
3990 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003991 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003992 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003993 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08003994 }
3995
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07003996 static String getDeDatabaseName(int userId) {
3997 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
3998 DE_DATABASE_NAME);
3999 return databaseFile.getPath();
4000 }
4001
4002 static String getCeDatabaseName(int userId) {
4003 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4004 CE_DATABASE_NAME);
4005 return databaseFile.getPath();
4006 }
4007
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004008 private static class DebugDbHelper{
4009 private DebugDbHelper() {
4010 }
4011
4012 private static String TABLE_DEBUG = "debug_table";
4013
4014 // Columns for the table
4015 private static String ACTION_TYPE = "action_type";
4016 private static String TIMESTAMP = "time";
4017 private static String CALLER_UID = "caller_uid";
4018 private static String TABLE_NAME = "table_name";
4019 private static String KEY = "primary_key";
4020
4021 // These actions correspond to the occurrence of real actions. Since
4022 // these are called by the authenticators, the uid associated will be
4023 // of the authenticator.
4024 private static String ACTION_SET_PASSWORD = "action_set_password";
4025 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4026 private static String ACTION_ACCOUNT_ADD = "action_account_add";
4027 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
4028 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4029 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4030
4031 // These actions don't necessarily correspond to any action on
4032 // accountDb taking place. As an example, there might be a request for
4033 // addingAccount, which might not lead to addition of account on grounds
4034 // of bad authentication. We will still be logging it to keep track of
4035 // who called.
4036 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4037 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004038
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004039 //This action doesn't add account to accountdb. Account is only
4040 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08004041 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004042 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4043 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08004044
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004045 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4046
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004047 private static void createDebugTable(SQLiteDatabase db) {
4048 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4049 + ACCOUNTS_ID + " INTEGER,"
4050 + ACTION_TYPE + " TEXT NOT NULL, "
4051 + TIMESTAMP + " DATETIME,"
4052 + CALLER_UID + " INTEGER NOT NULL,"
4053 + TABLE_NAME + " TEXT NOT NULL,"
4054 + KEY + " INTEGER PRIMARY KEY)");
4055 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4056 }
4057 }
4058
4059 private void logRecord(UserAccounts accounts, String action, String tableName) {
4060 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4061 logRecord(db, action, tableName, -1, accounts);
4062 }
4063
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004064 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4065 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4066 logRecord(db, action, tableName, -1, accounts, uid);
4067 }
4068
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004069 /*
4070 * This function receives an opened writable database.
4071 */
4072 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4073 UserAccounts userAccount) {
4074 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4075 }
4076
4077 /*
4078 * This function receives an opened writable database.
4079 */
4080 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4081 UserAccounts userAccount, int callingUid) {
4082 SQLiteStatement logStatement = userAccount.statementForLogging;
4083 logStatement.bindLong(1, accountId);
4084 logStatement.bindString(2, action);
4085 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4086 logStatement.bindLong(4, callingUid);
4087 logStatement.bindString(5, tableName);
4088 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
4089 logStatement.execute();
4090 logStatement.clearBindings();
4091 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4092 % MAX_DEBUG_DB_SIZE;
4093 }
4094
4095 /*
4096 * This should only be called once to compile the sql statement for logging
4097 * and to find the insertion point.
4098 */
4099 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4100 UserAccounts userAccount) {
4101 // Initialize the count if not done earlier.
4102 int size = (int) getDebugTableRowCount(db);
4103 if (size >= MAX_DEBUG_DB_SIZE) {
4104 // Table is full, and we need to find the point where to insert.
4105 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4106 } else {
4107 userAccount.debugDbInsertionPoint = size;
4108 }
4109 compileSqlStatementForLogging(db, userAccount);
4110 }
4111
4112 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4113 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4114 + " VALUES (?,?,?,?,?,?)";
4115 userAccount.statementForLogging = db.compileStatement(sql);
4116 }
4117
4118 private long getDebugTableRowCount(SQLiteDatabase db) {
4119 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4120 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4121 }
4122
4123 /*
4124 * Finds the row key where the next insertion should take place. This should
4125 * be invoked only if the table has reached its full capacity.
4126 */
4127 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4128 // This query finds the smallest timestamp value (and if 2 records have
4129 // same timestamp, the choose the lower id).
4130 String queryCountDebugDbRows = new StringBuilder()
4131 .append("SELECT ").append(DebugDbHelper.KEY)
4132 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4133 .append(" ORDER BY ")
4134 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4135 .append(" LIMIT 1")
4136 .toString();
4137 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4138 }
4139
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004140 static class PreNDatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004141
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004142 private final Context mContext;
4143 private final int mUserId;
4144
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004145 public PreNDatabaseHelper(Context context, int userId) {
4146 super(context, AccountManagerService.getPreNDatabaseName(userId), null,
4147 PRE_N_DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004148 mContext = context;
4149 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004150 }
4151
4152 @Override
4153 public void onCreate(SQLiteDatabase db) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004154 // We use PreNDatabaseHelper only if pre-N db exists
4155 throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004156 }
4157
Amith Yamasani67df64b2012-12-14 12:09:36 -08004158 private void createSharedAccountsTable(SQLiteDatabase db) {
4159 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4160 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4161 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4162 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4163 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4164 }
4165
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004166 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4167 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4168 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4169 }
4170
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004171 private void addOldAccountNameColumn(SQLiteDatabase db) {
4172 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4173 }
4174
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004175 private void addDebugTable(SQLiteDatabase db) {
4176 DebugDbHelper.createDebugTable(db);
4177 }
4178
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004179 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004180 db.execSQL(""
4181 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4182 + " BEGIN"
4183 + " DELETE FROM " + TABLE_AUTHTOKENS
4184 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4185 + " DELETE FROM " + TABLE_EXTRAS
4186 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004187 + " DELETE FROM " + TABLE_GRANTS
4188 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004189 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004190 }
4191
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004192 private void createGrantsTable(SQLiteDatabase db) {
4193 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4194 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4195 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4196 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4197 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4198 + "," + GRANTS_GRANTEE_UID + "))");
4199 }
4200
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004201 private void populateMetaTableWithAuthTypeAndUID(
4202 SQLiteDatabase db,
4203 Map<String, Integer> authTypeAndUIDMap) {
4204 Iterator<Entry<String, Integer>> iterator = authTypeAndUIDMap.entrySet().iterator();
4205 while (iterator.hasNext()) {
4206 Entry<String, Integer> entry = iterator.next();
4207 ContentValues values = new ContentValues();
4208 values.put(META_KEY,
4209 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
4210 values.put(META_VALUE, entry.getValue());
4211 db.insert(TABLE_META, null, values);
4212 }
4213 }
4214
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004215 /**
4216 * Pre-N database may need an upgrade before splitting
4217 */
Fred Quintana60307342009-03-24 22:48:12 -07004218 @Override
4219 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004220 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004221
Fred Quintanaa698f422009-04-08 19:14:54 -07004222 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004223 // no longer need to do anything since the work is done
4224 // when upgrading from version 2
4225 oldVersion++;
4226 }
4227
4228 if (oldVersion == 2) {
4229 createGrantsTable(db);
4230 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4231 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004232 oldVersion++;
4233 }
Costin Manolache3348f142009-09-29 18:58:36 -07004234
4235 if (oldVersion == 3) {
4236 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4237 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4238 oldVersion++;
4239 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004240
4241 if (oldVersion == 4) {
4242 createSharedAccountsTable(db);
4243 oldVersion++;
4244 }
4245
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004246 if (oldVersion == 5) {
4247 addOldAccountNameColumn(db);
4248 oldVersion++;
4249 }
4250
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004251 if (oldVersion == 6) {
4252 addLastSuccessfullAuthenticatedTimeColumn(db);
4253 oldVersion++;
4254 }
4255
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004256 if (oldVersion == 7) {
4257 addDebugTable(db);
4258 oldVersion++;
4259 }
4260
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004261 if (oldVersion == 8) {
4262 populateMetaTableWithAuthTypeAndUID(
4263 db,
4264 AccountManagerService.getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
4265 oldVersion++;
4266 }
4267
Amith Yamasani67df64b2012-12-14 12:09:36 -08004268 if (oldVersion != newVersion) {
4269 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4270 }
Fred Quintana60307342009-03-24 22:48:12 -07004271 }
4272
4273 @Override
4274 public void onOpen(SQLiteDatabase db) {
4275 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4276 }
4277 }
4278
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004279 static class DeDatabaseHelper extends SQLiteOpenHelper {
4280
4281 private final int mUserId;
4282 private volatile boolean mCeAttached;
4283
4284 private DeDatabaseHelper(Context context, int userId) {
4285 super(context, getDeDatabaseName(userId), null, DE_DATABASE_VERSION);
4286 mUserId = userId;
4287 }
4288
4289 /**
4290 * This call needs to be made while the mCacheLock is held. The way to
4291 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4292 * @param db The database.
4293 */
4294 @Override
4295 public void onCreate(SQLiteDatabase db) {
4296 Log.i(TAG, "Creating DE database for user " + mUserId);
4297 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4298 + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4299 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4300 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4301 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4302 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4303 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4304
4305 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4306 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4307 + META_VALUE + " TEXT)");
4308
4309 createGrantsTable(db);
4310 createSharedAccountsTable(db);
4311 createAccountsDeletionTrigger(db);
4312 DebugDbHelper.createDebugTable(db);
4313 }
4314
4315 private void createSharedAccountsTable(SQLiteDatabase db) {
4316 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4317 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4318 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4319 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4320 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4321 }
4322
4323 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4324 db.execSQL(""
4325 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4326 + " BEGIN"
4327 + " DELETE FROM " + TABLE_GRANTS
4328 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4329 + " END");
4330 }
4331
4332 private void createGrantsTable(SQLiteDatabase db) {
4333 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4334 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4335 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4336 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4337 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4338 + "," + GRANTS_GRANTEE_UID + "))");
4339 }
4340
4341 @Override
4342 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4343 Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4344
4345 if (oldVersion != newVersion) {
4346 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4347 }
4348 }
4349
4350 public void attachCeDatabase() {
4351 File ceDbFile = new File(getCeDatabaseName(mUserId));
4352 SQLiteDatabase db = getWritableDatabase();
4353 db.execSQL("ATTACH DATABASE '" + ceDbFile.getPath()+ "' AS ceDb");
4354 mCeAttached = true;
4355 }
4356
4357 public boolean isCeDatabaseAttached() {
4358 return mCeAttached;
4359 }
4360
4361
4362 public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
4363 if(!mCeAttached) {
4364 Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user "
4365 + mUserId + " is still locked ", new Throwable());
4366 }
4367 return super.getReadableDatabase();
4368 }
4369
4370 public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
4371 if(!mCeAttached) {
4372 Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
4373 + " is still locked ", new Throwable());
4374 }
4375 return super.getWritableDatabase();
4376 }
4377
4378 @Override
4379 public void onOpen(SQLiteDatabase db) {
4380 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
4381 }
4382
4383 private void migratePreNDbToDe(File preNDbFile) {
4384 Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
4385 SQLiteDatabase db = getWritableDatabase();
4386 db.execSQL("ATTACH DATABASE '" + preNDbFile.getPath() + "' AS preNDb");
4387 db.beginTransaction();
4388 // Copy accounts fields
4389 db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
4390 + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4391 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4392 + ") "
4393 + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
4394 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4395 + " FROM preNDb." + TABLE_ACCOUNTS);
4396 // Copy SHARED_ACCOUNTS
4397 db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
4398 + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
4399 "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
4400 + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
4401 // Copy DEBUG_TABLE
4402 db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
4403 + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4404 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4405 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
4406 "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
4407 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
4408 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
4409 + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
4410 // Copy GRANTS
4411 db.execSQL("INSERT INTO " + TABLE_GRANTS
4412 + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4413 + GRANTS_GRANTEE_UID + ") " +
4414 "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
4415 + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
4416 // Copy META
4417 db.execSQL("INSERT INTO " + TABLE_META
4418 + "(" + META_KEY + "," + META_VALUE + ") "
4419 + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
4420 db.setTransactionSuccessful();
4421 db.endTransaction();
4422
4423 db.execSQL("DETACH DATABASE preNDb");
4424 }
4425
4426 static DeDatabaseHelper create(Context context, int userId) {
4427 File oldDb = new File(getPreNDatabaseName(userId));
4428 File newDb = new File(getDeDatabaseName(userId));
4429 boolean newDbExists = newDb.exists();
4430 DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId);
4431 // If the db just created, and there is a legacy db, migrate it
4432 if (!newDbExists && oldDb.exists()) {
4433 // Migrate legacy db to the latest version - PRE_N_DATABASE_VERSION
4434 PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId);
4435 // Open the database to force upgrade if required
4436 preNDatabaseHelper.getWritableDatabase();
4437 preNDatabaseHelper.close();
4438 // Move data without SPII to DE
4439 deDatabaseHelper.migratePreNDbToDe(oldDb);
4440 }
4441 return deDatabaseHelper;
4442 }
4443 }
4444
4445 static class CeDatabaseHelper extends SQLiteOpenHelper {
4446
4447 public CeDatabaseHelper(Context context, int userId) {
4448 super(context, getCeDatabaseName(userId), null, CE_DATABASE_VERSION);
4449 }
4450
4451 /**
4452 * This call needs to be made while the mCacheLock is held.
4453 * @param db The database.
4454 */
4455 @Override
4456 public void onCreate(SQLiteDatabase db) {
4457 Log.i(TAG, "Creating CE database " + getDatabaseName());
4458 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4459 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4460 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4461 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4462 + ACCOUNTS_PASSWORD + " TEXT, "
4463 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4464
4465 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
4466 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4467 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4468 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
4469 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
4470 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
4471
4472 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
4473 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4474 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
4475 + EXTRAS_KEY + " TEXT NOT NULL, "
4476 + EXTRAS_VALUE + " TEXT, "
4477 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
4478
4479 createAccountsDeletionTrigger(db);
4480 }
4481
4482 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4483 db.execSQL(""
4484 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4485 + " BEGIN"
4486 + " DELETE FROM " + TABLE_AUTHTOKENS
4487 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4488 + " DELETE FROM " + TABLE_EXTRAS
4489 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4490 + " END");
4491 }
4492
4493 @Override
4494 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4495 Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
4496
4497 if (oldVersion == 9) {
4498 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4499 Log.v(TAG, "onUpgrade upgrading to v10");
4500 }
4501 db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
4502 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
4503 // Recreate the trigger, since the old one references the table to be removed
4504 db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
4505 createAccountsDeletionTrigger(db);
4506 db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
4507 db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
4508 oldVersion ++;
4509 }
4510
4511 if (oldVersion != newVersion) {
4512 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4513 }
4514 }
4515
4516 @Override
4517 public void onOpen(SQLiteDatabase db) {
4518 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
4519 }
4520
4521 static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
4522 String type) {
4523 Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
4524 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
4525 new String[]{name, type}, null, null, null);
4526 try {
4527 if (cursor.moveToNext()) {
4528 return cursor.getString(0);
4529 }
4530 return null;
4531 } finally {
4532 cursor.close();
4533 }
4534 }
4535
4536 /**
4537 * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
4538 * it also performs migration to the new CE database.
4539 * @param context
4540 * @param userId id of the user where the database is located
4541 */
4542 static CeDatabaseHelper create(Context context, int userId) {
4543
4544 File oldDatabaseFile = new File(getPreNDatabaseName(userId));
4545 File ceDatabaseFile = new File(getCeDatabaseName(userId));
4546 boolean newDbExists = ceDatabaseFile.exists();
4547 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4548 Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
4549 + oldDatabaseFile.exists() + " newDbExists=" + newDbExists);
4550 }
4551 boolean removeOldDb = false;
4552 if (!newDbExists && oldDatabaseFile.exists()) {
4553 removeOldDb = migratePreNDbToCe(oldDatabaseFile, ceDatabaseFile);
4554 }
4555 // Try to open and upgrade if necessary
4556 CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, userId);
4557 ceHelper.getWritableDatabase();
4558 ceHelper.close();
4559 if (removeOldDb) {
4560 // TODO STOPSHIP - backup file during testing. Remove file before the release
4561 Log.i(TAG, "Migration complete - creating backup of old db " + oldDatabaseFile);
4562 renameToBakFile(oldDatabaseFile);
4563 }
4564 return ceHelper;
4565 }
4566
4567 private static void renameToBakFile(File file) {
4568 File bakFile = new File(file.getPath() + ".bak");
4569 if (!file.renameTo(bakFile)) {
4570 Log.e(TAG, "Cannot move file to " + bakFile);
4571 }
4572 }
4573
4574 private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
4575 Log.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
4576 try {
4577 FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
4578 } catch (IOException e) {
4579 Log.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
4580 // Try to remove potentially damaged file if I/O error occurred
4581 deleteDbFileWarnIfFailed(ceDbFile);
4582 return false;
4583 }
4584 return true;
4585 }
4586 }
4587
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004588 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004589 return asBinder();
4590 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004591
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004592 /**
4593 * Searches array of arguments for the specified string
4594 * @param args array of argument strings
4595 * @param value value to search for
4596 * @return true if the value is contained in the array
4597 */
4598 private static boolean scanArgs(String[] args, String value) {
4599 if (args != null) {
4600 for (String arg : args) {
4601 if (value.equals(arg)) {
4602 return true;
4603 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004604 }
4605 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004606 return false;
4607 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004608
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004609 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004610 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07004611 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4612 != PackageManager.PERMISSION_GRANTED) {
4613 fout.println("Permission Denial: can't dump AccountsManager from from pid="
4614 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4615 + " without permission " + android.Manifest.permission.DUMP);
4616 return;
4617 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004618 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004619 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004620
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004621 final List<UserInfo> users = getUserManager().getUsers();
4622 for (UserInfo user : users) {
4623 ipw.println("User " + user + ":");
4624 ipw.increaseIndent();
4625 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4626 ipw.println();
4627 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08004628 }
4629 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004630
Amith Yamasani04e0d262012-02-14 11:50:53 -08004631 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4632 String[] args, boolean isCheckinRequest) {
4633 synchronized (userAccounts.cacheLock) {
4634 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004635
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004636 if (isCheckinRequest) {
4637 // This is a checkin request. *Only* upload the account types and the count of each.
4638 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4639 null, null, ACCOUNTS_TYPE, null, null);
4640 try {
4641 while (cursor.moveToNext()) {
4642 // print type,count
4643 fout.println(cursor.getString(0) + "," + cursor.getString(1));
4644 }
4645 } finally {
4646 if (cursor != null) {
4647 cursor.close();
4648 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004649 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004650 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004651 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07004652 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004653 fout.println("Accounts: " + accounts.length);
4654 for (Account account : accounts) {
4655 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004656 }
Fred Quintana307da1a2010-01-21 14:24:20 -08004657
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004658 // Add debug information.
4659 fout.println();
4660 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4661 null, null, null, null, DebugDbHelper.TIMESTAMP);
4662 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4663 fout.println("Accounts History");
4664 try {
4665 while (cursor.moveToNext()) {
4666 // print type,count
4667 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4668 cursor.getString(2) + "," + cursor.getString(3) + ","
4669 + cursor.getString(4) + "," + cursor.getString(5));
4670 }
4671 } finally {
4672 cursor.close();
4673 }
4674
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004675 fout.println();
4676 synchronized (mSessions) {
4677 final long now = SystemClock.elapsedRealtime();
4678 fout.println("Active Sessions: " + mSessions.size());
4679 for (Session session : mSessions.values()) {
4680 fout.println(" " + session.toDebugString(now));
4681 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004682 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004683
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004684 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004685 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004686 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004687 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004688 }
4689
Amith Yamasani04e0d262012-02-14 11:50:53 -08004690 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07004691 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004692 long identityToken = clearCallingIdentity();
4693 try {
4694 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4695 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4696 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004697
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004698 if (intent.getComponent() != null &&
4699 GrantCredentialsPermissionActivity.class.getName().equals(
4700 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004701 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004702 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004703 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004704 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004705 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004706 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07004707 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004708 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004709 Notification n = new Notification.Builder(contextForUser)
4710 .setWhen(0)
4711 .setSmallIcon(android.R.drawable.stat_sys_warning)
4712 .setColor(contextForUser.getColor(
4713 com.android.internal.R.color.system_notification_accent_color))
4714 .setContentTitle(String.format(notificationTitleFormat, account.name))
4715 .setContentText(message)
4716 .setContentIntent(PendingIntent.getActivityAsUser(
4717 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4718 null, user))
4719 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004720 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004721 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004722 } finally {
4723 restoreCallingIdentity(identityToken);
4724 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004725 }
4726
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004727 protected void installNotification(final int notificationId, final Notification n,
4728 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08004729 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004730 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08004731 }
4732
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004733 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004734 long identityToken = clearCallingIdentity();
4735 try {
4736 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004737 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004738 } finally {
4739 restoreCallingIdentity(identityToken);
4740 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004741 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004742
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004743 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
4744 for (String perm : permissions) {
4745 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
4746 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4747 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
4748 }
4749 final int opCode = AppOpsManager.permissionToOpCode(perm);
4750 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
4751 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
4752 return true;
4753 }
4754 }
4755 }
4756 return false;
4757 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004758
Amith Yamasani67df64b2012-12-14 12:09:36 -08004759 private int handleIncomingUser(int userId) {
4760 try {
4761 return ActivityManagerNative.getDefault().handleIncomingUser(
4762 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
4763 } catch (RemoteException re) {
4764 // Shouldn't happen, local.
4765 }
4766 return userId;
4767 }
4768
Christopher Tateccbf84f2013-05-08 15:25:41 -07004769 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004770 final int callingUserId = UserHandle.getUserId(callingUid);
4771
4772 final PackageManager userPackageManager;
4773 try {
4774 userPackageManager = mContext.createPackageContextAsUser(
4775 "android", 0, new UserHandle(callingUserId)).getPackageManager();
4776 } catch (NameNotFoundException e) {
4777 return false;
4778 }
4779
4780 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07004781 for (String name : packages) {
4782 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004783 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08004784 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08004785 && (packageInfo.applicationInfo.privateFlags
4786 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07004787 return true;
4788 }
4789 } catch (PackageManager.NameNotFoundException e) {
4790 return false;
4791 }
4792 }
4793 return false;
4794 }
4795
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004796 private boolean permissionIsGranted(
4797 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07004798 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07004799 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004800 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07004801 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08004802 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004803 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4804 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08004805 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004806 + ": is authenticator? " + fromAuthenticator
4807 + ", has explicit permission? " + hasExplicitGrants);
4808 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07004809 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004810 }
4811
Svetoslavf3f02ac2015-09-08 14:36:35 -07004812 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
4813 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004814 if (accountType == null) {
4815 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004816 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07004817 return getTypesVisibleToCaller(callingUid, userId,
4818 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004819 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004820 }
4821
4822 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
4823 if (accountType == null) {
4824 return false;
4825 } else {
4826 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
4827 }
4828 }
4829
Svetoslavf3f02ac2015-09-08 14:36:35 -07004830 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
4831 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004832 boolean isPermitted =
4833 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
4834 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004835 return getTypesForCaller(callingUid, userId, isPermitted);
4836 }
4837
4838 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
4839 return getTypesForCaller(callingUid, userId, false);
4840 }
4841
4842 private List<String> getTypesForCaller(
4843 int callingUid, int userId, boolean isOtherwisePermitted) {
4844 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004845 long identityToken = Binder.clearCallingIdentity();
4846 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
4847 try {
4848 serviceInfos = mAuthenticatorCache.getAllServices(userId);
4849 } finally {
4850 Binder.restoreCallingIdentity(identityToken);
4851 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004852 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004853 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004854 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
4855 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
4856 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004857 }
4858 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004859 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004860 }
4861
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004862 private boolean isAccountPresentForCaller(String accountName, String accountType) {
4863 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
4864 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
4865 if (account.name.equals(accountName)) {
4866 return true;
4867 }
4868 }
4869 }
4870 return false;
4871 }
4872
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004873 private static void checkManageUsersPermission(String message) {
4874 if (ActivityManager.checkComponentPermission(
4875 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
4876 != PackageManager.PERMISSION_GRANTED) {
4877 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
4878 }
4879 }
4880
Amith Yamasani04e0d262012-02-14 11:50:53 -08004881 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
4882 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004883 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004884 return true;
4885 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004886 UserAccounts accounts = getUserAccountsForCaller();
4887 synchronized (accounts.cacheLock) {
4888 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
4889 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004890 account.name, account.type};
4891 final boolean permissionGranted =
4892 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
4893 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
4894 // TODO: Skip this check when running automated tests. Replace this
4895 // with a more general solution.
4896 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08004897 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004898 + " but ignoring since device is in test harness.");
4899 return true;
4900 }
4901 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004902 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004903 }
4904
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004905 private boolean isSystemUid(int callingUid) {
4906 String[] packages = null;
4907 long ident = Binder.clearCallingIdentity();
4908 try {
4909 packages = mPackageManager.getPackagesForUid(callingUid);
4910 } finally {
4911 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004912 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004913 if (packages != null) {
4914 for (String name : packages) {
4915 try {
4916 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
4917 if (packageInfo != null
4918 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
4919 != 0) {
4920 return true;
4921 }
4922 } catch (PackageManager.NameNotFoundException e) {
4923 Log.w(TAG, String.format("Could not find package [%s]", name), e);
4924 }
4925 }
4926 } else {
4927 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004928 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004929 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00004930 }
4931
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004932 /** Succeeds if any of the specified permissions are granted. */
4933 private void checkReadAccountsPermitted(
4934 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004935 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004936 int userId,
4937 String opPackageName) {
4938 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004939 String msg = String.format(
4940 "caller uid %s cannot access %s accounts",
4941 callingUid,
4942 accountType);
4943 Log.w(TAG, " " + msg);
4944 throw new SecurityException(msg);
4945 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004946 }
4947
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004948 private boolean canUserModifyAccounts(int userId, int callingUid) {
4949 // the managing app can always modify accounts
4950 if (isProfileOwner(callingUid)) {
4951 return true;
4952 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004953 if (getUserManager().getUserRestrictions(new UserHandle(userId))
4954 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
4955 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08004956 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004957 return true;
4958 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004959
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004960 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
4961 // the managing app can always modify accounts
4962 if (isProfileOwner(callingUid)) {
4963 return true;
4964 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004965 DevicePolicyManager dpm = (DevicePolicyManager) mContext
4966 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004967 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02004968 if (typesArray == null) {
4969 return true;
4970 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004971 for (String forbiddenType : typesArray) {
4972 if (forbiddenType.equals(accountType)) {
4973 return false;
4974 }
4975 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08004976 return true;
4977 }
4978
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004979 private boolean isProfileOwner(int uid) {
4980 final DevicePolicyManagerInternal dpmi =
4981 LocalServices.getService(DevicePolicyManagerInternal.class);
4982 return (dpmi != null)
4983 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4984 }
4985
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004986 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07004987 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
4988 throws RemoteException {
4989 final int callingUid = getCallingUid();
4990
Amith Yamasani27db4682013-03-30 17:07:47 -07004991 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07004992 throw new SecurityException();
4993 }
4994
4995 if (value) {
4996 grantAppPermission(account, authTokenType, uid);
4997 } else {
4998 revokeAppPermission(account, authTokenType, uid);
4999 }
5000 }
5001
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005002 /**
5003 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5004 * <p>
5005 * Although this is public it can only be accessed via the AccountManagerService object
5006 * which is in the system. This means we don't need to protect it with permissions.
5007 * @hide
5008 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005009 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005010 if (account == null || authTokenType == null) {
5011 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005012 return;
5013 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005014 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005015 synchronized (accounts.cacheLock) {
5016 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005017 db.beginTransaction();
5018 try {
5019 long accountId = getAccountIdLocked(db, account);
5020 if (accountId >= 0) {
5021 ContentValues values = new ContentValues();
5022 values.put(GRANTS_ACCOUNTS_ID, accountId);
5023 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
5024 values.put(GRANTS_GRANTEE_UID, uid);
5025 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
5026 db.setTransactionSuccessful();
5027 }
5028 } finally {
5029 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005030 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005031 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005032 UserHandle.of(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005033 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005034 }
5035
5036 /**
5037 * Don't allow callers with the given uid permission to get credentials for
5038 * account/authTokenType.
5039 * <p>
5040 * Although this is public it can only be accessed via the AccountManagerService object
5041 * which is in the system. This means we don't need to protect it with permissions.
5042 * @hide
5043 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005044 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005045 if (account == null || authTokenType == null) {
5046 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005047 return;
5048 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005049 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005050 synchronized (accounts.cacheLock) {
5051 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005052 db.beginTransaction();
5053 try {
5054 long accountId = getAccountIdLocked(db, account);
5055 if (accountId >= 0) {
5056 db.delete(TABLE_GRANTS,
5057 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
5058 + GRANTS_GRANTEE_UID + "=?",
5059 new String[]{String.valueOf(accountId), authTokenType,
5060 String.valueOf(uid)});
5061 db.setTransactionSuccessful();
5062 }
5063 } finally {
5064 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005065 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005066 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5067 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005068 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005069 }
Fred Quintana56285a62010-12-02 14:20:51 -08005070
5071 static final private String stringArrayToString(String[] value) {
5072 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5073 }
5074
Amith Yamasani04e0d262012-02-14 11:50:53 -08005075 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5076 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005077 if (oldAccountsForType != null) {
5078 ArrayList<Account> newAccountsList = new ArrayList<Account>();
5079 for (Account curAccount : oldAccountsForType) {
5080 if (!curAccount.equals(account)) {
5081 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005082 }
5083 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005084 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005085 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005086 } else {
5087 Account[] newAccountsForType = new Account[newAccountsList.size()];
5088 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005089 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005090 }
Fred Quintana56285a62010-12-02 14:20:51 -08005091 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005092 accounts.userDataCache.remove(account);
5093 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005094 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005095 }
5096
5097 /**
5098 * This assumes that the caller has already checked that the account is not already present.
5099 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08005100 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5101 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005102 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5103 Account[] newAccountsForType = new Account[oldLength + 1];
5104 if (accountsForType != null) {
5105 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005106 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005107 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005108 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08005109 }
5110
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005111 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07005112 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005113 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07005114 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005115 return unfiltered;
5116 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005117 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005118 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005119 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005120 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005121 // otherwise return non-shared accounts only.
5122 // This might be a temporary way to specify a whitelist
5123 String whiteList = mContext.getResources().getString(
5124 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5125 for (String packageName : packages) {
5126 if (whiteList.contains(";" + packageName + ";")) {
5127 return unfiltered;
5128 }
5129 }
5130 ArrayList<Account> allowed = new ArrayList<Account>();
5131 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5132 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005133 String requiredAccountType = "";
5134 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005135 // If there's an explicit callingPackage specified, check if that package
5136 // opted in to see restricted accounts.
5137 if (callingPackage != null) {
5138 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005139 if (pi != null && pi.restrictedAccountType != null) {
5140 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005141 }
5142 } else {
5143 // Otherwise check if the callingUid has a package that has opted in
5144 for (String packageName : packages) {
5145 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5146 if (pi != null && pi.restrictedAccountType != null) {
5147 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005148 break;
5149 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005150 }
5151 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005152 } catch (NameNotFoundException nnfe) {
5153 }
5154 for (Account account : unfiltered) {
5155 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005156 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005157 } else {
5158 boolean found = false;
5159 for (Account shared : sharedAccounts) {
5160 if (shared.equals(account)) {
5161 found = true;
5162 break;
5163 }
5164 }
5165 if (!found) {
5166 allowed.add(account);
5167 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005168 }
5169 }
5170 Account[] filtered = new Account[allowed.size()];
5171 allowed.toArray(filtered);
5172 return filtered;
5173 } else {
5174 return unfiltered;
5175 }
5176 }
5177
Amith Yamasani27db4682013-03-30 17:07:47 -07005178 /*
5179 * packageName can be null. If not null, it should be used to filter out restricted accounts
5180 * that the package is not allowed to access.
5181 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005182 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07005183 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005184 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005185 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005186 if (accounts == null) {
5187 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005188 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005189 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07005190 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005191 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005192 } else {
5193 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005194 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005195 totalLength += accounts.length;
5196 }
5197 if (totalLength == 0) {
5198 return EMPTY_ACCOUNT_ARRAY;
5199 }
5200 Account[] accounts = new Account[totalLength];
5201 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005202 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005203 System.arraycopy(accountsOfType, 0, accounts, totalLength,
5204 accountsOfType.length);
5205 totalLength += accountsOfType.length;
5206 }
Amith Yamasani27db4682013-03-30 17:07:47 -07005207 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005208 }
5209 }
5210
Amith Yamasani04e0d262012-02-14 11:50:53 -08005211 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5212 Account account, String key, String value) {
5213 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005214 if (userDataForAccount == null) {
5215 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005216 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005217 }
5218 if (value == null) {
5219 userDataForAccount.remove(key);
5220 } else {
5221 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005222 }
5223 }
5224
Carlos Valdivia91979be2015-05-22 14:11:35 -07005225 protected String readCachedTokenInternal(
5226 UserAccounts accounts,
5227 Account account,
5228 String tokenType,
5229 String callingPackage,
5230 byte[] pkgSigDigest) {
5231 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005232 return accounts.accountTokenCaches.get(
5233 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005234 }
5235 }
5236
Amith Yamasani04e0d262012-02-14 11:50:53 -08005237 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5238 Account account, String key, String value) {
5239 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005240 if (authTokensForAccount == null) {
5241 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005242 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005243 }
5244 if (value == null) {
5245 authTokensForAccount.remove(key);
5246 } else {
5247 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005248 }
5249 }
5250
Amith Yamasani04e0d262012-02-14 11:50:53 -08005251 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5252 String authTokenType) {
5253 synchronized (accounts.cacheLock) {
5254 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005255 if (authTokensForAccount == null) {
5256 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005257 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005258 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005259 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005260 }
5261 return authTokensForAccount.get(authTokenType);
5262 }
5263 }
5264
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00005265 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
5266 synchronized (accounts.cacheLock) {
5267 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
5268 if (userDataForAccount == null) {
5269 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005270 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00005271 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
5272 accounts.userDataCache.put(account, userDataForAccount);
5273 }
5274 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005275 }
5276 }
5277
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005278 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
5279 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005280 HashMap<String, String> userDataForAccount = new HashMap<>();
5281 Cursor cursor = db.query(CE_TABLE_EXTRAS,
Fred Quintana56285a62010-12-02 14:20:51 -08005282 COLUMNS_EXTRAS_KEY_AND_VALUE,
5283 SELECTION_USERDATA_BY_ACCOUNT,
5284 new String[]{account.name, account.type},
5285 null, null, null);
5286 try {
5287 while (cursor.moveToNext()) {
5288 final String tmpkey = cursor.getString(0);
5289 final String value = cursor.getString(1);
5290 userDataForAccount.put(tmpkey, value);
5291 }
5292 } finally {
5293 cursor.close();
5294 }
5295 return userDataForAccount;
5296 }
5297
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005298 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
5299 final SQLiteDatabase db, Account account) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005300 HashMap<String, String> authTokensForAccount = new HashMap<>();
5301 Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
Fred Quintana56285a62010-12-02 14:20:51 -08005302 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
5303 SELECTION_AUTHTOKENS_BY_ACCOUNT,
5304 new String[]{account.name, account.type},
5305 null, null, null);
5306 try {
5307 while (cursor.moveToNext()) {
5308 final String type = cursor.getString(0);
5309 final String authToken = cursor.getString(1);
5310 authTokensForAccount.put(type, authToken);
5311 }
5312 } finally {
5313 cursor.close();
5314 }
5315 return authTokensForAccount;
5316 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005317
5318 private Context getContextForUser(UserHandle user) {
5319 try {
5320 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5321 } catch (NameNotFoundException e) {
5322 // Default to mContext, not finding the package system is running as is unlikely.
5323 return mContext;
5324 }
5325 }
Sandra Kwan78812282015-11-04 11:19:47 -08005326
5327 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5328 try {
5329 response.onResult(result);
5330 } catch (RemoteException e) {
5331 // if the caller is dead then there is no one to care about remote
5332 // exceptions
5333 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5334 Log.v(TAG, "failure while notifying response", e);
5335 }
5336 }
5337 }
5338
5339 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5340 String errorMessage) {
5341 try {
5342 response.onError(errorCode, errorMessage);
5343 } catch (RemoteException e) {
5344 // if the caller is dead then there is no one to care about remote
5345 // exceptions
5346 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5347 Log.v(TAG, "failure while notifying response", e);
5348 }
5349 }
5350 }
Fred Quintana60307342009-03-24 22:48:12 -07005351}