blob: 31f14e7a77bac64359ff82dad07f6d260a5e991d [file] [log] [blame]
Fred Quintana60307342009-03-24 22:48:12 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.accounts;
Fred Quintana60307342009-03-24 22:48:12 -070018
Doug Zongker885cfc232009-10-21 16:52:44 -070019import android.Manifest;
Carlos Valdivia91979be2015-05-22 14:11:35 -070020import android.accounts.AbstractAccountAuthenticator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080021import android.accounts.Account;
22import android.accounts.AccountAndUser;
23import android.accounts.AccountAuthenticatorResponse;
24import android.accounts.AccountManager;
25import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070026import android.accounts.CantAddAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.accounts.GrantCredentialsPermissionActivity;
28import android.accounts.IAccountAuthenticator;
29import android.accounts.IAccountAuthenticatorResponse;
30import android.accounts.IAccountManager;
31import android.accounts.IAccountManagerResponse;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070032import android.annotation.NonNull;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080033import android.app.ActivityManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070034import android.app.ActivityManagerNative;
Amith Yamasani3b458ad2013-04-18 18:40:07 -070035import android.app.AppGlobals;
Svetoslavf3f02ac2015-09-08 14:36:35 -070036import android.app.AppOpsManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000040import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010041import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000042import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070043import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070044import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070045import android.content.ContentValues;
46import android.content.Context;
47import android.content.Intent;
48import android.content.IntentFilter;
Fred Quintanab839afc2009-10-14 15:57:28 -070049import android.content.ServiceConnection;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -080050import android.content.pm.ActivityInfo;
Doug Zongker885cfc232009-10-21 16:52:44 -070051import android.content.pm.ApplicationInfo;
52import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070053import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070054import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070055import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070056import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070057import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070058import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070059import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070060import android.database.Cursor;
61import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070062import android.database.sqlite.SQLiteDatabase;
63import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070064import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070065import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070066import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080067import android.os.Environment;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070068import android.os.FileUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070070import android.os.IBinder;
71import android.os.Looper;
72import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070073import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070074import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070075import android.os.RemoteException;
76import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070077import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070078import android.os.UserManager;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070079import android.os.storage.StorageManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070080import android.text.TextUtils;
81import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070082import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070083import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080084import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070085import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070086
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070087import com.android.internal.R;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070088import com.android.internal.annotations.VisibleForTesting;
Amith Yamasani67df64b2012-12-14 12:09:36 -080089import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080090import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -070091import com.android.internal.util.Preconditions;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070092import com.android.server.FgThread;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000093import com.android.server.LocalServices;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -060094import com.android.server.SystemService;
95
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070096import com.google.android.collect.Lists;
97import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070098
Oscar Montemayora8529f62009-11-18 10:14:20 -080099import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700100import java.io.FileDescriptor;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700101import java.io.IOException;
Fred Quintanaa698f422009-04-08 19:14:54 -0700102import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800103import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700104import java.security.MessageDigest;
105import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700106import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700107import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800108import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700109import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700110import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700111import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700112import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800113import java.util.LinkedHashMap;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700114import java.util.LinkedList;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700115import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800116import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800117import java.util.Map.Entry;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700118import java.util.Set;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700119import java.util.concurrent.atomic.AtomicInteger;
120import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700121
Fred Quintana60307342009-03-24 22:48:12 -0700122/**
123 * A system service that provides account, password, and authtoken management for all
124 * accounts on the device. Some of these calls are implemented with the help of the corresponding
125 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
126 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700127 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700128 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700129 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700130public class AccountManagerService
131 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800132 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700133 private static final String TAG = "AccountManagerService";
134
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600135 public static class Lifecycle extends SystemService {
136 private AccountManagerService mService;
137
138 public Lifecycle(Context context) {
139 super(context);
140 }
141
142 @Override
143 public void onStart() {
144 mService = new AccountManagerService(getContext());
145 publishBinderService(Context.ACCOUNT_SERVICE, mService);
146 }
147
148 @Override
149 public void onBootPhase(int phase) {
150 if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
151 mService.systemReady();
152 }
153 }
154
155 @Override
156 public void onUnlockUser(int userHandle) {
157 mService.onUnlockUser(userHandle);
158 }
159 }
160
Fred Quintana60307342009-03-24 22:48:12 -0700161 private static final String DATABASE_NAME = "accounts.db";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700162 private static final int PRE_N_DATABASE_VERSION = 9;
163 private static final int CE_DATABASE_VERSION = 10;
164 private static final int DE_DATABASE_VERSION = 1;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700165
166 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700167
168 private final Context mContext;
169
Fred Quintana56285a62010-12-02 14:20:51 -0800170 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700171 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700172 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800173
Fred Quintana60307342009-03-24 22:48:12 -0700174 private final MessageHandler mMessageHandler;
175
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700176 /**
177 * Used to keep data read/write operations for logging purposes in a separate thread
178 * from main thread
179 */
180 private final LinkedList<Runnable> mLogRecordRunnables = new LinkedList<Runnable>();
181 private Thread mLogRecordThread;
182
Fred Quintana60307342009-03-24 22:48:12 -0700183 // Messages that can be sent on mHandler
184 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700185 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700186
Fred Quintana56285a62010-12-02 14:20:51 -0800187 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700188
189 private static final String TABLE_ACCOUNTS = "accounts";
190 private static final String ACCOUNTS_ID = "_id";
191 private static final String ACCOUNTS_NAME = "name";
192 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700193 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700194 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700195 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800196 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
197 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700198
199 private static final String TABLE_AUTHTOKENS = "authtokens";
200 private static final String AUTHTOKENS_ID = "_id";
201 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
202 private static final String AUTHTOKENS_TYPE = "type";
203 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
204
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700205 private static final String TABLE_GRANTS = "grants";
206 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
207 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
208 private static final String GRANTS_GRANTEE_UID = "uid";
209
Fred Quintana60307342009-03-24 22:48:12 -0700210 private static final String TABLE_EXTRAS = "extras";
211 private static final String EXTRAS_ID = "_id";
212 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
213 private static final String EXTRAS_KEY = "key";
214 private static final String EXTRAS_VALUE = "value";
215
216 private static final String TABLE_META = "meta";
217 private static final String META_KEY = "key";
218 private static final String META_VALUE = "value";
219
Amith Yamasani67df64b2012-12-14 12:09:36 -0800220 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700221 private static final String SHARED_ACCOUNTS_ID = "_id";
222
223 private static final String PRE_N_DATABASE_NAME = "accounts.db";
224 private static final String CE_DATABASE_NAME = "accounts_ce.db";
225 private static final String DE_DATABASE_NAME = "accounts_de.db";
226 private static final String CE_DB_PREFIX = "ceDb.";
227 private static final String CE_TABLE_ACCOUNTS = CE_DB_PREFIX + TABLE_ACCOUNTS;
228 private static final String CE_TABLE_AUTHTOKENS = CE_DB_PREFIX + TABLE_AUTHTOKENS;
229 private static final String CE_TABLE_EXTRAS = CE_DB_PREFIX + TABLE_EXTRAS;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800230
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700231 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
232 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700233 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800234
Carlos Valdivia91979be2015-05-22 14:11:35 -0700235 static {
236 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
237 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
238 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700239
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700240 private static final String COUNT_OF_MATCHING_GRANTS = ""
241 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
242 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
243 + " AND " + GRANTS_GRANTEE_UID + "=?"
244 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
245 + " AND " + ACCOUNTS_NAME + "=?"
246 + " AND " + ACCOUNTS_TYPE + "=?";
247
Fred Quintana56285a62010-12-02 14:20:51 -0800248 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
249 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700250
Fred Quintana56285a62010-12-02 14:20:51 -0800251 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
252 AUTHTOKENS_AUTHTOKEN};
253
254 private static final String SELECTION_USERDATA_BY_ACCOUNT =
255 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
256 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
257
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800258 private static final String META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX =
259 "auth_uid_for_type:";
260 private static final String META_KEY_DELIMITER = ":";
261 private static final String SELECTION_META_BY_AUTHENTICATOR_TYPE = META_KEY + " LIKE ?";
262
Fred Quintanaa698f422009-04-08 19:14:54 -0700263 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700264 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
265
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700266 private static final String NEW_ACCOUNT_VISIBLE = "android.accounts.NEW_ACCOUNT_VISIBLE";
267
Amith Yamasani04e0d262012-02-14 11:50:53 -0800268 static class UserAccounts {
269 private final int userId;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700270 private final DeDatabaseHelper openHelper;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800271 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
272 credentialsPermissionNotificationIds =
273 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
274 private final HashMap<Account, Integer> signinRequiredNotificationIds =
275 new HashMap<Account, Integer>();
276 private final Object cacheLock = new Object();
277 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700278 private final HashMap<String, Account[]> accountCache =
279 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800280 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700281 private final Map<Account, Map<String, String>> userDataCache = new HashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800282 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700283 private final Map<Account, Map<String, String>> authTokenCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700284
285 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700286 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700287
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700288 /** protected by the {@link #cacheLock} */
289 private final Map<String, ArrayList<Integer>> mApplicationAccountRequestMappings =
290 new HashMap<>();
291
292 /* Together the below two Sparse Arrays serve as visible list. One maps UID to account
293 number. Another maps Account number to Account.*/
294
295 /** protected by the {@link #cacheLock} */
296 private final SparseArray<ArrayList<Integer>> mVisibleListUidToMockAccountNumbers =
297 new SparseArray<>();
298
299 //TODO: Instead of using Mock Account IDs, use the actual account IDs.
300 /** protected by the {@link #cacheLock} */
301 private final SparseArray<Account> mMockAccountIdToAccount = new SparseArray<>();
302
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700303 /**
304 * protected by the {@link #cacheLock}
305 *
306 * Caches the previous names associated with an account. Previous names
307 * should be cached because we expect that when an Account is renamed,
308 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
309 * want to know if the accounts they care about have been renamed.
310 *
311 * The previous names are wrapped in an {@link AtomicReference} so that
312 * we can distinguish between those accounts with no previous names and
313 * those whose previous names haven't been cached (yet).
314 */
315 private final HashMap<Account, AtomicReference<String>> previousNameCache =
316 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800317
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700318 private int debugDbInsertionPoint = -1;
319 private SQLiteStatement statementForLogging;
320
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700321 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800322 this.userId = userId;
323 synchronized (cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700324 openHelper = DeDatabaseHelper.create(context, userId, preNDbFile, deDbFile);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800325 }
326 }
327 }
328
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700329 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600330 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800331
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700332 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700333 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700334
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700335 /**
336 * This should only be called by system code. One should only call this after the service
337 * has started.
338 * @return a reference to the AccountManagerService instance
339 * @hide
340 */
341 public static AccountManagerService getSingleton() {
342 return sThis.get();
343 }
Fred Quintana60307342009-03-24 22:48:12 -0700344
Fred Quintana56285a62010-12-02 14:20:51 -0800345 public AccountManagerService(Context context) {
346 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700347 }
348
Fred Quintana56285a62010-12-02 14:20:51 -0800349 public AccountManagerService(Context context, PackageManager packageManager,
350 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700351 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800352 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700353 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700354
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700355 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700356
Fred Quintana56285a62010-12-02 14:20:51 -0800357 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800358 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700359
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700360 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800361
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700362 addRequestsForPreInstalledApplications();
363
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800364 IntentFilter intentFilter = new IntentFilter();
365 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
366 intentFilter.addDataScheme("package");
367 mContext.registerReceiver(new BroadcastReceiver() {
368 @Override
369 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700370 // Don't delete accounts when updating a authenticator's
371 // package.
372 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700373 /* Purging data requires file io, don't block the main thread. This is probably
374 * less than ideal because we are introducing a race condition where old grants
375 * could be exercised until they are purged. But that race condition existed
376 * anyway with the broadcast receiver.
377 *
378 * Ideally, we would completely clear the cache, purge data from the database,
379 * and then rebuild the cache. All under the cache lock. But that change is too
380 * large at this point.
381 */
382 Runnable r = new Runnable() {
383 @Override
384 public void run() {
385 purgeOldGrantsAll();
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700386
387 /* clears application request's for account types supported */
388 int uidOfUninstalledApplication =
389 intent.getIntExtra(Intent.EXTRA_UID, -1);
390 if(uidOfUninstalledApplication != -1) {
391 clearRequestedAccountVisibility(uidOfUninstalledApplication,
392 getUserAccounts(UserHandle.getUserId(
393 uidOfUninstalledApplication)));
394 }
395
396 /* removes visibility of previous UID of this uninstalled application*/
397 removeAccountVisibilityAllAccounts(uidOfUninstalledApplication,
398 getUserAccounts(UserHandle.getUserId(
399 uidOfUninstalledApplication)));
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700400 }
401 };
402 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700403 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700404
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800405 }
406 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800407
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700408 IntentFilter packageAddedOrChangedFilter = new IntentFilter();
409 intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
410 packageAddedOrChangedFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
411 packageAddedOrChangedFilter.addDataScheme("package");
412 mContext.registerReceiverAsUser(new BroadcastReceiver() {
413 @Override
414 public void onReceive(Context context1, Intent intent) {
415 mMessageHandler.post(new Runnable() {
416 @Override
417 public void run() {
418 int uidOfInstalledApplication =
419 intent.getIntExtra(Intent.EXTRA_UID, -1);
420 if(uidOfInstalledApplication != -1) {
421 registerAccountTypesSupported(
422 uidOfInstalledApplication,
423 getUserAccounts(
424 UserHandle.getUserId(uidOfInstalledApplication)));
425 }
426 }
427 });
428 }
429 }, UserHandle.ALL, packageAddedOrChangedFilter, null, null);
430
Amith Yamasani13593602012-03-22 16:16:17 -0700431 IntentFilter userFilter = new IntentFilter();
432 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800433 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700434 @Override
435 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800436 String action = intent.getAction();
437 if (Intent.ACTION_USER_REMOVED.equals(action)) {
438 onUserRemoved(intent);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800439 }
Amith Yamasani13593602012-03-22 16:16:17 -0700440 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800441 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800442 }
443
Dianne Hackborn164371f2013-10-01 19:10:13 -0700444 @Override
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700445 public boolean addAccountExplicitlyWithUid(Account account, String password, Bundle extras,
446 int[] selectedUids) {
447 if(addAccountExplicitly(account,password,extras)) {
448 for(int thisUid : selectedUids) {
449 makeAccountVisible(account, thisUid);
450 }
451 return true;
452 }
453 return false;
454 }
455
456 @Override
457 public int[] getRequestingUidsForType(String accountType) {
458 int callingUid = Binder.getCallingUid();
459 if (!isAccountManagedByCaller(accountType, callingUid, UserHandle.getUserId(callingUid))) {
460 String msg = String.format(
461 "uid %s cannot get secrets for accounts of type: %s",
462 callingUid,
463 accountType);
464 throw new SecurityException(msg);
465 }
466 return getRequestingUidsForType(accountType, getUserAccounts(
467 UserHandle.getUserId(callingUid)));
468 }
469
470 /**
471 * Returns all UIDs for applications that requested the account type. This method
472 * is called indirectly by the Authenticator and AccountManager
473 *
474 * @param accountType authenticator would like to know the requesting apps of
475 * @param ua UserAccount that currently hosts the account and application
476 *
477 * @return ArrayList of all UIDs that support accounts of this
478 * account type that seek approval (to be used to know which accounts for
479 * the authenticator to include in addAccountExplicitly). Null if none.
480 */
481 private int[] getRequestingUidsForType(String accountType, UserAccounts ua) {
482 synchronized(ua.cacheLock) {
483 Map<String, ArrayList<Integer>> userApplicationAccountRequestMappings =
484 ua.mApplicationAccountRequestMappings;
485 ArrayList<Integer> allUidsForAccountType = userApplicationAccountRequestMappings.get(
486 accountType);
487 if(allUidsForAccountType == null) {
488 return null;
489 }
490 int[] toReturn = new int[allUidsForAccountType.size()];
491 for(int i = 0 ; i < toReturn.length ; i++) {
492 toReturn[i] = allUidsForAccountType.get(i);
493 }
494 return toReturn;
495 }
496 }
497
498 @Override
499 public boolean isAccountVisible(Account a, int uid) {
500 int callingUid = Binder.getCallingUid();
501 if (!isAccountManagedByCaller(a.type, callingUid, UserHandle.getUserId(callingUid))) {
502 String msg = String.format(
503 "uid %s cannot get secrets for accounts of type: %s",
504 callingUid,
505 a.type);
506 throw new SecurityException(msg);
507 }
508 return isAccountVisible(a, uid, getUserAccounts(UserHandle.getUserId(callingUid)));
509 }
510
511 /**
512 * Checks visibility of certain account of a process identified
513 * by a given UID. This is called by the Authenticator indirectly.
514 *
515 * @param a The account to check visibility of
516 * @param uid UID to check visibility of
517 * @param ua UserAccount that currently hosts the account and application
518 *
519 * @return True if application has access to the account
520 *
521 */
522 private boolean isAccountVisible(Account a, int uid, UserAccounts ua) {
Tejas Khorana69990d92016-08-03 11:19:40 -0700523 if(isAccountManagedByCaller(a.type, uid, UserHandle.getUserId(uid))) {
524 return true;
525 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700526 int accountMapping = getMockAccountNumber(a, ua);
527 if(accountMapping < 0) {
528 return true;
529 }
530 synchronized(ua.cacheLock) {
Tejas Khorana69990d92016-08-03 11:19:40 -0700531 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700532 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
533 ua.mVisibleListUidToMockAccountNumbers;
534 ArrayList<Integer> linkedAccountsToUid = userWlUidToMockAccountNums.get(uid);
Tejas Khorana69990d92016-08-03 11:19:40 -0700535 int indexOfAccountMapping = userAcctIdToAcctMap.indexOfValueByValue(a);
536 return indexOfAccountMapping == -1 || (linkedAccountsToUid != null
537 && linkedAccountsToUid.contains(accountMapping));
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700538 }
539 }
540
541 @Override
542 public boolean makeAccountVisible(Account a, int uid) {
543 int callingUid = Binder.getCallingUid();
544 if (!isAccountManagedByCaller(a.type, callingUid, UserHandle.getUserId(callingUid))) {
545 String msg = String.format(
546 "uid %s cannot get secrets for accounts of type: %s",
547 callingUid,
548 a.type);
549 throw new SecurityException(msg);
550 }
551 return makeAccountVisible(a, uid, getUserAccounts(UserHandle.getUserId(callingUid)));
552 }
553
554 /**
555 * Gives a certain UID, represented a application, access to an account. This method
556 * is called indirectly by the Authenticator.
557 *
558 * @param a Account to make visible
559 * @param uid to add visibility of the Account from
560 * @param ua UserAccount that currently hosts the account and application
561 *
562 * @return True if account made visible to application and was not previously visible.
563 */
564 private boolean makeAccountVisible(Account a, int uid, UserAccounts ua) {
565 int accountMapping = getMockAccountNumber(a, ua);
566 if(accountMapping < 0) {
567 accountMapping = makeAccountNumber(a, ua);
568 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700569 synchronized(ua.cacheLock) {
570 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
571 ua.mVisibleListUidToMockAccountNumbers;
572 ArrayList<Integer> linkedAccountsToUid = userWlUidToMockAccountNums.get(uid);
573 if(linkedAccountsToUid == null) {
574 linkedAccountsToUid = new ArrayList<>();
575 linkedAccountsToUid.add(accountMapping);
576 userWlUidToMockAccountNums.put(uid, linkedAccountsToUid);
577 } else if(!linkedAccountsToUid.contains(accountMapping)) {
578 linkedAccountsToUid.add(accountMapping);
579 } else {
580 return false;
581 }
582 }
583
584 String[] subPackages = mPackageManager.getPackagesForUid(uid);
585 if(subPackages != null) {
586 for(String subPackage : subPackages) {
587 sendNotification(subPackage, a);
588 }
589 }
590 return true;
591 }
592
593 @Override
594 public boolean removeAccountVisibility(Account a, int uid) {
595 int callingUid = Binder.getCallingUid();
596 if (!isAccountManagedByCaller(a.type, callingUid, UserHandle.getUserId(callingUid))) {
597 String msg = String.format(
598 "uid %s cannot get secrets for accounts of type: %s",
599 callingUid,
600 a.type);
601 throw new SecurityException(msg);
602 }
603 return removeAccountVisibility(a, uid, getUserAccounts(UserHandle.getUserId(callingUid)));
604 }
605
606 /**
607 * Removes visibility of certain account of a process identified
608 * by a given UID to an application. This is called directly by the
609 * AccountManager and indirectly by the Authenticator.
610 *
611 * @param a Account to remove visibility from
612 * @param uid UID to remove visibility of the Account from
613 * @param ua UserAccount that hosts the account and application
614 *
615 * @return True if application access to account removed and was previously visible.
616 */
617 private boolean removeAccountVisibility(Account a, int uid, UserAccounts ua) {
618 int accountMapping = getMockAccountNumber(a, ua);
619 if(accountMapping < 0) {
620 return false;
621 }
622 synchronized(ua.cacheLock) {
623 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
624 ua.mVisibleListUidToMockAccountNumbers;
625 ArrayList<Integer> linkedAccountsToUid = userWlUidToMockAccountNums.get(uid);
626 if(linkedAccountsToUid != null) {
627 boolean toReturn = linkedAccountsToUid.remove((Integer) accountMapping);
628 if(linkedAccountsToUid.size() == 0) {
629 userWlUidToMockAccountNums.remove(uid);
630 }
631 return toReturn;
632 }
633 }
634 return false;
635 }
636
637 /**
638 * Registers an application's preferences for supported account types for login. This is
639 * a helper method of requestAccountVisibility and indirectly called by AccountManager.
640 *
641 * @param accountTypes account types third party app is willing to support
642 * @param uid of application requesting account visibility
643 * @param ua UserAccount that hosts the account and application
644 */
645 private void addRequestedAccountsVisibility(String[] accountTypes, int uid, UserAccounts ua) {
646 synchronized(ua.cacheLock) {
647 Map<String, ArrayList<Integer>> userApplicationAccountRequestMappings =
648 ua.mApplicationAccountRequestMappings;
649 for(String accountType : accountTypes) {
650 ArrayList<Integer> accountUidAppList = userApplicationAccountRequestMappings
651 .get(accountType);
652 if(accountUidAppList == null) {
653 accountUidAppList = new ArrayList<>();
654 accountUidAppList.add(uid);
655 userApplicationAccountRequestMappings.put(accountType, accountUidAppList);
656 } else if (!accountUidAppList.contains(uid)) {
657 accountUidAppList.add(uid);
658 }
659 }
660 }
661 }
662
663 /**
664 * Registers the requested login account types requested by all the applications already
665 * installed on the device.
666 */
667 private void addRequestsForPreInstalledApplications() {
668 List<PackageInfo> allInstalledPackages = mContext.getPackageManager().
669 getInstalledPackages(0);
670 for(PackageInfo pi : allInstalledPackages) {
671 int currentUid = pi.applicationInfo.uid;
672 if(currentUid != -1) {
673 registerAccountTypesSupported(currentUid,
674 getUserAccounts(UserHandle.getUserId(currentUid)));
675 }
676 }
677 }
678
679 /**
680 * Clears all preferences an application had for login account types it offered
681 * support for. This method is used by AccountManager after application is
682 * uninstalled.
683 *
684 * @param uid Uid of the application to clear account type preferences
685 * @param ua UserAccount that hosted the account and application
686 *
687 * @return true if any previous settings were overridden.
688 */
689 private boolean clearRequestedAccountVisibility(int uid, UserAccounts ua) {
690 boolean accountsDeleted = false;
691 ArrayList<String> accountTypesToRemove = new ArrayList<>();
692 synchronized(ua.cacheLock) {
693 Map<String, ArrayList<Integer>> userApplicationAccountRequestMappings =
694 ua.mApplicationAccountRequestMappings;
695 Set<Entry<String, ArrayList<Integer>>> accountTypeAppListEntries =
696 userApplicationAccountRequestMappings.entrySet();
697
698 for(Entry<String, ArrayList<Integer>> entry : accountTypeAppListEntries) {
699 ArrayList<Integer> supportedApps = entry.getValue();
700 if(supportedApps.remove((Integer) uid)) {
701 accountsDeleted = true;
702 }
703
704 if(supportedApps.isEmpty()) {
705 accountTypesToRemove.add(entry.getKey());
706 }
707 }
708
709 for(String s : accountTypesToRemove) {
710 userApplicationAccountRequestMappings.remove(s);
711 }
712 }
713
714 return accountsDeleted;
715 }
716
717 /**
718 * Retrieves the mock account number associated with an Account in order to later retrieve
719 * the account from the Integer-Account Mapping. An account number is not the same as
720 * accountId in the database. This method can be indirectly called by AccountManager and
721 * indirectly by the Authenticator.
722 *
723 * @param a account to retrieve account number mapping
724 * @param ua UserAccount that currently hosts the account and application
725 *
726 * @return account number affiliated with the Account in question. Negative number if none.
727 */
728 private int getMockAccountNumber(Account a, UserAccounts ua) {
729 //TODO: Each account is linked to AccountId rather than generated mock account numbers
730 SparseArray<Account> userAcctIdToAcctMap =
731 ua.mMockAccountIdToAccount;
732 synchronized(ua.cacheLock) {
733 int indexOfAccount = userAcctIdToAcctMap.indexOfValueByValue(a);
734 if(indexOfAccount < 0) {
735 return -1;
736 }
737 return userAcctIdToAcctMap.keyAt(indexOfAccount);
738 }
739 }
740
741 /**
742 * Returns a full list of accounts that a certain UID is allowed access
743 * based on the visible list entries.
744 *
745 * @param uid of application to retrieve visible listed accounts for
746 * @param ua UserAccount that currently hosts the account and application
747 *
748 * @return array of Account values that are accessible by the given uids
749 */
750 private Account[] getVisibleListedAccounts(int uid, UserAccounts ua) {
751 ArrayList<Account> visibleListedAccounts = new ArrayList<>();
752 synchronized(ua.cacheLock) {
753 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
754 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
755 ua.mVisibleListUidToMockAccountNumbers;
756 ArrayList<Integer> visibleListedUidAccountNumbers =
757 userWlUidToMockAccountNums.get(uid);
758 if(visibleListedUidAccountNumbers != null) {
759 for(Integer accountNumber : visibleListedUidAccountNumbers) {
760 Account currentAccount = userAcctIdToAcctMap.get(accountNumber);
761 visibleListedAccounts.add(currentAccount);
762 }
763 }
764 }
765 Account[] arrVisibleListedAccounts = new Account[visibleListedAccounts.size()];
766 return visibleListedAccounts.toArray(arrVisibleListedAccounts);
767 }
768
769 /**
770 * Makes an account number for a given Account to be mapped to.
771 * This method is called by makeVisible if an Account does not have
772 * a mapping for the visible list. This method is thus indirectly
773 * called by the Authenticator.
774 *
775 * @param a account to make an account number mapping of
776 * @param ua UserAccount that currently hosts the account and application
777 *
778 * @return account number created to map to the given account
779 */
780 // TODO: Remove this method and use accountId from DB.
781 private int makeAccountNumber(Account a, UserAccounts ua) {
782 synchronized(ua.cacheLock) {
783 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
784 int newAccountMapping = 0;
785 while(userAcctIdToAcctMap.get(newAccountMapping) != null) {
786 newAccountMapping++;
787 }
788 userAcctIdToAcctMap.put(newAccountMapping, a);
789 return newAccountMapping;
790 }
791 }
792
793
794
795 /**
796 * Registers an application, represented by a UID, to support account types detailed in
797 * the applications manifest as well as allowing it to opt for notifications.
798 *
799 * @param uid UID of application
800 * @param ua UserAccount that currently hosts the account and application
801 */
802 private void registerAccountTypesSupported(int uid, UserAccounts ua) {
803 /* Account types supported are drawn from the Android Manifest of the Application */
804 String interestedPackages = null;
805 try {
806 String[] allPackages = mPackageManager.getPackagesForUid(uid);
807 for(String aPackage : allPackages) {
808 ApplicationInfo ai = mPackageManager.getApplicationInfo(aPackage,
809 PackageManager.GET_META_DATA);
810 Bundle b = ai.metaData;
811 if(b == null) {
812 return;
813 }
814 interestedPackages = b.getString("android.accounts.SupportedLoginTypes");
815 }
816 } catch (PackageManager.NameNotFoundException e) {
817 Log.d("NameNotFoundException", e.getMessage());
818 }
819 if(interestedPackages != null) {
820 /* request remote account types directly from here. Reads from Android Manifest */
821 requestAccountVisibility(interestedPackages.split(";"), uid, ua);
822 }
823 }
824
825 /**
826 * Allows AccountManager to register account types that an application has login
827 * support for. This method over-writes all of the application's previous settings
828 * for accounts it supported.
829 *
830 * @param accountTypes array of account types application wishes to support
831 * @param uid of application registering requested account types
832 * @param ua UserAccount that hosts the account and application
833 */
834 private void requestAccountVisibility(String[] accountTypes, int uid, UserAccounts ua) {
835 if(accountTypes.length > 0) {
836 clearRequestedAccountVisibility(uid, ua);
837 addRequestedAccountsVisibility(accountTypes, uid, ua);
838 }
839 }
840
841 /**
842 * Removes visibility of all Accounts to this particular UID. This is called when an
843 * application is uninstalled so another application that is installed with the same
844 * UID cannot access Accounts. This is called by AccountManager.
845 *
846 * @param uid of application to remove all Account visibility to
847 * @param ua UserAccount that hosts the current Account
848 */
849 private void removeAccountVisibilityAllAccounts(int uid, UserAccounts ua) {
850 synchronized(ua.cacheLock) {
851 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
852 ua.mVisibleListUidToMockAccountNumbers;
853 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
854 ArrayList<Integer> allAccountNumbersList = userWlUidToMockAccountNums.get(uid);
855 if(allAccountNumbersList != null) {
856 Integer[] allAccountNumbers = allAccountNumbersList.toArray(
857 new Integer[allAccountNumbersList.size()]);
858 for(int accountNum : allAccountNumbers) {
859 removeAccountVisibility(userAcctIdToAcctMap.get(accountNum), uid, ua);
860 }
861 }
862 }
863 }
864
865 /**
866 * Removes visible list functionality of a certain Account.
867 * This method is currently called by (1) addAccountExplicitly (as opposed to
868 * addAccountExplicitlyWithUid) and (2) removeAccountExplicitly.
869 *
870 * @param a the account to clear the visible list functionality for
871 * @param ua currently UserAccounts profile containing Account
872 *
873 * @return true if account previously had visible list functionality
874 */
875 private boolean removeVisibleListFunctionality(Account a, UserAccounts ua) {
876 int mockAccountNum = getMockAccountNumber(a, ua);
877 if(mockAccountNum < 0) {
878 return false;
879 }
880 synchronized(ua.cacheLock) {
881 SparseArray<ArrayList<Integer>> userWlUidToMockAccountNums =
882 ua.mVisibleListUidToMockAccountNumbers;
883 SparseArray<Account> userAcctIdToAcctMap = ua.mMockAccountIdToAccount;
884
885 /* Removing mapping from account number to account removes visible list functionality*/
886 userAcctIdToAcctMap.remove(mockAccountNum);
887
888 for(int i = userWlUidToMockAccountNums.size() - 1 ; i >= 0 ; i--) {
889 int uidKey = userWlUidToMockAccountNums.keyAt(i);
890 ArrayList<Integer> allAccountNumbers = userWlUidToMockAccountNums.get(uidKey);
891 if(allAccountNumbers != null) {
892 allAccountNumbers.remove(mockAccountNum);
893 if(allAccountNumbers.isEmpty()) {
894 userWlUidToMockAccountNums.remove(uidKey);
895 }
896 }
897 }
898 }
899 return true;
900 }
901
902 /**
903 * Sends a direct intent to a package, notifying it of a visible account. This
904 * method is a helper method of makeAccountVisible.
905 *
906 * @param desiredPackage to send Account to
907 * @param visibleAccount to send to package
908 */
909 private void sendNotification(String desiredPackage, Account visibleAccount) {
910 Intent intent = new Intent();
911 intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
912 intent.setAction(NEW_ACCOUNT_VISIBLE);
913 intent.setPackage(desiredPackage);
914 intent.putExtra("android.accounts.KEY_ACCOUNT", (Account) visibleAccount);
915 mContext.sendBroadcast(intent);
916 }
917
918 @Override
Dianne Hackborn164371f2013-10-01 19:10:13 -0700919 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
920 throws RemoteException {
921 try {
922 return super.onTransact(code, data, reply, flags);
923 } catch (RuntimeException e) {
924 // The account manager only throws security exceptions, so let's
925 // log all others.
926 if (!(e instanceof SecurityException)) {
927 Slog.wtf(TAG, "Account Manager Crash", e);
928 }
929 throw e;
930 }
931 }
932
Kenny Root26ff6622012-07-30 12:58:03 -0700933 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700934 }
935
Amith Yamasani258848d2012-08-10 17:06:33 -0700936 private UserManager getUserManager() {
937 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700938 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700939 }
940 return mUserManager;
941 }
942
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700943 /**
944 * Validate internal set of accounts against installed authenticators for
945 * given user. Clears cached authenticators before validating.
946 */
947 public void validateAccounts(int userId) {
948 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700949 // Invalidate user-specific cache to make sure we catch any
950 // removed authenticators.
951 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
952 }
953
954 /**
955 * Validate internal set of accounts against installed authenticators for
956 * given user. Clear cached authenticators before validating when requested.
957 */
958 private void validateAccountsInternal(
959 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700960 if (Log.isLoggable(TAG, Log.DEBUG)) {
961 Log.d(TAG, "validateAccountsInternal " + accounts.userId
962 + " isCeDatabaseAttached=" + accounts.openHelper.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600963 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700964 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700965
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700966 if (invalidateAuthenticatorCache) {
967 mAuthenticatorCache.invalidateCache(accounts.userId);
968 }
969
Carlos Valdiviaa46b1122016-04-26 19:36:50 -0700970 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
971 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -0700972 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700973
Amith Yamasani04e0d262012-02-14 11:50:53 -0800974 synchronized (accounts.cacheLock) {
975 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800976 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800977
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700978 // Get a map of stored authenticator types to UID
979 Map<String, Integer> metaAuthUid = AccountsDbUtils.findMetaAuthUid(db);
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800980 // Create a list of authenticator type whose previous uid no longer exists
981 HashSet<String> obsoleteAuthType = Sets.newHashSet();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700982 SparseBooleanArray knownUids = null;
983 for (Entry<String, Integer> authToUidEntry : metaAuthUid.entrySet()) {
984 String type = authToUidEntry.getKey();
985 int uid = authToUidEntry.getValue();
986 Integer knownUid = knownAuth.get(type);
987 if (knownUid != null && uid == knownUid) {
988 // Remove it from the knownAuth list if it's unchanged.
989 knownAuth.remove(type);
990 } else {
991 /*
992 * The authenticator is presently not cached and should only be triggered
993 * when we think an authenticator has been removed (or is being updated).
994 * But we still want to check if any data with the associated uid is
995 * around. This is an (imperfect) signal that the package may be updating.
996 *
997 * A side effect of this is that an authenticator sharing a uid with
998 * multiple apps won't get its credentials wiped as long as some app with
999 * that uid is still on the device. But I suspect that this is a rare case.
1000 * And it isn't clear to me how an attacker could really exploit that
1001 * feature.
1002 *
1003 * The upshot is that we don't have to worry about accounts getting
1004 * uninstalled while the authenticator's package is being updated.
1005 *
1006 */
1007 if (knownUids == null) {
1008 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001009 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001010 if (!knownUids.get(uid)) {
1011 // The authenticator is not presently available to the cache. And the
1012 // package no longer has a data directory (so we surmise it isn't updating).
1013 // So purge its data from the account databases.
1014 obsoleteAuthType.add(type);
1015 // And delete it from the TABLE_META
1016 AccountsDbUtils.deleteMetaByAuthTypeAndUid(db, type, uid);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001017 }
1018 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001019 }
1020
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001021 // Add the newly registered authenticator to TABLE_META. If old authenticators have
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001022 // been re-enabled (after being updated for example), then we just overwrite the old
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001023 // values.
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001024 for (Entry<String, Integer> entry : knownAuth.entrySet()) {
1025 AccountsDbUtils.insertOrReplaceMetaAuthTypeAndUid(db, entry.getKey(),
1026 entry.getValue());
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001027 }
1028
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001029 final Map<Long, Account> accountsMap = AccountsDbUtils.findAllAccounts(db);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001030 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001031 accounts.accountCache.clear();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001032 final HashMap<String, ArrayList<String>> accountNamesByType = new LinkedHashMap<>();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001033 for (Entry<Long, Account> accountEntry : accountsMap.entrySet()) {
1034 final long accountId = accountEntry.getKey();
1035 final Account account = accountEntry.getValue();
1036 if (obsoleteAuthType.contains(account.type)) {
1037 Slog.w(TAG, "deleting account " + account.name + " because type "
1038 + account.type + "'s registered authenticator no longer exist.");
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001039 db.beginTransaction();
1040 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001041 AccountsDbUtils.deleteAccount(db, accountId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001042 // Also delete from CE table if user is unlocked; if user is currently
1043 // locked the account will be removed later by syncDeCeAccountsLocked
1044 if (userUnlocked) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001045 AccountsDbUtils.deleteCeAccount(db, accountId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001046 }
1047 db.setTransactionSuccessful();
1048 } finally {
1049 db.endTransaction();
1050 }
Fred Quintana56285a62010-12-02 14:20:51 -08001051 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001052
1053 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
1054 accountId, accounts);
1055
Amith Yamasani04e0d262012-02-14 11:50:53 -08001056 accounts.userDataCache.remove(account);
1057 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001058 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08001059 } else {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001060 ArrayList<String> accountNames = accountNamesByType.get(account.type);
Fred Quintana56285a62010-12-02 14:20:51 -08001061 if (accountNames == null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001062 accountNames = new ArrayList<>();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001063 accountNamesByType.put(account.type, accountNames);
Fred Quintana56285a62010-12-02 14:20:51 -08001064 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001065 accountNames.add(account.name);
Fred Quintana56285a62010-12-02 14:20:51 -08001066 }
1067 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001068 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -08001069 final String accountType = cur.getKey();
1070 final ArrayList<String> accountNames = cur.getValue();
1071 final Account[] accountsForType = new Account[accountNames.size()];
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001072 for (int i = 0; i < accountsForType.length; i++) {
1073 accountsForType[i] = new Account(accountNames.get(i), accountType);
Fred Quintana56285a62010-12-02 14:20:51 -08001074 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001075 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -08001076 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001077 } finally {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001078 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001079 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001080 }
Fred Quintanaafa92b82009-12-01 16:27:03 -08001081 }
1082 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001083 }
1084
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001085 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
1086 // Get the UIDs of all apps that might have data on the device. We want
1087 // to preserve user data if the app might otherwise be storing data.
1088 List<PackageInfo> pkgsWithData =
1089 mPackageManager.getInstalledPackagesAsUser(
1090 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1091 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
1092 for (PackageInfo pkgInfo : pkgsWithData) {
1093 if (pkgInfo.applicationInfo != null
1094 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
1095 knownUids.put(pkgInfo.applicationInfo.uid, true);
1096 }
1097 }
1098 return knownUids;
1099 }
1100
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001101 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1102 Context context,
1103 int userId) {
1104 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001105 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
1106 }
1107
1108 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1109 IAccountAuthenticatorCache authCache,
1110 int userId) {
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001111 HashMap<String, Integer> knownAuth = new HashMap<>();
1112 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
1113 .getAllServices(userId)) {
1114 knownAuth.put(service.type.type, service.uid);
1115 }
1116 return knownAuth;
1117 }
1118
Amith Yamasani04e0d262012-02-14 11:50:53 -08001119 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001120 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001121 }
1122
1123 protected UserAccounts getUserAccounts(int userId) {
1124 synchronized (mUsers) {
1125 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001126 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001127 if (accounts == null) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001128 File preNDbFile = new File(getPreNDatabaseName(userId));
1129 File deDbFile = new File(getDeDatabaseName(userId));
1130 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001131 initializeDebugDbSizeAndCompileSqlStatementForLogging(
1132 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001133 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001134 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001135 validateAccounts = true;
1136 }
1137 // open CE database if necessary
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001138 if (!accounts.openHelper.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001139 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
1140 synchronized (accounts.cacheLock) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001141 File preNDatabaseFile = new File(getPreNDatabaseName(userId));
1142 File ceDatabaseFile = new File(getCeDatabaseName(userId));
1143 CeDatabaseHelper.create(mContext, userId, preNDatabaseFile, ceDatabaseFile);
1144 accounts.openHelper.attachCeDatabase(ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001145 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001146 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001147 }
1148 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001149 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001150 }
1151 return accounts;
1152 }
1153 }
1154
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001155 private void syncDeCeAccountsLocked(UserAccounts accounts) {
1156 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
1157 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001158 List<Account> accountsToRemove = AccountsDbUtils.findCeAccountsNotInDe(db);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001159 if (!accountsToRemove.isEmpty()) {
1160 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
1161 + accounts.userId + " was locked. Removing accounts from CE tables");
1162 logRecord(accounts, DebugDbHelper.ACTION_SYNC_DE_CE_ACCOUNTS, TABLE_ACCOUNTS);
1163
1164 for (Account account : accountsToRemove) {
1165 removeAccountInternal(accounts, account, Process.myUid());
1166 }
1167 }
1168 }
1169
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001170 private void purgeOldGrantsAll() {
1171 synchronized (mUsers) {
1172 for (int i = 0; i < mUsers.size(); i++) {
1173 purgeOldGrants(mUsers.valueAt(i));
1174 }
1175 }
1176 }
1177
1178 private void purgeOldGrants(UserAccounts accounts) {
1179 synchronized (accounts.cacheLock) {
1180 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001181 List<Integer> uids = AccountsDbUtils.findAllUidGrants(db);
1182 for (int uid : uids) {
1183 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
1184 if (packageExists) {
1185 continue;
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001186 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001187 Log.d(TAG, "deleting grants for UID " + uid
1188 + " because its package is no longer installed");
1189 AccountsDbUtils.deleteGrantsByUid(db, uid);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001190 }
1191 }
1192 }
1193
Amith Yamasani13593602012-03-22 16:16:17 -07001194 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -07001195 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -07001196 if (userId < 1) return;
1197
1198 UserAccounts accounts;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001199 boolean userUnlocked;
Amith Yamasani13593602012-03-22 16:16:17 -07001200 synchronized (mUsers) {
1201 accounts = mUsers.get(userId);
1202 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001203 userUnlocked = mLocalUnlockedUsers.get(userId);
1204 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001205 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001206 if (accounts != null) {
1207 synchronized (accounts.cacheLock) {
1208 accounts.openHelper.close();
1209 }
Amith Yamasani13593602012-03-22 16:16:17 -07001210 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001211 Log.i(TAG, "Removing database files for user " + userId);
1212 File dbFile = new File(getDeDatabaseName(userId));
Amith Yamasani13593602012-03-22 16:16:17 -07001213
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001214 deleteDbFileWarnIfFailed(dbFile);
1215 // Remove CE file if user is unlocked, or FBE is not enabled
1216 boolean fbeEnabled = StorageManager.isFileEncryptedNativeOrEmulated();
1217 if (!fbeEnabled || userUnlocked) {
1218 File ceDb = new File(getCeDatabaseName(userId));
1219 if (ceDb.exists()) {
1220 deleteDbFileWarnIfFailed(ceDb);
1221 }
1222 }
1223 }
1224
1225 private static void deleteDbFileWarnIfFailed(File dbFile) {
1226 if (!SQLiteDatabase.deleteDatabase(dbFile)) {
1227 Log.w(TAG, "Database at " + dbFile + " was not deleted successfully");
Amith Yamasani13593602012-03-22 16:16:17 -07001228 }
1229 }
1230
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001231 @VisibleForTesting
1232 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -06001233 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
1234 }
1235
1236 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001237 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1238 Log.v(TAG, "onUserUnlocked " + userId);
1239 }
1240 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001241 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001242 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001243 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001244 syncSharedAccounts(userId);
1245 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001246
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001247 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001248 // Check if there's a shared account that needs to be created as an account
1249 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
1250 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -07001251 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001252 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001253 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001254 : UserHandle.USER_SYSTEM;
1255 if (parentUserId < 0) {
1256 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
1257 return;
1258 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001259 for (Account sa : sharedAccounts) {
1260 if (ArrayUtils.contains(accounts, sa)) continue;
1261 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001262 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001263 }
1264 }
1265
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001266 @Override
1267 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001268 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -07001269 }
1270
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001271 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001272 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001273 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001274 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1275 Log.v(TAG, "getPassword: " + account
1276 + ", caller's uid " + Binder.getCallingUid()
1277 + ", pid " + Binder.getCallingPid());
1278 }
Fred Quintana382601f2010-03-25 12:25:10 -07001279 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001280 int userId = UserHandle.getCallingUserId();
1281 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001282 String msg = String.format(
1283 "uid %s cannot get secrets for accounts of type: %s",
1284 callingUid,
1285 account.type);
1286 throw new SecurityException(msg);
1287 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001288 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001289 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001290 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001291 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001292 } finally {
1293 restoreCallingIdentity(identityToken);
1294 }
1295 }
1296
Amith Yamasani04e0d262012-02-14 11:50:53 -08001297 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -07001298 if (account == null) {
1299 return null;
1300 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001301 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001302 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
1303 return null;
1304 }
Fred Quintana31957f12009-10-21 13:43:10 -07001305
Amith Yamasani04e0d262012-02-14 11:50:53 -08001306 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001307 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001308 return AccountsDbUtils.findAccountPasswordByNameAndType(db, account.name,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001309 account.type);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001310 }
1311 }
1312
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001313 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001314 public String getPreviousName(Account account) {
1315 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1316 Log.v(TAG, "getPreviousName: " + account
1317 + ", caller's uid " + Binder.getCallingUid()
1318 + ", pid " + Binder.getCallingPid());
1319 }
1320 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001321 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001322 long identityToken = clearCallingIdentity();
1323 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001324 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001325 return readPreviousNameInternal(accounts, account);
1326 } finally {
1327 restoreCallingIdentity(identityToken);
1328 }
1329 }
1330
1331 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
1332 if (account == null) {
1333 return null;
1334 }
1335 synchronized (accounts.cacheLock) {
1336 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
1337 if (previousNameRef == null) {
1338 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001339 String previousName = AccountsDbUtils.findAccountPreviousName(db, account);
1340 previousNameRef = new AtomicReference<>(previousName);
1341 accounts.previousNameCache.put(account, previousNameRef);
1342 return previousName;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001343 } else {
1344 return previousNameRef.get();
1345 }
1346 }
1347 }
1348
1349 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001350 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001351 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001352 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001353 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1354 account, key, callingUid, Binder.getCallingPid());
1355 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001356 }
Fred Quintana382601f2010-03-25 12:25:10 -07001357 if (account == null) throw new IllegalArgumentException("account is null");
1358 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001359 int userId = UserHandle.getCallingUserId();
1360 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001361 String msg = String.format(
1362 "uid %s cannot get user data for accounts of type: %s",
1363 callingUid,
1364 account.type);
1365 throw new SecurityException(msg);
1366 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001367 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001368 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1369 return null;
1370 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001371 long identityToken = clearCallingIdentity();
1372 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001373 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00001374 synchronized (accounts.cacheLock) {
1375 if (!accountExistsCacheLocked(accounts, account)) {
1376 return null;
1377 }
1378 return readUserDataInternalLocked(accounts, account, key);
1379 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001380 } finally {
1381 restoreCallingIdentity(identityToken);
1382 }
1383 }
1384
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001385 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001386 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001387 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001388 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1389 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001390 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001391 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001392 + ", pid " + Binder.getCallingPid());
1393 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001394 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001395 if (isCrossUser(callingUid, userId)) {
1396 throw new SecurityException(
1397 String.format(
1398 "User %s tying to get authenticator types for %s" ,
1399 UserHandle.getCallingUserId(),
1400 userId));
1401 }
1402
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001403 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001404 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001405 return getAuthenticatorTypesInternal(userId);
1406
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001407 } finally {
1408 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001409 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001410 }
1411
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001412 /**
1413 * Should only be called inside of a clearCallingIdentity block.
1414 */
1415 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
1416 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1417 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1418 AuthenticatorDescription[] types =
1419 new AuthenticatorDescription[authenticatorCollection.size()];
1420 int i = 0;
1421 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1422 : authenticatorCollection) {
1423 types[i] = authenticator.type;
1424 i++;
1425 }
1426 return types;
1427 }
1428
1429
1430
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001431 private boolean isCrossUser(int callingUid, int userId) {
1432 return (userId != UserHandle.getCallingUserId()
1433 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001434 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001435 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1436 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001437 }
1438
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001439 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001440 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001441 Bundle.setDefusable(extras, true);
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001442 // clears the visible list functionality for this account because this method allows
1443 // default account access to all applications for account.
1444
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001445 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001446 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001447 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001448 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001449 + ", pid " + Binder.getCallingPid());
1450 }
Fred Quintana382601f2010-03-25 12:25:10 -07001451 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001452 int userId = UserHandle.getCallingUserId();
1453 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001454 String msg = String.format(
1455 "uid %s cannot explicitly add accounts of type: %s",
1456 callingUid,
1457 account.type);
1458 throw new SecurityException(msg);
1459 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001460 removeVisibleListFunctionality(account, getUserAccounts(UserHandle.getUserId(callingUid)));
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001461 /*
1462 * Child users are not allowed to add accounts. Only the accounts that are
1463 * shared by the parent profile can be added to child profile.
1464 *
1465 * TODO: Only allow accounts that were shared to be added by
1466 * a limited user.
1467 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001468
Fred Quintana60307342009-03-24 22:48:12 -07001469 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001470 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001471 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001472 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001473 return addAccountInternal(accounts, account, password, extras, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -07001474 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001475 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001476 }
1477 }
1478
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001479 @Override
1480 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001481 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001482 int callingUid = Binder.getCallingUid();
1483 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1484 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001485 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001486 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001487 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1488 final UserAccounts toAccounts = getUserAccounts(userTo);
1489 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001490 if (response != null) {
1491 Bundle result = new Bundle();
1492 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1493 try {
1494 response.onResult(result);
1495 } catch (RemoteException e) {
1496 Slog.w(TAG, "Failed to report error back to the client." + e);
1497 }
1498 }
1499 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001500 }
1501
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001502 Slog.d(TAG, "Copying account " + account.name
1503 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001504 long identityToken = clearCallingIdentity();
1505 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001506 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001507 false /* stripAuthTokenFromResult */, account.name,
1508 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001509 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001510 protected String toDebugString(long now) {
1511 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1512 + ", " + account.type;
1513 }
1514
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001515 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001516 public void run() throws RemoteException {
1517 mAuthenticator.getAccountCredentialsForCloning(this, account);
1518 }
1519
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001520 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001521 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001522 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001523 if (result != null
1524 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1525 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001526 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001527 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001528 super.onResult(result);
1529 }
1530 }
1531 }.bind();
1532 } finally {
1533 restoreCallingIdentity(identityToken);
1534 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001535 }
1536
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001537 @Override
1538 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001539 final int callingUid = Binder.getCallingUid();
1540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1541 String msg = String.format(
1542 "accountAuthenticated( account: %s, callerUid: %s)",
1543 account,
1544 callingUid);
1545 Log.v(TAG, msg);
1546 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001547 if (account == null) {
1548 throw new IllegalArgumentException("account is null");
1549 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001550 int userId = UserHandle.getCallingUserId();
1551 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001552 String msg = String.format(
1553 "uid %s cannot notify authentication for accounts of type: %s",
1554 callingUid,
1555 account.type);
1556 throw new SecurityException(msg);
1557 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001558
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001559 if (!canUserModifyAccounts(userId, callingUid) ||
1560 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001561 return false;
1562 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001563
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001564 long identityToken = clearCallingIdentity();
1565 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001566 UserAccounts accounts = getUserAccounts(userId);
1567 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001568 } finally {
1569 restoreCallingIdentity(identityToken);
1570 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001571 }
1572
1573 private boolean updateLastAuthenticatedTime(Account account) {
1574 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001575 synchronized (accounts.cacheLock) {
1576 final ContentValues values = new ContentValues();
1577 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
1578 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1579 int i = db.update(
1580 TABLE_ACCOUNTS,
1581 values,
1582 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
1583 new String[] {
1584 account.name, account.type
1585 });
1586 if (i > 0) {
1587 return true;
1588 }
1589 }
1590 return false;
1591 }
1592
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001593 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001594 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1595 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001596 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001597 long id = clearCallingIdentity();
1598 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001599 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001600 false /* stripAuthTokenFromResult */, account.name,
1601 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001602 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001603 protected String toDebugString(long now) {
1604 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1605 + ", " + account.type;
1606 }
1607
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001608 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001609 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001610 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001611 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001612 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -07001613 for (Account acc : getAccounts(parentUserId,
1614 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001615 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001616 mAuthenticator.addAccountFromCredentials(
1617 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001618 break;
1619 }
1620 }
1621 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001622 }
1623
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001624 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001625 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001626 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001627 // TODO: Anything to do if if succedded?
1628 // TODO: If it failed: Show error notification? Should we remove the shadow
1629 // account to avoid retries?
1630 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001631 }
1632
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001633 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001634 public void onError(int errorCode, String errorMessage) {
1635 super.onError(errorCode, errorMessage);
1636 // TODO: Show error notification to user
1637 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1638 }
1639
1640 }.bind();
1641 } finally {
1642 restoreCallingIdentity(id);
1643 }
1644 }
1645
Amith Yamasani04e0d262012-02-14 11:50:53 -08001646 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001647 Bundle extras, int callingUid) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001648 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001649 if (account == null) {
1650 return false;
1651 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001652 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001653 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1654 + " is locked. callingUid=" + callingUid);
1655 return false;
1656 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001657 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001658 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001659 db.beginTransaction();
1660 try {
1661 long numMatches = DatabaseUtils.longForQuery(db,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001662 "select count(*) from " + CE_TABLE_ACCOUNTS
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001663 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1664 new String[]{account.name, account.type});
1665 if (numMatches > 0) {
1666 Log.w(TAG, "insertAccountIntoDatabase: " + account
1667 + ", skipping since the account already exists");
1668 return false;
1669 }
1670 ContentValues values = new ContentValues();
1671 values.put(ACCOUNTS_NAME, account.name);
1672 values.put(ACCOUNTS_TYPE, account.type);
1673 values.put(ACCOUNTS_PASSWORD, password);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001674 long accountId = db.insert(CE_TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001675 if (accountId < 0) {
1676 Log.w(TAG, "insertAccountIntoDatabase: " + account
1677 + ", skipping the DB insert failed");
1678 return false;
1679 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001680 // Insert into DE table
1681 values = new ContentValues();
1682 values.put(ACCOUNTS_ID, accountId);
1683 values.put(ACCOUNTS_NAME, account.name);
1684 values.put(ACCOUNTS_TYPE, account.type);
1685 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS,
1686 System.currentTimeMillis());
1687 if (db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values) < 0) {
1688 Log.w(TAG, "insertAccountIntoDatabase: " + account
1689 + ", skipping the DB insert failed");
1690 return false;
1691 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001692 if (extras != null) {
1693 for (String key : extras.keySet()) {
1694 final String value = extras.getString(key);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001695 if (AccountsDbUtils.insertExtra(db, accountId, key, value) < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001696 Log.w(TAG, "insertAccountIntoDatabase: " + account
1697 + ", skipping since insertExtra failed for key " + key);
1698 return false;
1699 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001700 }
1701 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001702 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001703
1704 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1705 accounts, callingUid);
1706
Amith Yamasani04e0d262012-02-14 11:50:53 -08001707 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001708 } finally {
1709 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001710 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001711 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001712 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1713 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001714 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001715
1716 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1717 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001718 return true;
1719 }
1720
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001721 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001722 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001723 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001724 }
1725 }
1726
Amith Yamasani5be347b2013-03-31 17:44:31 -07001727 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001728 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001729 * running, then clone the account too.
1730 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001731 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001732 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001733 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001734 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001735 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001736 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001737 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001738 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001739 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1740 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001741 }
1742 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001743 }
1744 }
1745
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001746 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001747 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001748 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001749 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001750 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1751 Log.v(TAG, "hasFeatures: " + account
1752 + ", response " + response
1753 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001754 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001755 + ", pid " + Binder.getCallingPid());
1756 }
Fred Quintana382601f2010-03-25 12:25:10 -07001757 if (response == null) throw new IllegalArgumentException("response is null");
1758 if (account == null) throw new IllegalArgumentException("account is null");
1759 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001760 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001761 checkReadAccountsPermitted(callingUid, account.type, userId,
1762 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001763
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001764 long identityToken = clearCallingIdentity();
1765 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001766 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001767 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001768 } finally {
1769 restoreCallingIdentity(identityToken);
1770 }
1771 }
1772
1773 private class TestFeaturesSession extends Session {
1774 private final String[] mFeatures;
1775 private final Account mAccount;
1776
Amith Yamasani04e0d262012-02-14 11:50:53 -08001777 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001778 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001779 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001780 true /* stripAuthTokenFromResult */, account.name,
1781 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001782 mFeatures = features;
1783 mAccount = account;
1784 }
1785
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001786 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001787 public void run() throws RemoteException {
1788 try {
1789 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1790 } catch (RemoteException e) {
1791 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1792 }
1793 }
1794
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001795 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001796 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001797 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001798 IAccountManagerResponse response = getResponseAndClose();
1799 if (response != null) {
1800 try {
1801 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001802 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001803 return;
1804 }
Fred Quintana56285a62010-12-02 14:20:51 -08001805 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1806 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1807 + response);
1808 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001809 final Bundle newResult = new Bundle();
1810 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1811 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1812 response.onResult(newResult);
1813 } catch (RemoteException e) {
1814 // if the caller is dead then there is no one to care about remote exceptions
1815 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1816 Log.v(TAG, "failure while notifying response", e);
1817 }
1818 }
1819 }
1820 }
1821
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001822 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001823 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001824 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001825 + ", " + mAccount
1826 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1827 }
1828 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001829
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001830 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001831 public void renameAccount(
1832 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001833 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001834 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1835 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001836 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001837 + ", pid " + Binder.getCallingPid());
1838 }
1839 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001840 int userId = UserHandle.getCallingUserId();
1841 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001842 String msg = String.format(
1843 "uid %s cannot rename accounts of type: %s",
1844 callingUid,
1845 accountToRename.type);
1846 throw new SecurityException(msg);
1847 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001848 long identityToken = clearCallingIdentity();
1849 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001850 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001851 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001852 Bundle result = new Bundle();
1853 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1854 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1855 try {
1856 response.onResult(result);
1857 } catch (RemoteException e) {
1858 Log.w(TAG, e.getMessage());
1859 }
1860 } finally {
1861 restoreCallingIdentity(identityToken);
1862 }
1863 }
1864
1865 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001866 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001867 Account resultAccount = null;
1868 /*
1869 * Cancel existing notifications. Let authenticators
1870 * re-post notifications as required. But we don't know if
1871 * the authenticators have bound their notifications to
1872 * now stale account name data.
1873 *
1874 * With a rename api, we might not need to do this anymore but it
1875 * shouldn't hurt.
1876 */
1877 cancelNotification(
1878 getSigninRequiredNotificationId(accounts, accountToRename),
1879 new UserHandle(accounts.userId));
1880 synchronized(accounts.credentialsPermissionNotificationIds) {
1881 for (Pair<Pair<Account, String>, Integer> pair:
1882 accounts.credentialsPermissionNotificationIds.keySet()) {
1883 if (accountToRename.equals(pair.first.first)) {
1884 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1885 cancelNotification(id, new UserHandle(accounts.userId));
1886 }
1887 }
1888 }
1889 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001890 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001891 db.beginTransaction();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001892 Account renamedAccount = new Account(newName, accountToRename.type);
1893 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001894 final long accountId = AccountsDbUtils.findAccountId(db, accountToRename);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001895 if (accountId >= 0) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001896 final ContentValues values = new ContentValues();
1897 values.put(ACCOUNTS_NAME, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001898 final String[] argsAccountId = { String.valueOf(accountId) };
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001899 db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1900 // Update NAME/PREVIOUS_NAME in DE accounts table
1901 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001902 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1903 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001904 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1905 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001906 }
1907 } finally {
1908 db.endTransaction();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001909 }
1910 /*
1911 * Database transaction was successful. Clean up cached
1912 * data associated with the account in the user profile.
1913 */
1914 insertAccountIntoCacheLocked(accounts, renamedAccount);
1915 /*
1916 * Extract the data and token caches before removing the
1917 * old account to preserve the user data associated with
1918 * the account.
1919 */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001920 Map<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1921 Map<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001922 removeAccountFromCacheLocked(accounts, accountToRename);
1923 /*
1924 * Update the cached data associated with the renamed
1925 * account.
1926 */
1927 accounts.userDataCache.put(renamedAccount, tmpData);
1928 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1929 accounts.previousNameCache.put(
1930 renamedAccount,
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001931 new AtomicReference<>(accountToRename.name));
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001932 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001933
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001934 int parentUserId = accounts.userId;
1935 if (canHaveProfile(parentUserId)) {
1936 /*
1937 * Owner or system user account was renamed, rename the account for
1938 * those users with which the account was shared.
1939 */
1940 List<UserInfo> users = getUserManager().getUsers(true);
1941 for (UserInfo user : users) {
1942 if (user.isRestricted()
1943 && (user.restrictedProfileParentId == parentUserId)) {
1944 renameSharedAccountAsUser(accountToRename, newName, user.id);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001945 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001946 }
1947 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001948 sendAccountsChangedBroadcast(accounts.userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001949 }
1950 return resultAccount;
1951 }
1952
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001953 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001954 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001955 return userInfo != null && userInfo.canHaveProfile();
1956 }
1957
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001958 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001959 public void removeAccount(IAccountManagerResponse response, Account account,
1960 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001961 removeAccountAsUser(
1962 response,
1963 account,
1964 expectActivityLaunch,
1965 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001966 }
1967
1968 @Override
1969 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001970 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001971 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001972 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1973 Log.v(TAG, "removeAccount: " + account
1974 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001975 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001976 + ", pid " + Binder.getCallingPid()
1977 + ", for user id " + userId);
1978 }
1979 if (response == null) throw new IllegalArgumentException("response is null");
1980 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001981 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001982 if (isCrossUser(callingUid, userId)) {
1983 throw new SecurityException(
1984 String.format(
1985 "User %s tying remove account for %s" ,
1986 UserHandle.getCallingUserId(),
1987 userId));
1988 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001989 /*
1990 * Only the system or authenticator should be allowed to remove accounts for that
1991 * authenticator. This will let users remove accounts (via Settings in the system) but not
1992 * arbitrary applications (like competing authenticators).
1993 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001994 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001995 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1996 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001997 String msg = String.format(
1998 "uid %s cannot remove accounts of type: %s",
1999 callingUid,
2000 account.type);
2001 throw new SecurityException(msg);
2002 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002003 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002004 try {
2005 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2006 "User cannot modify accounts");
2007 } catch (RemoteException re) {
2008 }
2009 return;
2010 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002011 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002012 try {
2013 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2014 "User cannot modify accounts of this type (policy).");
2015 } catch (RemoteException re) {
2016 }
2017 return;
2018 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002019 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002020 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002021 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002022 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002023 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08002024 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002025 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002026 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002027 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002028 }
2029 }
2030 }
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002031 SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002032 final long accountId = AccountsDbUtils.findAccountId(db, account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002033 logRecord(
2034 db,
2035 DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE,
2036 TABLE_ACCOUNTS,
2037 accountId,
2038 accounts,
2039 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002040 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002041 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
2042 } finally {
2043 restoreCallingIdentity(identityToken);
2044 }
2045 }
2046
2047 @Override
2048 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002049 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002050 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2051 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002052 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002053 + ", pid " + Binder.getCallingPid());
2054 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002055 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002056 if (account == null) {
2057 /*
2058 * Null accounts should result in returning false, as per
2059 * AccountManage.addAccountExplicitly(...) java doc.
2060 */
2061 Log.e(TAG, "account is null");
2062 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002063 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002064 String msg = String.format(
2065 "uid %s cannot explicitly add accounts of type: %s",
2066 callingUid,
2067 account.type);
2068 throw new SecurityException(msg);
2069 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07002070 removeVisibleListFunctionality(account, getUserAccounts(UserHandle.getUserId(callingUid)));
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002071 UserAccounts accounts = getUserAccountsForCaller();
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002072 SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002073 final long accountId = AccountsDbUtils.findAccountId(db, account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002074 logRecord(
2075 db,
2076 DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE,
2077 TABLE_ACCOUNTS,
2078 accountId,
2079 accounts,
2080 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002081 long identityToken = clearCallingIdentity();
2082 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002083 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002084 } finally {
2085 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07002086 }
Fred Quintana60307342009-03-24 22:48:12 -07002087 }
2088
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002089 private class RemoveAccountSession extends Session {
2090 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002091 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002092 Account account, boolean expectActivityLaunch) {
2093 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002094 true /* stripAuthTokenFromResult */, account.name,
2095 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002096 mAccount = account;
2097 }
2098
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002099 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002100 protected String toDebugString(long now) {
2101 return super.toDebugString(now) + ", removeAccount"
2102 + ", account " + mAccount;
2103 }
2104
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002105 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002106 public void run() throws RemoteException {
2107 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
2108 }
2109
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002110 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002111 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002112 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002113 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
2114 && !result.containsKey(AccountManager.KEY_INTENT)) {
2115 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002116 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002117 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002118 }
2119 IAccountManagerResponse response = getResponseAndClose();
2120 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002121 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2122 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2123 + response);
2124 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002125 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002126 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002127 try {
2128 response.onResult(result2);
2129 } catch (RemoteException e) {
2130 // ignore
2131 }
2132 }
2133 }
2134 super.onResult(result);
2135 }
2136 }
2137
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002138 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002139 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002140 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002141 }
2142
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002143 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002144 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002145 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002146 if (!userUnlocked) {
2147 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
2148 + " is still locked. CE data will be removed later");
2149 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002150 synchronized (accounts.cacheLock) {
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002151 final SQLiteDatabase db = userUnlocked
2152 ? accounts.openHelper.getWritableDatabaseUserIsUnlocked()
2153 : accounts.openHelper.getWritableDatabase();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002154 db.beginTransaction();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002155 // Set to a dummy value, this will only be used if the database
2156 // transaction succeeds.
2157 long accountId = -1;
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002158 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002159 accountId = AccountsDbUtils.findAccountId(db, account);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002160 if (accountId >= 0) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002161 AccountsDbUtils.deleteAccount(db, accountId);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002162 if (userUnlocked) {
2163 // Delete from CE table
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002164 AccountsDbUtils.deleteCeAccount(db, accountId);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002165 }
2166 db.setTransactionSuccessful();
2167 isChanged = true;
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002168 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002169 } finally {
2170 db.endTransaction();
2171 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002172 if (isChanged) {
2173 removeAccountFromCacheLocked(accounts, account);
2174 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occured.
2175 sendAccountsChangedBroadcast(accounts.userId);
2176 String action = userUnlocked ? DebugDbHelper.ACTION_ACCOUNT_REMOVE
2177 : DebugDbHelper.ACTION_ACCOUNT_REMOVE_DE;
2178 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts);
2179 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002180 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002181 long id = Binder.clearCallingIdentity();
2182 try {
2183 int parentUserId = accounts.userId;
2184 if (canHaveProfile(parentUserId)) {
2185 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002186 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002187 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002188 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002189 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002190 }
2191 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002192 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002193 } finally {
2194 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002195 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002196 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002197 }
2198
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002199 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002200 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002201 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002202 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2203 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002204 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002205 + ", pid " + Binder.getCallingPid());
2206 }
Fred Quintana382601f2010-03-25 12:25:10 -07002207 if (accountType == null) throw new IllegalArgumentException("accountType is null");
2208 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002209 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002210 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002211 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002212 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002213 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002214 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002215 db.beginTransaction();
2216 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002217 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002218 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002219 db.setTransactionSuccessful();
2220 } finally {
2221 db.endTransaction();
2222 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002223 }
Fred Quintana60307342009-03-24 22:48:12 -07002224 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002225 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002226 }
2227 }
2228
Carlos Valdivia91979be2015-05-22 14:11:35 -07002229 private void invalidateCustomTokenLocked(
2230 UserAccounts accounts,
2231 String accountType,
2232 String authToken) {
2233 if (authToken == null || accountType == null) {
2234 return;
2235 }
2236 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002237 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002238 }
2239
Amith Yamasani04e0d262012-02-14 11:50:53 -08002240 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
2241 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002242 if (authToken == null || accountType == null) {
2243 return;
2244 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002245 Cursor cursor = AccountsDbUtils.findAuthtokenForAllAccounts(db, accountType, authToken);
Fred Quintana33269202009-04-20 16:05:10 -07002246 try {
2247 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002248 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002249 String accountName = cursor.getString(1);
2250 String authTokenType = cursor.getString(2);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002251 AccountsDbUtils.deleteAuthToken(db, authTokenId);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002252 writeAuthTokenIntoCacheLocked(
2253 accounts,
2254 db,
2255 new Account(accountName, accountType),
2256 authTokenType,
2257 null);
Fred Quintana60307342009-03-24 22:48:12 -07002258 }
Fred Quintana33269202009-04-20 16:05:10 -07002259 } finally {
2260 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002261 }
2262 }
2263
Carlos Valdivia91979be2015-05-22 14:11:35 -07002264 private void saveCachedToken(
2265 UserAccounts accounts,
2266 Account account,
2267 String callerPkg,
2268 byte[] callerSigDigest,
2269 String tokenType,
2270 String token,
2271 long expiryMillis) {
2272
2273 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2274 return;
2275 }
2276 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002277 UserHandle.of(accounts.userId));
Carlos Valdivia91979be2015-05-22 14:11:35 -07002278 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002279 accounts.accountTokenCaches.put(
2280 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002281 }
2282 }
2283
Amith Yamasani04e0d262012-02-14 11:50:53 -08002284 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2285 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002286 if (account == null || type == null) {
2287 return false;
2288 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002289 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002290 UserHandle.of(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002291 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002292 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002293 db.beginTransaction();
2294 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002295 long accountId = AccountsDbUtils.findAccountId(db, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002296 if (accountId < 0) {
2297 return false;
2298 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002299 AccountsDbUtils.deleteAuthtokensByAccountIdAndType(db, accountId, type);
2300 if (AccountsDbUtils.insertAuthToken(db, accountId, type, authToken) >= 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002301 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002302 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002303 return true;
2304 }
Fred Quintana33269202009-04-20 16:05:10 -07002305 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002306 } finally {
2307 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07002308 }
Fred Quintana60307342009-03-24 22:48:12 -07002309 }
2310 }
2311
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002312 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002313 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002314 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002315 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2316 Log.v(TAG, "peekAuthToken: " + account
2317 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002318 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002319 + ", pid " + Binder.getCallingPid());
2320 }
Fred Quintana382601f2010-03-25 12:25:10 -07002321 if (account == null) throw new IllegalArgumentException("account is null");
2322 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002323 int userId = UserHandle.getCallingUserId();
2324 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002325 String msg = String.format(
2326 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2327 callingUid,
2328 account.type);
2329 throw new SecurityException(msg);
2330 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002331 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002332 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2333 + callingUid);
2334 return null;
2335 }
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(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002339 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002340 } finally {
2341 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002342 }
Fred Quintana60307342009-03-24 22:48:12 -07002343 }
2344
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002345 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002346 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002347 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002348 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2349 Log.v(TAG, "setAuthToken: " + account
2350 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002351 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002352 + ", pid " + Binder.getCallingPid());
2353 }
Fred Quintana382601f2010-03-25 12:25:10 -07002354 if (account == null) throw new IllegalArgumentException("account is null");
2355 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002356 int userId = UserHandle.getCallingUserId();
2357 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002358 String msg = String.format(
2359 "uid %s cannot set auth tokens associated with accounts of type: %s",
2360 callingUid,
2361 account.type);
2362 throw new SecurityException(msg);
2363 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002364 long identityToken = clearCallingIdentity();
2365 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002366 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002367 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002368 } finally {
2369 restoreCallingIdentity(identityToken);
2370 }
Fred Quintana60307342009-03-24 22:48:12 -07002371 }
2372
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002373 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002374 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002375 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002376 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2377 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002378 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002379 + ", pid " + Binder.getCallingPid());
2380 }
Fred Quintana382601f2010-03-25 12:25:10 -07002381 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002382 int userId = UserHandle.getCallingUserId();
2383 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002384 String msg = String.format(
2385 "uid %s cannot set secrets for accounts of type: %s",
2386 callingUid,
2387 account.type);
2388 throw new SecurityException(msg);
2389 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002390 long identityToken = clearCallingIdentity();
2391 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002392 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002393 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002394 } finally {
2395 restoreCallingIdentity(identityToken);
2396 }
Fred Quintana60307342009-03-24 22:48:12 -07002397 }
2398
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002399 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2400 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002401 if (account == null) {
2402 return;
2403 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002404 boolean isChanged = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002405 synchronized (accounts.cacheLock) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002406 final SQLiteDatabase db = accounts.openHelper.getWritableDatabaseUserIsUnlocked();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002407 db.beginTransaction();
2408 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002409 final long accountId = AccountsDbUtils.findAccountId(db, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002410 if (accountId >= 0) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002411 AccountsDbUtils.updateAccountPassword(db, accountId, password);
2412 AccountsDbUtils.deleteAuthTokensByAccountId(db, accountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002413 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002414 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002415 db.setTransactionSuccessful();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002416 // If there is an account whose password will be updated and the database
2417 // transactions succeed, then we say that a change has occured. Even if the
2418 // new password is the same as the old and there were no authtokens to delete.
2419 isChanged = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002420 String action = (password == null || password.length() == 0) ?
2421 DebugDbHelper.ACTION_CLEAR_PASSWORD
2422 : DebugDbHelper.ACTION_SET_PASSWORD;
2423 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08002424 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002425 } finally {
2426 db.endTransaction();
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002427 if (isChanged) {
2428 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2429 sendAccountsChangedBroadcast(accounts.userId);
2430 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002431 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002432 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002433 }
2434
Amith Yamasani04e0d262012-02-14 11:50:53 -08002435 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08002436 Log.i(TAG, "the accounts changed, sending broadcast of "
2437 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07002438 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07002439 }
2440
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002441 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002442 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002443 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002444 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2445 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002446 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002447 + ", pid " + Binder.getCallingPid());
2448 }
Fred Quintana382601f2010-03-25 12:25:10 -07002449 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002450 int userId = UserHandle.getCallingUserId();
2451 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002452 String msg = String.format(
2453 "uid %s cannot clear passwords for accounts of type: %s",
2454 callingUid,
2455 account.type);
2456 throw new SecurityException(msg);
2457 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002458 long identityToken = clearCallingIdentity();
2459 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002460 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002461 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002462 } finally {
2463 restoreCallingIdentity(identityToken);
2464 }
Fred Quintana60307342009-03-24 22:48:12 -07002465 }
2466
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002467 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002468 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002469 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002470 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2471 Log.v(TAG, "setUserData: " + account
2472 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002473 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002474 + ", pid " + Binder.getCallingPid());
2475 }
Fred Quintana382601f2010-03-25 12:25:10 -07002476 if (key == null) throw new IllegalArgumentException("key is null");
2477 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002478 int userId = UserHandle.getCallingUserId();
2479 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002480 String msg = String.format(
2481 "uid %s cannot set user data for accounts of type: %s",
2482 callingUid,
2483 account.type);
2484 throw new SecurityException(msg);
2485 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002486 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002487 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002488 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002489 synchronized (accounts.cacheLock) {
2490 if (!accountExistsCacheLocked(accounts, account)) {
2491 return;
2492 }
2493 setUserdataInternalLocked(accounts, account, key, value);
2494 }
Fred Quintana60307342009-03-24 22:48:12 -07002495 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002496 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002497 }
2498 }
2499
Simranjit Kohli858511c2016-03-10 18:36:11 +00002500 private boolean accountExistsCacheLocked(UserAccounts accounts, Account account) {
2501 if (accounts.accountCache.containsKey(account.type)) {
2502 for (Account acc : accounts.accountCache.get(account.type)) {
2503 if (acc.name.equals(account.name)) {
2504 return true;
2505 }
2506 }
2507 }
2508 return false;
2509 }
2510
2511 private void setUserdataInternalLocked(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002512 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07002513 if (account == null || key == null) {
2514 return;
2515 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002516 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
2517 db.beginTransaction();
2518 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002519 long accountId = AccountsDbUtils.findAccountId(db, account);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002520 if (accountId < 0) {
2521 return;
2522 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002523 long extrasId = AccountsDbUtils.findExtrasIdByAccountId(db, accountId, key);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002524 if (extrasId < 0) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002525 extrasId = AccountsDbUtils.insertExtra(db, accountId, key, value);
Simranjit Kohli858511c2016-03-10 18:36:11 +00002526 if (extrasId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002527 return;
2528 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002529 } else if (!AccountsDbUtils.updateExtra(db, extrasId, value)) {
2530 return;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002531 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002532 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
2533 db.setTransactionSuccessful();
2534 } finally {
2535 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002536 }
2537 }
2538
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002539 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002540 if (result == null) {
2541 Log.e(TAG, "the result is unexpectedly null", new Exception());
2542 }
2543 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2544 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2545 + response);
2546 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002547 try {
2548 response.onResult(result);
2549 } catch (RemoteException e) {
2550 // if the caller is dead then there is no one to care about remote
2551 // exceptions
2552 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2553 Log.v(TAG, "failure while notifying response", e);
2554 }
2555 }
2556 }
2557
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002558 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002559 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2560 final String authTokenType)
2561 throws RemoteException {
2562 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002563 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
2564
Fred Quintanad9640ec2012-05-23 12:37:00 -07002565 final int callingUid = getCallingUid();
2566 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07002567 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002568 throw new SecurityException("can only call from system");
2569 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002570 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002571 long identityToken = clearCallingIdentity();
2572 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002573 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002574 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2575 false /* stripAuthTokenFromResult */, null /* accountName */,
2576 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002577 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002578 protected String toDebugString(long now) {
2579 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002580 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002581 + ", authTokenType " + authTokenType;
2582 }
2583
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002584 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002585 public void run() throws RemoteException {
2586 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2587 }
2588
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002589 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002590 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002591 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002592 if (result != null) {
2593 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2594 Bundle bundle = new Bundle();
2595 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2596 super.onResult(bundle);
2597 return;
2598 } else {
2599 super.onResult(result);
2600 }
2601 }
2602 }.bind();
2603 } finally {
2604 restoreCallingIdentity(identityToken);
2605 }
2606 }
2607
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002608 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002609 public void getAuthToken(
2610 IAccountManagerResponse response,
2611 final Account account,
2612 final String authTokenType,
2613 final boolean notifyOnAuthFailure,
2614 final boolean expectActivityLaunch,
2615 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002616 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002617 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2618 Log.v(TAG, "getAuthToken: " + account
2619 + ", response " + response
2620 + ", authTokenType " + authTokenType
2621 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2622 + ", expectActivityLaunch " + expectActivityLaunch
2623 + ", caller's uid " + Binder.getCallingUid()
2624 + ", pid " + Binder.getCallingPid());
2625 }
Fred Quintana382601f2010-03-25 12:25:10 -07002626 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002627 try {
2628 if (account == null) {
2629 Slog.w(TAG, "getAuthToken called with null account");
2630 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2631 return;
2632 }
2633 if (authTokenType == null) {
2634 Slog.w(TAG, "getAuthToken called with null authTokenType");
2635 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2636 return;
2637 }
2638 } catch (RemoteException e) {
2639 Slog.w(TAG, "Failed to report error back to the client." + e);
2640 return;
2641 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002642 int userId = UserHandle.getCallingUserId();
2643 long ident = Binder.clearCallingIdentity();
2644 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002645 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002646 try {
2647 accounts = getUserAccounts(userId);
2648 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2649 AuthenticatorDescription.newKey(account.type), accounts.userId);
2650 } finally {
2651 Binder.restoreCallingIdentity(ident);
2652 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002653
Costin Manolachea40c6302010-12-13 14:50:45 -08002654 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002655 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002656
2657 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002658 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002659 final boolean permissionGranted =
2660 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002661
Carlos Valdivia91979be2015-05-22 14:11:35 -07002662 // Get the calling package. We will use it for the purpose of caching.
2663 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002664 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002665 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002666 try {
2667 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2668 } finally {
2669 Binder.restoreCallingIdentity(ident);
2670 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002671 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2672 String msg = String.format(
2673 "Uid %s is attempting to illegally masquerade as package %s!",
2674 callerUid,
2675 callerPkg);
2676 throw new SecurityException(msg);
2677 }
2678
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002679 // let authenticator know the identity of the caller
2680 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2681 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002682
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002683 if (notifyOnAuthFailure) {
2684 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002685 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002686
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002687 long identityToken = clearCallingIdentity();
2688 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002689 // Distill the caller's package signatures into a single digest.
2690 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2691
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002692 // if the caller has permission, do the peek. otherwise go the more expensive
2693 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002694 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002695 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002696 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002697 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002698 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2699 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2700 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002701 onResult(response, result);
2702 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002703 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002704 }
2705
Carlos Valdivia91979be2015-05-22 14:11:35 -07002706 if (customTokens) {
2707 /*
2708 * Look up tokens in the new cache only if the loginOptions don't have parameters
2709 * outside of those expected to be injected by the AccountManager, e.g.
2710 * ANDORID_PACKAGE_NAME.
2711 */
2712 String token = readCachedTokenInternal(
2713 accounts,
2714 account,
2715 authTokenType,
2716 callerPkg,
2717 callerPkgSigDigest);
2718 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002719 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2720 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2721 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002722 Bundle result = new Bundle();
2723 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2724 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2725 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2726 onResult(response, result);
2727 return;
2728 }
2729 }
2730
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002731 new Session(
2732 accounts,
2733 response,
2734 account.type,
2735 expectActivityLaunch,
2736 false /* stripAuthTokenFromResult */,
2737 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002738 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002739 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002740 protected String toDebugString(long now) {
2741 if (loginOptions != null) loginOptions.keySet();
2742 return super.toDebugString(now) + ", getAuthToken"
2743 + ", " + account
2744 + ", authTokenType " + authTokenType
2745 + ", loginOptions " + loginOptions
2746 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2747 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002748
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002749 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002750 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002751 // If the caller doesn't have permission then create and return the
2752 // "grant permission" intent instead of the "getAuthToken" intent.
2753 if (!permissionGranted) {
2754 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2755 } else {
2756 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2757 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002758 }
2759
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002760 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002761 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002762 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002763 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002764 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002765 Intent intent = newGrantCredentialsPermissionIntent(
2766 account,
2767 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002768 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002769 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002770 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002771 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002772 onResult(bundle);
2773 return;
2774 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002775 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002776 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002777 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2778 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002779 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002780 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002781 "the type and name should not be empty");
2782 return;
2783 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002784 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002785 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002786 saveAuthTokenToDatabase(
2787 mAccounts,
2788 resultAccount,
2789 authTokenType,
2790 authToken);
2791 }
2792 long expiryMillis = result.getLong(
2793 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2794 if (customTokens
2795 && expiryMillis > System.currentTimeMillis()) {
2796 saveCachedToken(
2797 mAccounts,
2798 account,
2799 callerPkg,
2800 callerPkgSigDigest,
2801 authTokenType,
2802 authToken,
2803 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002804 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002805 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002806
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002807 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002808 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002809 /*
2810 * Make sure that the supplied intent is owned by the authenticator
2811 * giving it to the system. Otherwise a malicious authenticator could
2812 * have users launching arbitrary activities by tricking users to
2813 * interact with malicious notifications.
2814 */
2815 checkKeyIntent(
2816 Binder.getCallingUid(),
2817 intent);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002818 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002819 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002820 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002821 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002822 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002823 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002824 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002825 }.bind();
2826 } finally {
2827 restoreCallingIdentity(identityToken);
2828 }
Fred Quintana60307342009-03-24 22:48:12 -07002829 }
2830
Carlos Valdivia91979be2015-05-22 14:11:35 -07002831 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2832 MessageDigest digester;
2833 try {
2834 digester = MessageDigest.getInstance("SHA-256");
2835 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2836 callerPkg, PackageManager.GET_SIGNATURES);
2837 for (Signature sig : pkgInfo.signatures) {
2838 digester.update(sig.toByteArray());
2839 }
2840 } catch (NoSuchAlgorithmException x) {
2841 Log.wtf(TAG, "SHA-256 should be available", x);
2842 digester = null;
2843 } catch (NameNotFoundException e) {
2844 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2845 digester = null;
2846 }
2847 return (digester == null) ? null : digester.digest();
2848 }
2849
Dianne Hackborn41203752012-08-31 14:05:51 -07002850 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2851 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002852 int uid = intent.getIntExtra(
2853 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2854 String authTokenType = intent.getStringExtra(
2855 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002856 final String titleAndSubtitle =
2857 mContext.getString(R.string.permission_request_notification_with_subtitle,
2858 account.name);
2859 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002860 String title = titleAndSubtitle;
2861 String subtitle = "";
2862 if (index > 0) {
2863 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002864 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002865 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002866 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002867 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002868 Notification n = new Notification.Builder(contextForUser)
2869 .setSmallIcon(android.R.drawable.stat_sys_warning)
2870 .setWhen(0)
2871 .setColor(contextForUser.getColor(
2872 com.android.internal.R.color.system_notification_accent_color))
2873 .setContentTitle(title)
2874 .setContentText(subtitle)
2875 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2876 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2877 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002878 installNotification(getCredentialPermissionNotificationId(
2879 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002880 }
2881
Costin Manolache5f383ad92010-12-02 16:44:46 -08002882 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002883 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002884
2885 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002886 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002887 // Since it was set in Eclair+ we can't change it without breaking apps using
2888 // the intent from a non-Activity context.
2889 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002890 intent.addCategory(
2891 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002892
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002893 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002894 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2895 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002896 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002897
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002898 return intent;
2899 }
2900
2901 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2902 int uid) {
2903 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002904 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002905 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002906 final Pair<Pair<Account, String>, Integer> key =
2907 new Pair<Pair<Account, String>, Integer>(
2908 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002909 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002910 if (id == null) {
2911 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002912 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002913 }
2914 }
2915 return id;
2916 }
2917
Amith Yamasani04e0d262012-02-14 11:50:53 -08002918 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002919 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002920 synchronized (accounts.signinRequiredNotificationIds) {
2921 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002922 if (id == null) {
2923 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002924 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002925 }
2926 }
2927 return id;
2928 }
2929
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002930 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002931 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002932 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002933 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002934 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002935 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2936 Log.v(TAG, "addAccount: accountType " + accountType
2937 + ", response " + response
2938 + ", authTokenType " + authTokenType
2939 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2940 + ", expectActivityLaunch " + expectActivityLaunch
2941 + ", caller's uid " + Binder.getCallingUid()
2942 + ", pid " + Binder.getCallingPid());
2943 }
Fred Quintana382601f2010-03-25 12:25:10 -07002944 if (response == null) throw new IllegalArgumentException("response is null");
2945 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002946
Amith Yamasani71e6c692013-03-24 17:39:28 -07002947 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002948 final int uid = Binder.getCallingUid();
2949 final int userId = UserHandle.getUserId(uid);
2950 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002951 try {
2952 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2953 "User is not allowed to add an account!");
2954 } catch (RemoteException re) {
2955 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002956 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002957 return;
2958 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002959 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002960 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002961 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2962 "User cannot modify accounts of this type (policy).");
2963 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002964 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002965 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2966 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002967 return;
2968 }
2969
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002970 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002971 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2972 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2973 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2974
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002975 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002976 long identityToken = clearCallingIdentity();
2977 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002978 UserAccounts accounts = getUserAccounts(usrId);
2979 logRecordWithUid(
2980 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002981 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002982 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002983 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002984 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002985 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002986 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002987 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002988 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002989
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002990 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002991 protected String toDebugString(long now) {
2992 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002993 + ", accountType " + accountType
2994 + ", requiredFeatures "
2995 + (requiredFeatures != null
2996 ? TextUtils.join(",", requiredFeatures)
2997 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002998 }
2999 }.bind();
3000 } finally {
3001 restoreCallingIdentity(identityToken);
3002 }
Fred Quintana60307342009-03-24 22:48:12 -07003003 }
3004
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003005 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003006 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3007 final String authTokenType, final String[] requiredFeatures,
3008 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003009 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003010 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003011 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3012 Log.v(TAG, "addAccount: accountType " + accountType
3013 + ", response " + response
3014 + ", authTokenType " + authTokenType
3015 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
3016 + ", expectActivityLaunch " + expectActivityLaunch
3017 + ", caller's uid " + Binder.getCallingUid()
3018 + ", pid " + Binder.getCallingPid()
3019 + ", for user id " + userId);
3020 }
3021 if (response == null) throw new IllegalArgumentException("response is null");
3022 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003023 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003024 if (isCrossUser(callingUid, userId)) {
3025 throw new SecurityException(
3026 String.format(
3027 "User %s trying to add account for %s" ,
3028 UserHandle.getCallingUserId(),
3029 userId));
3030 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003031
3032 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003033 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003034 try {
3035 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3036 "User is not allowed to add an account!");
3037 } catch (RemoteException re) {
3038 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003039 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003040 return;
3041 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003042 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003043 try {
3044 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3045 "User cannot modify accounts of this type (policy).");
3046 } catch (RemoteException re) {
3047 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003048 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3049 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003050 return;
3051 }
3052
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003053 final int pid = Binder.getCallingPid();
3054 final int uid = Binder.getCallingUid();
3055 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3056 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3057 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3058
3059 long identityToken = clearCallingIdentity();
3060 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003061 UserAccounts accounts = getUserAccounts(userId);
3062 logRecordWithUid(
3063 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003064 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003065 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003066 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003067 @Override
3068 public void run() throws RemoteException {
3069 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3070 options);
3071 }
3072
3073 @Override
3074 protected String toDebugString(long now) {
3075 return super.toDebugString(now) + ", addAccount"
3076 + ", accountType " + accountType
3077 + ", requiredFeatures "
3078 + (requiredFeatures != null
3079 ? TextUtils.join(",", requiredFeatures)
3080 : null);
3081 }
3082 }.bind();
3083 } finally {
3084 restoreCallingIdentity(identityToken);
3085 }
3086 }
3087
Sandra Kwan78812282015-11-04 11:19:47 -08003088 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003089 public void startAddAccountSession(
3090 final IAccountManagerResponse response,
3091 final String accountType,
3092 final String authTokenType,
3093 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003094 final boolean expectActivityLaunch,
3095 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003096 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003097 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3098 Log.v(TAG,
3099 "startAddAccountSession: accountType " + accountType
3100 + ", response " + response
3101 + ", authTokenType " + authTokenType
3102 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
3103 + ", expectActivityLaunch " + expectActivityLaunch
3104 + ", caller's uid " + Binder.getCallingUid()
3105 + ", pid " + Binder.getCallingPid());
3106 }
3107 if (response == null) {
3108 throw new IllegalArgumentException("response is null");
3109 }
3110 if (accountType == null) {
3111 throw new IllegalArgumentException("accountType is null");
3112 }
3113
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003114 final int uid = Binder.getCallingUid();
3115 final int userId = UserHandle.getUserId(uid);
3116 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003117 try {
3118 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3119 "User is not allowed to add an account!");
3120 } catch (RemoteException re) {
3121 }
3122 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3123 return;
3124 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003125 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003126 try {
3127 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3128 "User cannot modify accounts of this type (policy).");
3129 } catch (RemoteException re) {
3130 }
3131 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3132 userId);
3133 return;
3134 }
Sandra Kwan78812282015-11-04 11:19:47 -08003135 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003136 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3137 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3138 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3139
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003140 // Check to see if the Password should be included to the caller.
3141 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3142 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003143 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003144
Sandra Kwan78812282015-11-04 11:19:47 -08003145 int usrId = UserHandle.getCallingUserId();
3146 long identityToken = clearCallingIdentity();
3147 try {
3148 UserAccounts accounts = getUserAccounts(usrId);
3149 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
3150 TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003151 new StartAccountSession(
3152 accounts,
3153 response,
3154 accountType,
3155 expectActivityLaunch,
3156 null /* accountName */,
3157 false /* authDetailsRequired */,
3158 true /* updateLastAuthenticationTime */,
3159 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003160 @Override
3161 public void run() throws RemoteException {
3162 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3163 requiredFeatures, options);
3164 }
3165
3166 @Override
3167 protected String toDebugString(long now) {
3168 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3169 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3170 + accountType + ", requiredFeatures "
3171 + (requiredFeatures != null ? requiredFeaturesStr : null);
3172 }
3173 }.bind();
3174 } finally {
3175 restoreCallingIdentity(identityToken);
3176 }
3177 }
3178
3179 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3180 private abstract class StartAccountSession extends Session {
3181
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003182 private final boolean mIsPasswordForwardingAllowed;
3183
3184 public StartAccountSession(
3185 UserAccounts accounts,
3186 IAccountManagerResponse response,
3187 String accountType,
3188 boolean expectActivityLaunch,
3189 String accountName,
3190 boolean authDetailsRequired,
3191 boolean updateLastAuthenticationTime,
3192 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003193 super(accounts, response, accountType, expectActivityLaunch,
3194 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3195 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003196 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003197 }
3198
3199 @Override
3200 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003201 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003202 mNumResults++;
3203 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003204 if (result != null
3205 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003206 checkKeyIntent(
3207 Binder.getCallingUid(),
3208 intent);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003209 // Omit passwords if the caller isn't permitted to see them.
3210 if (!mIsPasswordForwardingAllowed) {
3211 result.remove(AccountManager.KEY_PASSWORD);
3212 }
Sandra Kwan78812282015-11-04 11:19:47 -08003213 }
Sandra Kwan78812282015-11-04 11:19:47 -08003214 IAccountManagerResponse response;
3215 if (mExpectActivityLaunch && result != null
3216 && result.containsKey(AccountManager.KEY_INTENT)) {
3217 response = mResponse;
3218 } else {
3219 response = getResponseAndClose();
3220 }
3221 if (response == null) {
3222 return;
3223 }
3224 if (result == null) {
3225 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3226 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3227 + response);
3228 }
3229 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3230 "null bundle returned");
3231 return;
3232 }
3233
3234 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3235 // All AccountManager error codes are greater
3236 // than 0
3237 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3238 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3239 return;
3240 }
3241
3242 // Strip auth token from result.
3243 result.remove(AccountManager.KEY_AUTHTOKEN);
3244
3245 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3246 Log.v(TAG,
3247 getClass().getSimpleName() + " calling onResult() on response " + response);
3248 }
3249
3250 // Get the session bundle created by authenticator. The
3251 // bundle contains data necessary for finishing the session
3252 // later. The session bundle will be encrypted here and
3253 // decrypted later when trying to finish the session.
3254 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3255 if (sessionBundle != null) {
3256 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3257 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003258 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003259 Log.w(TAG, "Account type in session bundle doesn't match request.");
3260 }
3261 // Add accountType info to session bundle. This will
3262 // override any value set by authenticator.
3263 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3264
3265 // Encrypt session bundle before returning to caller.
3266 try {
3267 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3268 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3269 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3270 } catch (GeneralSecurityException e) {
3271 if (Log.isLoggable(TAG, Log.DEBUG)) {
3272 Log.v(TAG, "Failed to encrypt session bundle!", e);
3273 }
3274 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3275 "failed to encrypt session bundle");
3276 return;
3277 }
3278 }
3279
3280 sendResponse(response, result);
3281 }
3282 }
3283
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003284 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003285 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003286 @NonNull Bundle sessionBundle,
3287 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003288 Bundle appInfo,
3289 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003290 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003291 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003292 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3293 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003294 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003295 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003296 + ", caller's uid " + callingUid
3297 + ", caller's user id " + UserHandle.getCallingUserId()
3298 + ", pid " + Binder.getCallingPid()
3299 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003300 }
3301 if (response == null) {
3302 throw new IllegalArgumentException("response is null");
3303 }
3304
3305 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3306 // Account type is added to it before encryption.
3307 if (sessionBundle == null || sessionBundle.size() == 0) {
3308 throw new IllegalArgumentException("sessionBundle is empty");
3309 }
3310
Sandra Kwan0b84b452016-01-20 15:25:42 -08003311 // Only allow the system process to finish session for other users
3312 if (isCrossUser(callingUid, userId)) {
3313 throw new SecurityException(
3314 String.format(
3315 "User %s trying to finish session for %s without cross user permission",
3316 UserHandle.getCallingUserId(),
3317 userId));
3318 }
3319
Sandra Kwan0b84b452016-01-20 15:25:42 -08003320 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003321 sendErrorResponse(response,
3322 AccountManager.ERROR_CODE_USER_RESTRICTED,
3323 "User is not allowed to add an account!");
3324 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3325 return;
3326 }
3327
3328 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003329 final Bundle decryptedBundle;
3330 final String accountType;
3331 // First decrypt session bundle to get account type for checking permission.
3332 try {
3333 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3334 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3335 if (decryptedBundle == null) {
3336 sendErrorResponse(
3337 response,
3338 AccountManager.ERROR_CODE_BAD_REQUEST,
3339 "failed to decrypt session bundle");
3340 return;
3341 }
3342 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3343 // Account type cannot be null. This should not happen if session bundle was created
3344 // properly by #StartAccountSession.
3345 if (TextUtils.isEmpty(accountType)) {
3346 sendErrorResponse(
3347 response,
3348 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3349 "accountType is empty");
3350 return;
3351 }
3352
3353 // If by any chances, decryptedBundle contains colliding keys with
3354 // system info
3355 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3356 // update credentials flow, we should replace with the new values of the current call.
3357 if (appInfo != null) {
3358 decryptedBundle.putAll(appInfo);
3359 }
3360
3361 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003362 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003363 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3364 } catch (GeneralSecurityException e) {
3365 if (Log.isLoggable(TAG, Log.DEBUG)) {
3366 Log.v(TAG, "Failed to decrypt session bundle!", e);
3367 }
3368 sendErrorResponse(
3369 response,
3370 AccountManager.ERROR_CODE_BAD_REQUEST,
3371 "failed to decrypt session bundle");
3372 return;
3373 }
3374
Sandra Kwan0b84b452016-01-20 15:25:42 -08003375 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003376 sendErrorResponse(
3377 response,
3378 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3379 "User cannot modify accounts of this type (policy).");
3380 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3381 userId);
3382 return;
3383 }
3384
3385 long identityToken = clearCallingIdentity();
3386 try {
3387 UserAccounts accounts = getUserAccounts(userId);
3388 logRecordWithUid(
3389 accounts,
3390 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3391 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003392 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003393 new Session(
3394 accounts,
3395 response,
3396 accountType,
3397 expectActivityLaunch,
3398 true /* stripAuthTokenFromResult */,
3399 null /* accountName */,
3400 false /* authDetailsRequired */,
3401 true /* updateLastAuthenticationTime */) {
3402 @Override
3403 public void run() throws RemoteException {
3404 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3405 }
3406
3407 @Override
3408 protected String toDebugString(long now) {
3409 return super.toDebugString(now)
3410 + ", finishSession"
3411 + ", accountType " + accountType;
3412 }
3413 }.bind();
3414 } finally {
3415 restoreCallingIdentity(identityToken);
3416 }
3417 }
3418
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003419 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003420 final DevicePolicyManagerInternal dpmi =
3421 LocalServices.getService(DevicePolicyManagerInternal.class);
3422 Intent intent = null;
3423 if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
3424 intent = dpmi.createUserRestrictionSupportIntent(userId,
3425 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3426 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3427 intent = dpmi.createShowAdminSupportIntent(userId, false);
3428 }
3429 if (intent == null) {
3430 intent = getDefaultCantAddAccountIntent(errorCode);
3431 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003432 long identityToken = clearCallingIdentity();
3433 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003434 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003435 } finally {
3436 restoreCallingIdentity(identityToken);
3437 }
3438 }
3439
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003440 /**
3441 * Called when we don't know precisely who is preventing us from adding an account.
3442 */
3443 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3444 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3445 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3446 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3447 return cantAddAccount;
3448 }
3449
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003450 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003451 public void confirmCredentialsAsUser(
3452 IAccountManagerResponse response,
3453 final Account account,
3454 final Bundle options,
3455 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003456 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003457 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003458 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003459 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3460 Log.v(TAG, "confirmCredentials: " + account
3461 + ", response " + response
3462 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003463 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003464 + ", pid " + Binder.getCallingPid());
3465 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003466 // Only allow the system process to read accounts of other users
3467 if (isCrossUser(callingUid, userId)) {
3468 throw new SecurityException(
3469 String.format(
3470 "User %s trying to confirm account credentials for %s" ,
3471 UserHandle.getCallingUserId(),
3472 userId));
3473 }
Fred Quintana382601f2010-03-25 12:25:10 -07003474 if (response == null) throw new IllegalArgumentException("response is null");
3475 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003476 long identityToken = clearCallingIdentity();
3477 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003478 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003479 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003480 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003481 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003482 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003483 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003484 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003485 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003486 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003487 protected String toDebugString(long now) {
3488 return super.toDebugString(now) + ", confirmCredentials"
3489 + ", " + account;
3490 }
3491 }.bind();
3492 } finally {
3493 restoreCallingIdentity(identityToken);
3494 }
Fred Quintana60307342009-03-24 22:48:12 -07003495 }
3496
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003497 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003498 public void updateCredentials(IAccountManagerResponse response, final Account account,
3499 final String authTokenType, final boolean expectActivityLaunch,
3500 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003501 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003502 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3503 Log.v(TAG, "updateCredentials: " + account
3504 + ", response " + response
3505 + ", authTokenType " + authTokenType
3506 + ", expectActivityLaunch " + expectActivityLaunch
3507 + ", caller's uid " + Binder.getCallingUid()
3508 + ", pid " + Binder.getCallingPid());
3509 }
Fred Quintana382601f2010-03-25 12:25:10 -07003510 if (response == null) throw new IllegalArgumentException("response is null");
3511 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003512 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003513 long identityToken = clearCallingIdentity();
3514 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003515 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003516 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003517 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003518 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003519 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003520 public void run() throws RemoteException {
3521 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3522 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003523 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003524 protected String toDebugString(long now) {
3525 if (loginOptions != null) loginOptions.keySet();
3526 return super.toDebugString(now) + ", updateCredentials"
3527 + ", " + account
3528 + ", authTokenType " + authTokenType
3529 + ", loginOptions " + loginOptions;
3530 }
3531 }.bind();
3532 } finally {
3533 restoreCallingIdentity(identityToken);
3534 }
Fred Quintana60307342009-03-24 22:48:12 -07003535 }
3536
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003537 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003538 public void startUpdateCredentialsSession(
3539 IAccountManagerResponse response,
3540 final Account account,
3541 final String authTokenType,
3542 final boolean expectActivityLaunch,
3543 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003544 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003545 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3546 Log.v(TAG,
3547 "startUpdateCredentialsSession: " + account + ", response " + response
3548 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3549 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3550 + ", pid " + Binder.getCallingPid());
3551 }
3552 if (response == null) {
3553 throw new IllegalArgumentException("response is null");
3554 }
3555 if (account == null) {
3556 throw new IllegalArgumentException("account is null");
3557 }
Sandra Kwana578d112015-12-16 16:01:43 -08003558
3559 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003560 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003561
3562 // Check to see if the Password should be included to the caller.
3563 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3564 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003565 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003566
Sandra Kwane68c37e2015-11-12 17:11:49 -08003567 long identityToken = clearCallingIdentity();
3568 try {
3569 UserAccounts accounts = getUserAccounts(userId);
3570 new StartAccountSession(
3571 accounts,
3572 response,
3573 account.type,
3574 expectActivityLaunch,
3575 account.name,
3576 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003577 true /* updateLastCredentialTime */,
3578 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003579 @Override
3580 public void run() throws RemoteException {
3581 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3582 loginOptions);
3583 }
3584
3585 @Override
3586 protected String toDebugString(long now) {
3587 if (loginOptions != null)
3588 loginOptions.keySet();
3589 return super.toDebugString(now)
3590 + ", startUpdateCredentialsSession"
3591 + ", " + account
3592 + ", authTokenType " + authTokenType
3593 + ", loginOptions " + loginOptions;
3594 }
3595 }.bind();
3596 } finally {
3597 restoreCallingIdentity(identityToken);
3598 }
3599 }
3600
3601 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003602 public void isCredentialsUpdateSuggested(
3603 IAccountManagerResponse response,
3604 final Account account,
3605 final String statusToken) {
3606 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3607 Log.v(TAG,
3608 "isCredentialsUpdateSuggested: " + account + ", response " + response
3609 + ", caller's uid " + Binder.getCallingUid()
3610 + ", pid " + Binder.getCallingPid());
3611 }
3612 if (response == null) {
3613 throw new IllegalArgumentException("response is null");
3614 }
3615 if (account == null) {
3616 throw new IllegalArgumentException("account is null");
3617 }
3618 if (TextUtils.isEmpty(statusToken)) {
3619 throw new IllegalArgumentException("status token is empty");
3620 }
3621
Sandra Kwan390c9d22016-01-12 14:13:37 -08003622 int usrId = UserHandle.getCallingUserId();
3623 long identityToken = clearCallingIdentity();
3624 try {
3625 UserAccounts accounts = getUserAccounts(usrId);
3626 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3627 false /* stripAuthTokenFromResult */, account.name,
3628 false /* authDetailsRequired */) {
3629 @Override
3630 protected String toDebugString(long now) {
3631 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3632 + ", " + account;
3633 }
3634
3635 @Override
3636 public void run() throws RemoteException {
3637 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3638 }
3639
3640 @Override
3641 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003642 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003643 IAccountManagerResponse response = getResponseAndClose();
3644 if (response == null) {
3645 return;
3646 }
3647
3648 if (result == null) {
3649 sendErrorResponse(
3650 response,
3651 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3652 "null bundle");
3653 return;
3654 }
3655
3656 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3657 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3658 + response);
3659 }
3660 // Check to see if an error occurred. We know if an error occurred because all
3661 // error codes are greater than 0.
3662 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3663 sendErrorResponse(response,
3664 result.getInt(AccountManager.KEY_ERROR_CODE),
3665 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3666 return;
3667 }
3668 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3669 sendErrorResponse(
3670 response,
3671 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3672 "no result in response");
3673 return;
3674 }
3675 final Bundle newResult = new Bundle();
3676 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3677 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3678 sendResponse(response, newResult);
3679 }
3680 }.bind();
3681 } finally {
3682 restoreCallingIdentity(identityToken);
3683 }
3684 }
3685
3686 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003687 public void editProperties(IAccountManagerResponse response, final String accountType,
3688 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003689 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003690 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3691 Log.v(TAG, "editProperties: accountType " + accountType
3692 + ", response " + response
3693 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003694 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003695 + ", pid " + Binder.getCallingPid());
3696 }
Fred Quintana382601f2010-03-25 12:25:10 -07003697 if (response == null) throw new IllegalArgumentException("response is null");
3698 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003699 int userId = UserHandle.getCallingUserId();
3700 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003701 String msg = String.format(
3702 "uid %s cannot edit authenticator properites for account type: %s",
3703 callingUid,
3704 accountType);
3705 throw new SecurityException(msg);
3706 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003707 long identityToken = clearCallingIdentity();
3708 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003709 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003710 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003711 true /* stripAuthTokenFromResult */, null /* accountName */,
3712 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003713 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003714 public void run() throws RemoteException {
3715 mAuthenticator.editProperties(this, mAccountType);
3716 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003717 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003718 protected String toDebugString(long now) {
3719 return super.toDebugString(now) + ", editProperties"
3720 + ", accountType " + accountType;
3721 }
3722 }.bind();
3723 } finally {
3724 restoreCallingIdentity(identityToken);
3725 }
Fred Quintana60307342009-03-24 22:48:12 -07003726 }
3727
Amith Yamasani12747872015-12-07 14:19:49 -08003728 @Override
3729 public boolean someUserHasAccount(@NonNull final Account account) {
3730 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
3731 throw new SecurityException("Only system can check for accounts across users");
3732 }
3733 final long token = Binder.clearCallingIdentity();
3734 try {
3735 AccountAndUser[] allAccounts = getAllAccounts();
3736 for (int i = allAccounts.length - 1; i >= 0; i--) {
3737 if (allAccounts[i].account.equals(account)) {
3738 return true;
3739 }
3740 }
3741 return false;
3742 } finally {
3743 Binder.restoreCallingIdentity(token);
3744 }
3745 }
3746
Fred Quintana33269202009-04-20 16:05:10 -07003747 private class GetAccountsByTypeAndFeatureSession extends Session {
3748 private final String[] mFeatures;
3749 private volatile Account[] mAccountsOfType = null;
3750 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3751 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003752 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003753
Amith Yamasani04e0d262012-02-14 11:50:53 -08003754 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003755 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003756 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003757 true /* stripAuthTokenFromResult */, null /* accountName */,
3758 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003759 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003760 mFeatures = features;
3761 }
3762
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003763 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003764 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003765 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003766 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3767 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003768 }
Fred Quintana33269202009-04-20 16:05:10 -07003769 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07003770 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07003771 mCurrentAccount = 0;
3772
3773 checkAccount();
3774 }
3775
3776 public void checkAccount() {
3777 if (mCurrentAccount >= mAccountsOfType.length) {
3778 sendResult();
3779 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003780 }
Fred Quintana33269202009-04-20 16:05:10 -07003781
Fred Quintana29e94b82010-03-10 12:11:51 -08003782 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3783 if (accountAuthenticator == null) {
3784 // It is possible that the authenticator has died, which is indicated by
3785 // mAuthenticator being set to null. If this happens then just abort.
3786 // There is no need to send back a result or error in this case since
3787 // that already happened when mAuthenticator was cleared.
3788 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3789 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3790 + " connected to the authenticator, " + toDebugString());
3791 }
3792 return;
3793 }
Fred Quintana33269202009-04-20 16:05:10 -07003794 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003795 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003796 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003797 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003798 }
3799 }
3800
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003801 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003802 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003803 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07003804 mNumResults++;
3805 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003806 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003807 return;
3808 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003809 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003810 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3811 }
3812 mCurrentAccount++;
3813 checkAccount();
3814 }
3815
3816 public void sendResult() {
3817 IAccountManagerResponse response = getResponseAndClose();
3818 if (response != null) {
3819 try {
3820 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3821 for (int i = 0; i < accounts.length; i++) {
3822 accounts[i] = mAccountsWithFeatures.get(i);
3823 }
Fred Quintana56285a62010-12-02 14:20:51 -08003824 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3825 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3826 + response);
3827 }
Fred Quintana33269202009-04-20 16:05:10 -07003828 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003829 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003830 response.onResult(result);
3831 } catch (RemoteException e) {
3832 // if the caller is dead then there is no one to care about remote exceptions
3833 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3834 Log.v(TAG, "failure while notifying response", e);
3835 }
3836 }
3837 }
3838 }
3839
3840
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003841 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003842 protected String toDebugString(long now) {
3843 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3844 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3845 }
3846 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003847
Amith Yamasani04e0d262012-02-14 11:50:53 -08003848 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003849 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003850 * @hide
3851 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003852 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003853 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003854 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003855 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3856 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003857 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003858 return new Account[0];
3859 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003860 long identityToken = clearCallingIdentity();
3861 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003862 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003863 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003864 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003865 callingUid,
3866 null, // packageName
3867 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003868 } finally {
3869 restoreCallingIdentity(identityToken);
3870 }
3871 }
3872
Amith Yamasanif29f2362012-04-05 18:29:52 -07003873 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003874 * Returns accounts for all running users.
3875 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003876 * @hide
3877 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003878 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003879 public AccountAndUser[] getRunningAccounts() {
3880 final int[] runningUserIds;
3881 try {
3882 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3883 } catch (RemoteException e) {
3884 // Running in system_server; should never happen
3885 throw new RuntimeException(e);
3886 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003887 return getAccounts(runningUserIds);
3888 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003889
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003890 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003891 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003892 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07003893 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003894 final int[] userIds = new int[users.size()];
3895 for (int i = 0; i < userIds.length; i++) {
3896 userIds[i] = users.get(i).id;
3897 }
3898 return getAccounts(userIds);
3899 }
3900
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003901 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003902 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003903 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003904 for (int userId : userIds) {
3905 UserAccounts userAccounts = getUserAccounts(userId);
3906 if (userAccounts == null) continue;
3907 synchronized (userAccounts.cacheLock) {
3908 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3909 Binder.getCallingUid(), null);
3910 for (int a = 0; a < accounts.length; a++) {
3911 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003912 }
3913 }
3914 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003915
3916 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3917 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003918 }
3919
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003920 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003921 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003922 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3923 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003924 }
3925
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003926 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003927 private Account[] getAccountsAsUser(
3928 String type,
3929 int userId,
3930 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003931 int packageUid,
3932 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003933 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003934 // Only allow the system process to read accounts of other users
3935 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003936 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003937 && mContext.checkCallingOrSelfPermission(
3938 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3939 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003940 throw new SecurityException("User " + UserHandle.getCallingUserId()
3941 + " trying to get account for " + userId);
3942 }
3943
Fred Quintana56285a62010-12-02 14:20:51 -08003944 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3945 Log.v(TAG, "getAccounts: accountType " + type
3946 + ", caller's uid " + Binder.getCallingUid()
3947 + ", pid " + Binder.getCallingPid());
3948 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003949 // If the original calling app was using the framework account chooser activity, we'll
3950 // be passed in the original caller's uid here, which is what should be used for filtering.
3951 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3952 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003953 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003954 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003955 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3956 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003957 if (visibleAccountTypes.isEmpty()
3958 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003959 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003960 } else if (visibleAccountTypes.contains(type)) {
3961 // Prune the list down to just the requested type.
3962 visibleAccountTypes = new ArrayList<>();
3963 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003964 } // else aggregate all the visible accounts (it won't matter if the
3965 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003966
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003967 long identityToken = clearCallingIdentity();
3968 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003969 UserAccounts accounts = getUserAccounts(userId);
Tejas Khorana69990d92016-08-03 11:19:40 -07003970 Account[] accountsToReturn = getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003971 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003972 callingUid,
3973 callingPackage,
3974 visibleAccountTypes);
Tejas Khorana69990d92016-08-03 11:19:40 -07003975 ArrayList<Account> accountsToReturnList = new
3976 ArrayList<Account>(Arrays.asList(accountsToReturn));
3977 for(int i = accountsToReturnList.size() - 1; i >= 0 ; i--) {
3978 // if account not visible to caller or managed by caller, remove from
3979 // accounts to return. Note that all accounts visible by default unless
3980 // visible list functionality implemented
3981 if(!(isAccountVisible(accountsToReturnList.get(i), callingUid,
3982 getUserAccounts(userId)))) {
3983 accountsToReturnList.remove(i);
3984 }
3985 }
3986 return accountsToReturnList.toArray(new Account[accountsToReturnList.size()]);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003987 } finally {
3988 restoreCallingIdentity(identityToken);
3989 }
3990 }
3991
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003992 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003993 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003994 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003995 int callingUid,
3996 String callingPackage,
3997 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003998 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003999 ArrayList<Account> visibleAccounts = new ArrayList<>();
4000 for (String visibleType : visibleAccountTypes) {
4001 Account[] accountsForType = getAccountsFromCacheLocked(
4002 userAccounts, visibleType, callingUid, callingPackage);
4003 if (accountsForType != null) {
4004 visibleAccounts.addAll(Arrays.asList(accountsForType));
4005 }
4006 }
4007 Account[] result = new Account[visibleAccounts.size()];
4008 for (int i = 0; i < visibleAccounts.size(); i++) {
4009 result[i] = visibleAccounts.get(i);
4010 }
4011 return result;
4012 }
4013 }
4014
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004015 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004016 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004017 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004018 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
4019 for (Account account : accounts) {
4020 addSharedAccountAsUser(account, userId);
4021 }
4022 }
4023
4024 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004025 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004026 UserAccounts accounts = getUserAccounts(userId);
4027 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004028 AccountsDbUtils.deleteSharedAccount(db, account);
4029 long accountId = AccountsDbUtils.insertSharedAccount(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004030 if (accountId < 0) {
4031 Log.w(TAG, "insertAccountIntoDatabase: " + account
4032 + ", skipping the DB insert failed");
4033 return false;
4034 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004035 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004036 return true;
4037 }
4038
4039 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004040 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4041 userId = handleIncomingUser(userId);
4042 UserAccounts accounts = getUserAccounts(userId);
4043 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004044 long sharedTableAccountId = AccountsDbUtils.findSharedAccountId(db, account);
4045 int r = AccountsDbUtils.renameSharedAccount(db, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004046 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004047 int callingUid = getCallingUid();
4048 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
4049 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004050 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004051 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004052 }
4053 return r > 0;
4054 }
4055
4056 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08004057 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004058 return removeSharedAccountAsUser(account, userId, getCallingUid());
4059 }
4060
4061 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004062 userId = handleIncomingUser(userId);
4063 UserAccounts accounts = getUserAccounts(userId);
4064 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004065 long sharedTableAccountId = AccountsDbUtils.findSharedAccountId(db, account);
4066 boolean deleted = AccountsDbUtils.deleteSharedAccount(db, account);
4067 if (deleted) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004068 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
4069 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004070 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004071 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004072 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004073 }
4074
4075 @Override
4076 public Account[] getSharedAccountsAsUser(int userId) {
4077 userId = handleIncomingUser(userId);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004078 SQLiteDatabase db = getUserAccounts(userId).openHelper.getReadableDatabase();
4079 List<Account> accountList = AccountsDbUtils.getSharedAccounts(db);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004080 Account[] accountArray = new Account[accountList.size()];
4081 accountList.toArray(accountArray);
4082 return accountArray;
4083 }
4084
4085 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004086 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004087 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004088 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004089 }
4090
Amith Yamasani27db4682013-03-30 17:07:47 -07004091 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004092 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004093 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004094 int callingUid = Binder.getCallingUid();
4095 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
4096 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4097 + callingUid + " with uid=" + uid);
4098 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004099 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
4100 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07004101 }
4102
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004103 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004104 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004105 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4106 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004107 int packageUid = -1;
4108 try {
4109 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07004110 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
4111 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004112 } catch (RemoteException re) {
4113 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
4114 return new Account[0];
4115 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004116 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
4117 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004118 }
4119
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004120 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004121 public void getAccountsByFeatures(
4122 IAccountManagerResponse response,
4123 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004124 String[] features,
4125 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004126 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08004127 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4128 Log.v(TAG, "getAccounts: accountType " + type
4129 + ", response " + response
4130 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004131 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004132 + ", pid " + Binder.getCallingPid());
4133 }
Fred Quintana382601f2010-03-25 12:25:10 -07004134 if (response == null) throw new IllegalArgumentException("response is null");
4135 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004136 int userId = UserHandle.getCallingUserId();
4137
Svetoslavf3f02ac2015-09-08 14:36:35 -07004138 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4139 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004140 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004141 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004142 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004143 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
4144 try {
4145 response.onResult(result);
4146 } catch (RemoteException e) {
4147 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4148 }
4149 return;
4150 }
Fred Quintana33269202009-04-20 16:05:10 -07004151 long identityToken = clearCallingIdentity();
4152 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004153 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004154 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004155 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004156 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004157 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004158 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004159 Bundle result = new Bundle();
4160 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4161 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004162 return;
4163 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004164 new GetAccountsByTypeAndFeatureSession(
4165 userAccounts,
4166 response,
4167 type,
4168 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004169 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004170 } finally {
4171 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004172 }
4173 }
4174
Fred Quintanaa698f422009-04-08 19:14:54 -07004175 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004176 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004177 IAccountManagerResponse mResponse;
4178 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004179 final boolean mExpectActivityLaunch;
4180 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004181 final String mAccountName;
4182 // Indicates if we need to add auth details(like last credential time)
4183 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004184 // If set, we need to update the last authenticated time. This is
4185 // currently
4186 // used on
4187 // successful confirming credentials.
4188 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004189
Fred Quintana33269202009-04-20 16:05:10 -07004190 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004191 private int mNumRequestContinued = 0;
4192 private int mNumErrors = 0;
4193
Fred Quintana60307342009-03-24 22:48:12 -07004194 IAccountAuthenticator mAuthenticator = null;
4195
Fred Quintana8570f742010-02-18 10:32:54 -08004196 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004197 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004198
Amith Yamasani04e0d262012-02-14 11:50:53 -08004199 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004200 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4201 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004202 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4203 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4204 }
4205
4206 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4207 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4208 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004209 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004210 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004211 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004212 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004213 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004214 mResponse = response;
4215 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004216 mExpectActivityLaunch = expectActivityLaunch;
4217 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004218 mAccountName = accountName;
4219 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004220 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004221
Fred Quintanaa698f422009-04-08 19:14:54 -07004222 synchronized (mSessions) {
4223 mSessions.put(toString(), this);
4224 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004225 if (response != null) {
4226 try {
4227 response.asBinder().linkToDeath(this, 0 /* flags */);
4228 } catch (RemoteException e) {
4229 mResponse = null;
4230 binderDied();
4231 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004232 }
Fred Quintana60307342009-03-24 22:48:12 -07004233 }
4234
Fred Quintanaa698f422009-04-08 19:14:54 -07004235 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004236 if (mResponse == null) {
4237 // this session has already been closed
4238 return null;
4239 }
Fred Quintana60307342009-03-24 22:48:12 -07004240 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004241 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004242 return response;
4243 }
4244
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004245 /**
4246 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4247 * security policy.
4248 *
4249 * In particular we want to make sure that the Authenticator doesn't try to trick users
4250 * into launching aribtrary intents on the device via by tricking to click authenticator
4251 * supplied entries in the system Settings app.
4252 */
4253 protected void checkKeyIntent(
4254 int authUid,
4255 Intent intent) throws SecurityException {
4256 long bid = Binder.clearCallingIdentity();
4257 try {
4258 PackageManager pm = mContext.getPackageManager();
4259 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
4260 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4261 int targetUid = targetActivityInfo.applicationInfo.uid;
Sandra Kwan0e961a12016-06-30 14:34:01 -07004262 if (!GrantCredentialsPermissionActivity.class.getName().equals(
4263 targetActivityInfo.getClass().getName())
4264 && !CantAddAccountActivity.class
4265 .equals(targetActivityInfo.getClass().getName())
4266 && PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid,
4267 targetUid)) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004268 String pkgName = targetActivityInfo.packageName;
4269 String activityName = targetActivityInfo.name;
4270 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4271 + "does not share a signature with the supplying authenticator (%s).";
4272 throw new SecurityException(
4273 String.format(tmpl, activityName, pkgName, mAccountType));
4274 }
4275 } finally {
4276 Binder.restoreCallingIdentity(bid);
4277 }
4278 }
4279
Fred Quintanaa698f422009-04-08 19:14:54 -07004280 private void close() {
4281 synchronized (mSessions) {
4282 if (mSessions.remove(toString()) == null) {
4283 // the session was already closed, so bail out now
4284 return;
4285 }
4286 }
4287 if (mResponse != null) {
4288 // stop listening for response deaths
4289 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4290
4291 // clear this so that we don't accidentally send any further results
4292 mResponse = null;
4293 }
4294 cancelTimeout();
4295 unbind();
4296 }
4297
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004298 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004299 public void binderDied() {
4300 mResponse = null;
4301 close();
4302 }
4303
4304 protected String toDebugString() {
4305 return toDebugString(SystemClock.elapsedRealtime());
4306 }
4307
4308 protected String toDebugString(long now) {
4309 return "Session: expectLaunch " + mExpectActivityLaunch
4310 + ", connected " + (mAuthenticator != null)
4311 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4312 + "/" + mNumErrors + ")"
4313 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4314 }
4315
Fred Quintana60307342009-03-24 22:48:12 -07004316 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004317 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4318 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4319 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004320 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004321 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004322 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004323 }
4324 }
4325
4326 private void unbind() {
4327 if (mAuthenticator != null) {
4328 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004329 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004330 }
4331 }
4332
Fred Quintana60307342009-03-24 22:48:12 -07004333 public void cancelTimeout() {
4334 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
4335 }
4336
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004337 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004338 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004339 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004340 try {
4341 run();
4342 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004343 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004344 "remote exception");
4345 }
Fred Quintana60307342009-03-24 22:48:12 -07004346 }
4347
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004348 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004349 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004350 mAuthenticator = null;
4351 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004352 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004353 try {
4354 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4355 "disconnected");
4356 } catch (RemoteException e) {
4357 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4358 Log.v(TAG, "Session.onServiceDisconnected: "
4359 + "caught RemoteException while responding", e);
4360 }
4361 }
Fred Quintana60307342009-03-24 22:48:12 -07004362 }
4363 }
4364
Fred Quintanab839afc2009-10-14 15:57:28 -07004365 public abstract void run() throws RemoteException;
4366
Fred Quintana60307342009-03-24 22:48:12 -07004367 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004368 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004369 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004370 try {
4371 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4372 "timeout");
4373 } catch (RemoteException e) {
4374 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4375 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4376 e);
4377 }
4378 }
Fred Quintana60307342009-03-24 22:48:12 -07004379 }
4380 }
4381
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004382 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004383 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004384 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004385 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004386 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004387 if (result != null) {
4388 boolean isSuccessfulConfirmCreds = result.getBoolean(
4389 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004390 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004391 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4392 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004393 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004394 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4395 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004396 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004397 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004398 if (needUpdate || mAuthDetailsRequired) {
4399 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4400 if (needUpdate && accountPresent) {
4401 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4402 }
4403 if (mAuthDetailsRequired) {
4404 long lastAuthenticatedTime = -1;
4405 if (accountPresent) {
4406 lastAuthenticatedTime = DatabaseUtils.longForQuery(
4407 mAccounts.openHelper.getReadableDatabase(),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004408 "SELECT " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
4409 + " FROM " +
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004410 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
4411 + ACCOUNTS_TYPE + "=?",
4412 new String[] {
4413 mAccountName, mAccountType
4414 });
4415 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004416 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004417 lastAuthenticatedTime);
4418 }
4419 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004420 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004421 if (result != null
4422 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004423 checkKeyIntent(
4424 Binder.getCallingUid(),
4425 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004426 }
4427 if (result != null
4428 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004429 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4430 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004431 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4432 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004433 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4434 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004435 }
Fred Quintana60307342009-03-24 22:48:12 -07004436 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004437 IAccountManagerResponse response;
4438 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004439 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004440 response = mResponse;
4441 } else {
4442 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004443 }
Fred Quintana60307342009-03-24 22:48:12 -07004444 if (response != null) {
4445 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004446 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004447 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4448 Log.v(TAG, getClass().getSimpleName()
4449 + " calling onError() on response " + response);
4450 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004451 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004452 "null bundle returned");
4453 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004454 if (mStripAuthTokenFromResult) {
4455 result.remove(AccountManager.KEY_AUTHTOKEN);
4456 }
Fred Quintana56285a62010-12-02 14:20:51 -08004457 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4458 Log.v(TAG, getClass().getSimpleName()
4459 + " calling onResult() on response " + response);
4460 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004461 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4462 (intent == null)) {
4463 // All AccountManager error codes are greater than 0
4464 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4465 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4466 } else {
4467 response.onResult(result);
4468 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004469 }
Fred Quintana60307342009-03-24 22:48:12 -07004470 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004471 // if the caller is dead then there is no one to care about remote exceptions
4472 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4473 Log.v(TAG, "failure while notifying response", e);
4474 }
Fred Quintana60307342009-03-24 22:48:12 -07004475 }
4476 }
4477 }
Fred Quintana60307342009-03-24 22:48:12 -07004478
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004479 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004480 public void onRequestContinued() {
4481 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004482 }
4483
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004484 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004485 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004486 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004487 IAccountManagerResponse response = getResponseAndClose();
4488 if (response != null) {
4489 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004490 Log.v(TAG, getClass().getSimpleName()
4491 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004492 }
4493 try {
4494 response.onError(errorCode, errorMessage);
4495 } catch (RemoteException e) {
4496 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4497 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4498 }
4499 }
4500 } else {
4501 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4502 Log.v(TAG, "Session.onError: already closed");
4503 }
Fred Quintana60307342009-03-24 22:48:12 -07004504 }
4505 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004506
4507 /**
4508 * find the component name for the authenticator and initiate a bind
4509 * if no authenticator or the bind fails then return false, otherwise return true
4510 */
4511 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004512 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4513 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4514 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004515 if (authenticatorInfo == null) {
4516 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4517 Log.v(TAG, "there is no authenticator for " + authenticatorType
4518 + ", bailing out");
4519 }
4520 return false;
4521 }
4522
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004523 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004524 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004525 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4526 + " which isn't encryption aware");
4527 return false;
4528 }
4529
Fred Quintanab839afc2009-10-14 15:57:28 -07004530 Intent intent = new Intent();
4531 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
4532 intent.setComponent(authenticatorInfo.componentName);
4533 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4534 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
4535 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08004536 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004537 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07004538 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4539 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
4540 }
4541 return false;
4542 }
4543
Fred Quintanab839afc2009-10-14 15:57:28 -07004544 return true;
4545 }
Fred Quintana60307342009-03-24 22:48:12 -07004546 }
4547
4548 private class MessageHandler extends Handler {
4549 MessageHandler(Looper looper) {
4550 super(looper);
4551 }
Costin Manolache3348f142009-09-29 18:58:36 -07004552
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004553 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004554 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07004555 switch (msg.what) {
4556 case MESSAGE_TIMED_OUT:
4557 Session session = (Session)msg.obj;
4558 session.onTimedOut();
4559 break;
4560
Amith Yamasani5be347b2013-03-31 17:44:31 -07004561 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00004562 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07004563 break;
4564
Fred Quintana60307342009-03-24 22:48:12 -07004565 default:
4566 throw new IllegalStateException("unhandled message: " + msg.what);
4567 }
4568 }
4569 }
4570
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004571 @VisibleForTesting
4572 String getPreNDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07004573 File systemDir = Environment.getDataSystemDirectory();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004574 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
4575 PRE_N_DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004576 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07004577 // Migrate old file, if it exists, to the new location.
4578 // Make sure the new file doesn't already exist. A dummy file could have been
4579 // accidentally created in the old location, causing the new one to become corrupted
4580 // as well.
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004581 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07004582 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07004583 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07004584 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07004585 if (!userDir.exists()) {
4586 if (!userDir.mkdirs()) {
4587 throw new IllegalStateException("User dir cannot be created: " + userDir);
4588 }
4589 }
4590 if (!oldFile.renameTo(databaseFile)) {
4591 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
4592 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004593 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08004594 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004595 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08004596 }
4597
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004598 @VisibleForTesting
4599 String getDeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004600 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
4601 DE_DATABASE_NAME);
4602 return databaseFile.getPath();
4603 }
4604
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004605 @VisibleForTesting
4606 String getCeDatabaseName(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004607 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
4608 CE_DATABASE_NAME);
4609 return databaseFile.getPath();
4610 }
4611
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004612 private static class DebugDbHelper{
4613 private DebugDbHelper() {
4614 }
4615
4616 private static String TABLE_DEBUG = "debug_table";
4617
4618 // Columns for the table
4619 private static String ACTION_TYPE = "action_type";
4620 private static String TIMESTAMP = "time";
4621 private static String CALLER_UID = "caller_uid";
4622 private static String TABLE_NAME = "table_name";
4623 private static String KEY = "primary_key";
4624
4625 // These actions correspond to the occurrence of real actions. Since
4626 // these are called by the authenticators, the uid associated will be
4627 // of the authenticator.
4628 private static String ACTION_SET_PASSWORD = "action_set_password";
4629 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
4630 private static String ACTION_ACCOUNT_ADD = "action_account_add";
4631 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004632 private static String ACTION_ACCOUNT_REMOVE_DE = "action_account_remove_de";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004633 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
4634 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
4635
4636 // These actions don't necessarily correspond to any action on
4637 // accountDb taking place. As an example, there might be a request for
4638 // addingAccount, which might not lead to addition of account on grounds
4639 // of bad authentication. We will still be logging it to keep track of
4640 // who called.
4641 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
4642 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Fyodor Kupolov35f68082016-04-06 12:14:17 -07004643 private static String ACTION_SYNC_DE_CE_ACCOUNTS = "action_sync_de_ce_accounts";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004644
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004645 //This action doesn't add account to accountdb. Account is only
4646 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08004647 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08004648 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
4649 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08004650
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004651 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
4652
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004653 private static void createDebugTable(SQLiteDatabase db) {
4654 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
4655 + ACCOUNTS_ID + " INTEGER,"
4656 + ACTION_TYPE + " TEXT NOT NULL, "
4657 + TIMESTAMP + " DATETIME,"
4658 + CALLER_UID + " INTEGER NOT NULL,"
4659 + TABLE_NAME + " TEXT NOT NULL,"
4660 + KEY + " INTEGER PRIMARY KEY)");
4661 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
4662 }
4663 }
4664
4665 private void logRecord(UserAccounts accounts, String action, String tableName) {
4666 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4667 logRecord(db, action, tableName, -1, accounts);
4668 }
4669
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004670 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
4671 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
4672 logRecord(db, action, tableName, -1, accounts, uid);
4673 }
4674
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004675 /*
4676 * This function receives an opened writable database.
4677 */
4678 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4679 UserAccounts userAccount) {
4680 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
4681 }
4682
4683 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004684 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004685 */
4686 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
4687 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004688
4689 class LogRecordTask implements Runnable {
4690 private final String action;
4691 private final String tableName;
4692 private final long accountId;
4693 private final UserAccounts userAccount;
4694 private final int callingUid;
4695 private final long userDebugDbInsertionPoint;
4696
4697 LogRecordTask(final String action,
4698 final String tableName,
4699 final long accountId,
4700 final UserAccounts userAccount,
4701 final int callingUid,
4702 final long userDebugDbInsertionPoint) {
4703 this.action = action;
4704 this.tableName = tableName;
4705 this.accountId = accountId;
4706 this.userAccount = userAccount;
4707 this.callingUid = callingUid;
4708 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
4709 }
4710
4711 public void run() {
4712 SQLiteStatement logStatement = userAccount.statementForLogging;
4713 logStatement.bindLong(1, accountId);
4714 logStatement.bindString(2, action);
4715 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
4716 logStatement.bindLong(4, callingUid);
4717 logStatement.bindString(5, tableName);
4718 logStatement.bindLong(6, userDebugDbInsertionPoint);
4719 logStatement.execute();
4720 logStatement.clearBindings();
4721 }
4722 }
4723
4724 mLogRecordRunnables.add(new LogRecordTask(action, tableName, accountId, userAccount,
4725 callingUid, userAccount.debugDbInsertionPoint));
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004726 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
4727 % MAX_DEBUG_DB_SIZE;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07004728
4729
4730 if(mLogRecordThread == null || !mLogRecordThread.isAlive()) {
4731 mLogRecordThread = new Thread(new Runnable() {
4732 public void run() {
4733 while(mLogRecordRunnables.size() > 0) {
4734 mLogRecordRunnables.pollFirst().run();
4735 }
4736 }
4737 });
4738 mLogRecordThread.start();
4739 }
4740
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004741 }
4742
4743 /*
4744 * This should only be called once to compile the sql statement for logging
4745 * and to find the insertion point.
4746 */
4747 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
4748 UserAccounts userAccount) {
4749 // Initialize the count if not done earlier.
4750 int size = (int) getDebugTableRowCount(db);
4751 if (size >= MAX_DEBUG_DB_SIZE) {
4752 // Table is full, and we need to find the point where to insert.
4753 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
4754 } else {
4755 userAccount.debugDbInsertionPoint = size;
4756 }
4757 compileSqlStatementForLogging(db, userAccount);
4758 }
4759
4760 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4761 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4762 + " VALUES (?,?,?,?,?,?)";
4763 userAccount.statementForLogging = db.compileStatement(sql);
4764 }
4765
4766 private long getDebugTableRowCount(SQLiteDatabase db) {
4767 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4768 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4769 }
4770
4771 /*
4772 * Finds the row key where the next insertion should take place. This should
4773 * be invoked only if the table has reached its full capacity.
4774 */
4775 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4776 // This query finds the smallest timestamp value (and if 2 records have
4777 // same timestamp, the choose the lower id).
4778 String queryCountDebugDbRows = new StringBuilder()
4779 .append("SELECT ").append(DebugDbHelper.KEY)
4780 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4781 .append(" ORDER BY ")
4782 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4783 .append(" LIMIT 1")
4784 .toString();
4785 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4786 }
4787
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004788 static class PreNDatabaseHelper extends SQLiteOpenHelper {
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004789 private final Context mContext;
4790 private final int mUserId;
4791
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004792 public PreNDatabaseHelper(Context context, int userId, String preNDatabaseName) {
4793 super(context, preNDatabaseName, null, PRE_N_DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004794 mContext = context;
4795 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004796 }
4797
4798 @Override
4799 public void onCreate(SQLiteDatabase db) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004800 // We use PreNDatabaseHelper only if pre-N db exists
4801 throw new IllegalStateException("Legacy database cannot be created - only upgraded!");
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004802 }
4803
Amith Yamasani67df64b2012-12-14 12:09:36 -08004804 private void createSharedAccountsTable(SQLiteDatabase db) {
4805 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4806 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4807 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4808 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4809 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4810 }
4811
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004812 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4813 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4814 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4815 }
4816
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004817 private void addOldAccountNameColumn(SQLiteDatabase db) {
4818 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4819 }
4820
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004821 private void addDebugTable(SQLiteDatabase db) {
4822 DebugDbHelper.createDebugTable(db);
4823 }
4824
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004825 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004826 db.execSQL(""
4827 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4828 + " BEGIN"
4829 + " DELETE FROM " + TABLE_AUTHTOKENS
4830 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4831 + " DELETE FROM " + TABLE_EXTRAS
4832 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004833 + " DELETE FROM " + TABLE_GRANTS
4834 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004835 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004836 }
4837
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004838 private void createGrantsTable(SQLiteDatabase db) {
4839 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4840 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4841 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4842 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4843 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4844 + "," + GRANTS_GRANTEE_UID + "))");
4845 }
4846
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004847 private void populateMetaTableWithAuthTypeAndUID(SQLiteDatabase db,
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004848 Map<String, Integer> authTypeAndUIDMap) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004849 for (Entry<String, Integer> entry : authTypeAndUIDMap.entrySet()) {
4850 AccountsDbUtils.insertMetaAuthTypeAndUid(db, entry.getKey(), entry.getValue());
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004851 }
4852 }
4853
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004854 /**
4855 * Pre-N database may need an upgrade before splitting
4856 */
Fred Quintana60307342009-03-24 22:48:12 -07004857 @Override
4858 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004859 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004860
Fred Quintanaa698f422009-04-08 19:14:54 -07004861 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004862 // no longer need to do anything since the work is done
4863 // when upgrading from version 2
4864 oldVersion++;
4865 }
4866
4867 if (oldVersion == 2) {
4868 createGrantsTable(db);
4869 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4870 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004871 oldVersion++;
4872 }
Costin Manolache3348f142009-09-29 18:58:36 -07004873
4874 if (oldVersion == 3) {
4875 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4876 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4877 oldVersion++;
4878 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004879
4880 if (oldVersion == 4) {
4881 createSharedAccountsTable(db);
4882 oldVersion++;
4883 }
4884
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004885 if (oldVersion == 5) {
4886 addOldAccountNameColumn(db);
4887 oldVersion++;
4888 }
4889
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004890 if (oldVersion == 6) {
4891 addLastSuccessfullAuthenticatedTimeColumn(db);
4892 oldVersion++;
4893 }
4894
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004895 if (oldVersion == 7) {
4896 addDebugTable(db);
4897 oldVersion++;
4898 }
4899
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004900 if (oldVersion == 8) {
4901 populateMetaTableWithAuthTypeAndUID(
4902 db,
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004903 getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004904 oldVersion++;
4905 }
4906
Amith Yamasani67df64b2012-12-14 12:09:36 -08004907 if (oldVersion != newVersion) {
4908 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4909 }
Fred Quintana60307342009-03-24 22:48:12 -07004910 }
4911
4912 @Override
4913 public void onOpen(SQLiteDatabase db) {
4914 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4915 }
4916 }
4917
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004918 static class DeDatabaseHelper extends SQLiteOpenHelper {
4919
4920 private final int mUserId;
4921 private volatile boolean mCeAttached;
4922
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004923 private DeDatabaseHelper(Context context, int userId, String deDatabaseName) {
4924 super(context, deDatabaseName, null, DE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004925 mUserId = userId;
4926 }
4927
4928 /**
4929 * This call needs to be made while the mCacheLock is held. The way to
4930 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4931 * @param db The database.
4932 */
4933 @Override
4934 public void onCreate(SQLiteDatabase db) {
4935 Log.i(TAG, "Creating DE database for user " + mUserId);
4936 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4937 + ACCOUNTS_ID + " INTEGER PRIMARY KEY, "
4938 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4939 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4940 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
4941 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
4942 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4943
4944 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4945 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4946 + META_VALUE + " TEXT)");
4947
4948 createGrantsTable(db);
4949 createSharedAccountsTable(db);
4950 createAccountsDeletionTrigger(db);
4951 DebugDbHelper.createDebugTable(db);
4952 }
4953
4954 private void createSharedAccountsTable(SQLiteDatabase db) {
4955 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4956 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4957 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4958 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4959 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4960 }
4961
4962 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
4963 db.execSQL(""
4964 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4965 + " BEGIN"
4966 + " DELETE FROM " + TABLE_GRANTS
4967 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4968 + " END");
4969 }
4970
4971 private void createGrantsTable(SQLiteDatabase db) {
4972 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4973 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4974 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4975 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4976 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4977 + "," + GRANTS_GRANTEE_UID + "))");
4978 }
4979
4980 @Override
4981 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
4982 Log.i(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
4983
4984 if (oldVersion != newVersion) {
4985 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4986 }
4987 }
4988
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07004989 public void attachCeDatabase(File ceDbFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07004990 SQLiteDatabase db = getWritableDatabase();
4991 db.execSQL("ATTACH DATABASE '" + ceDbFile.getPath()+ "' AS ceDb");
4992 mCeAttached = true;
4993 }
4994
4995 public boolean isCeDatabaseAttached() {
4996 return mCeAttached;
4997 }
4998
4999
5000 public SQLiteDatabase getReadableDatabaseUserIsUnlocked() {
5001 if(!mCeAttached) {
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005002 Log.wtf(TAG, "getReadableDatabaseUserIsUnlocked called while user " + mUserId
5003 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005004 }
5005 return super.getReadableDatabase();
5006 }
5007
5008 public SQLiteDatabase getWritableDatabaseUserIsUnlocked() {
5009 if(!mCeAttached) {
5010 Log.wtf(TAG, "getWritableDatabaseUserIsUnlocked called while user " + mUserId
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005011 + " is still locked. CE database is not yet available.", new Throwable());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005012 }
5013 return super.getWritableDatabase();
5014 }
5015
5016 @Override
5017 public void onOpen(SQLiteDatabase db) {
5018 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DE_DATABASE_NAME);
5019 }
5020
5021 private void migratePreNDbToDe(File preNDbFile) {
5022 Log.i(TAG, "Migrate pre-N database to DE preNDbFile=" + preNDbFile);
5023 SQLiteDatabase db = getWritableDatabase();
5024 db.execSQL("ATTACH DATABASE '" + preNDbFile.getPath() + "' AS preNDb");
5025 db.beginTransaction();
5026 // Copy accounts fields
5027 db.execSQL("INSERT INTO " + TABLE_ACCOUNTS
5028 + "(" + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
5029 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
5030 + ") "
5031 + "SELECT " + ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ", "
5032 + ACCOUNTS_PREVIOUS_NAME + ", " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
5033 + " FROM preNDb." + TABLE_ACCOUNTS);
5034 // Copy SHARED_ACCOUNTS
5035 db.execSQL("INSERT INTO " + TABLE_SHARED_ACCOUNTS
5036 + "(" + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + ") " +
5037 "SELECT " + SHARED_ACCOUNTS_ID + "," + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
5038 + " FROM preNDb." + TABLE_SHARED_ACCOUNTS);
5039 // Copy DEBUG_TABLE
5040 db.execSQL("INSERT INTO " + DebugDbHelper.TABLE_DEBUG
5041 + "(" + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
5042 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
5043 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY + ") " +
5044 "SELECT " + ACCOUNTS_ID + "," + DebugDbHelper.ACTION_TYPE + ","
5045 + DebugDbHelper.TIMESTAMP + "," + DebugDbHelper.CALLER_UID + ","
5046 + DebugDbHelper.TABLE_NAME + "," + DebugDbHelper.KEY
5047 + " FROM preNDb." + DebugDbHelper.TABLE_DEBUG);
5048 // Copy GRANTS
5049 db.execSQL("INSERT INTO " + TABLE_GRANTS
5050 + "(" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
5051 + GRANTS_GRANTEE_UID + ") " +
5052 "SELECT " + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE + ","
5053 + GRANTS_GRANTEE_UID + " FROM preNDb." + TABLE_GRANTS);
5054 // Copy META
5055 db.execSQL("INSERT INTO " + TABLE_META
5056 + "(" + META_KEY + "," + META_VALUE + ") "
5057 + "SELECT " + META_KEY + "," + META_VALUE + " FROM preNDb." + TABLE_META);
5058 db.setTransactionSuccessful();
5059 db.endTransaction();
5060
5061 db.execSQL("DETACH DATABASE preNDb");
5062 }
5063
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005064 static DeDatabaseHelper create(
5065 Context context,
5066 int userId,
5067 File preNDatabaseFile,
5068 File deDatabaseFile) {
5069 boolean newDbExists = deDatabaseFile.exists();
5070 DeDatabaseHelper deDatabaseHelper = new DeDatabaseHelper(context, userId,
5071 deDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005072 // If the db just created, and there is a legacy db, migrate it
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005073 if (!newDbExists && preNDatabaseFile.exists()) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005074 // Migrate legacy db to the latest version - PRE_N_DATABASE_VERSION
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005075 PreNDatabaseHelper preNDatabaseHelper = new PreNDatabaseHelper(context, userId,
5076 preNDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005077 // Open the database to force upgrade if required
5078 preNDatabaseHelper.getWritableDatabase();
5079 preNDatabaseHelper.close();
5080 // Move data without SPII to DE
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005081 deDatabaseHelper.migratePreNDbToDe(preNDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005082 }
5083 return deDatabaseHelper;
5084 }
5085 }
5086
5087 static class CeDatabaseHelper extends SQLiteOpenHelper {
5088
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005089 public CeDatabaseHelper(Context context, String ceDatabaseName) {
5090 super(context, ceDatabaseName, null, CE_DATABASE_VERSION);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005091 }
5092
5093 /**
5094 * This call needs to be made while the mCacheLock is held.
5095 * @param db The database.
5096 */
5097 @Override
5098 public void onCreate(SQLiteDatabase db) {
5099 Log.i(TAG, "Creating CE database " + getDatabaseName());
5100 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
5101 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
5102 + ACCOUNTS_NAME + " TEXT NOT NULL, "
5103 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
5104 + ACCOUNTS_PASSWORD + " TEXT, "
5105 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
5106
5107 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
5108 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
5109 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
5110 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
5111 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
5112 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
5113
5114 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
5115 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
5116 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
5117 + EXTRAS_KEY + " TEXT NOT NULL, "
5118 + EXTRAS_VALUE + " TEXT, "
5119 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
5120
5121 createAccountsDeletionTrigger(db);
5122 }
5123
5124 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
5125 db.execSQL(""
5126 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
5127 + " BEGIN"
5128 + " DELETE FROM " + TABLE_AUTHTOKENS
5129 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
5130 + " DELETE FROM " + TABLE_EXTRAS
5131 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
5132 + " END");
5133 }
5134
5135 @Override
5136 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
5137 Log.i(TAG, "Upgrade CE from version " + oldVersion + " to version " + newVersion);
5138
5139 if (oldVersion == 9) {
5140 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5141 Log.v(TAG, "onUpgrade upgrading to v10");
5142 }
5143 db.execSQL("DROP TABLE IF EXISTS " + TABLE_META);
5144 db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHARED_ACCOUNTS);
5145 // Recreate the trigger, since the old one references the table to be removed
5146 db.execSQL("DROP TRIGGER IF EXISTS " + TABLE_ACCOUNTS + "Delete");
5147 createAccountsDeletionTrigger(db);
5148 db.execSQL("DROP TABLE IF EXISTS " + TABLE_GRANTS);
5149 db.execSQL("DROP TABLE IF EXISTS " + DebugDbHelper.TABLE_DEBUG);
5150 oldVersion ++;
5151 }
5152
5153 if (oldVersion != newVersion) {
5154 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
5155 }
5156 }
5157
5158 @Override
5159 public void onOpen(SQLiteDatabase db) {
5160 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + CE_DATABASE_NAME);
5161 }
5162
Fyodor Kupolov35f68082016-04-06 12:14:17 -07005163
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005164 /**
5165 * Creates a new {@code CeDatabaseHelper}. If pre-N db file is present at the old location,
5166 * it also performs migration to the new CE database.
5167 * @param context
5168 * @param userId id of the user where the database is located
5169 */
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005170 static CeDatabaseHelper create(
5171 Context context,
5172 int userId,
5173 File preNDatabaseFile,
5174 File ceDatabaseFile) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005175 boolean newDbExists = ceDatabaseFile.exists();
5176 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5177 Log.v(TAG, "CeDatabaseHelper.create userId=" + userId + " oldDbExists="
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005178 + preNDatabaseFile.exists() + " newDbExists=" + newDbExists);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005179 }
5180 boolean removeOldDb = false;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005181 if (!newDbExists && preNDatabaseFile.exists()) {
5182 removeOldDb = migratePreNDbToCe(preNDatabaseFile, ceDatabaseFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005183 }
5184 // Try to open and upgrade if necessary
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005185 CeDatabaseHelper ceHelper = new CeDatabaseHelper(context, ceDatabaseFile.getPath());
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005186 ceHelper.getWritableDatabase();
5187 ceHelper.close();
5188 if (removeOldDb) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07005189 Slog.i(TAG, "Migration complete - removing pre-N db " + preNDatabaseFile);
5190 if (!SQLiteDatabase.deleteDatabase(preNDatabaseFile)) {
5191 Slog.e(TAG, "Cannot remove pre-N db " + preNDatabaseFile);
5192 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005193 }
5194 return ceHelper;
5195 }
5196
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005197 private static boolean migratePreNDbToCe(File oldDbFile, File ceDbFile) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07005198 Slog.i(TAG, "Moving pre-N DB " + oldDbFile + " to CE " + ceDbFile);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005199 try {
5200 FileUtils.copyFileOrThrow(oldDbFile, ceDbFile);
5201 } catch (IOException e) {
Fyodor Kupolov27bd37f2016-04-21 11:26:14 -07005202 Slog.e(TAG, "Cannot copy file to " + ceDbFile + " from " + oldDbFile, e);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005203 // Try to remove potentially damaged file if I/O error occurred
5204 deleteDbFileWarnIfFailed(ceDbFile);
5205 return false;
5206 }
5207 return true;
5208 }
5209 }
5210
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005211 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07005212 return asBinder();
5213 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005214
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005215 /**
5216 * Searches array of arguments for the specified string
5217 * @param args array of argument strings
5218 * @param value value to search for
5219 * @return true if the value is contained in the array
5220 */
5221 private static boolean scanArgs(String[] args, String value) {
5222 if (args != null) {
5223 for (String arg : args) {
5224 if (value.equals(arg)) {
5225 return true;
5226 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005227 }
5228 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005229 return false;
5230 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005231
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005232 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005233 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07005234 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
5235 != PackageManager.PERMISSION_GRANTED) {
5236 fout.println("Permission Denial: can't dump AccountsManager from from pid="
5237 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
5238 + " without permission " + android.Manifest.permission.DUMP);
5239 return;
5240 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005241 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005242 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07005243
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005244 final List<UserInfo> users = getUserManager().getUsers();
5245 for (UserInfo user : users) {
5246 ipw.println("User " + user + ":");
5247 ipw.increaseIndent();
5248 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
5249 ipw.println();
5250 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005251 }
5252 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005253
Amith Yamasani04e0d262012-02-14 11:50:53 -08005254 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5255 String[] args, boolean isCheckinRequest) {
5256 synchronized (userAccounts.cacheLock) {
5257 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005258
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005259 if (isCheckinRequest) {
5260 // This is a checkin request. *Only* upload the account types and the count of each.
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005261 AccountsDbUtils.dumpAccountsTable(db, fout);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005262 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005263 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07005264 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005265 fout.println("Accounts: " + accounts.length);
5266 for (Account account : accounts) {
5267 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005268 }
Fred Quintana307da1a2010-01-21 14:24:20 -08005269
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005270 // Add debug information.
5271 fout.println();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005272 AccountsDbUtils.dumpDebugTable(db, fout);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005273 fout.println();
5274 synchronized (mSessions) {
5275 final long now = SystemClock.elapsedRealtime();
5276 fout.println("Active Sessions: " + mSessions.size());
5277 for (Session session : mSessions.values()) {
5278 fout.println(" " + session.toDebugString(now));
5279 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005280 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005281
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005282 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005283 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005284 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005285 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005286 }
5287
Amith Yamasani04e0d262012-02-14 11:50:53 -08005288 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07005289 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005290 long identityToken = clearCallingIdentity();
5291 try {
5292 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5293 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5294 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005295
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005296 if (intent.getComponent() != null &&
5297 GrantCredentialsPermissionActivity.class.getName().equals(
5298 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07005299 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005300 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005301 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07005302 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005303 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005304 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07005305 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005306 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005307 Notification n = new Notification.Builder(contextForUser)
5308 .setWhen(0)
5309 .setSmallIcon(android.R.drawable.stat_sys_warning)
5310 .setColor(contextForUser.getColor(
5311 com.android.internal.R.color.system_notification_accent_color))
5312 .setContentTitle(String.format(notificationTitleFormat, account.name))
5313 .setContentText(message)
5314 .setContentIntent(PendingIntent.getActivityAsUser(
5315 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
5316 null, user))
5317 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005318 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005319 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005320 } finally {
5321 restoreCallingIdentity(identityToken);
5322 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005323 }
5324
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005325 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005326 protected void installNotification(final int notificationId, final Notification n,
5327 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08005328 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005329 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08005330 }
5331
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005332 @VisibleForTesting
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005333 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005334 long identityToken = clearCallingIdentity();
5335 try {
5336 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005337 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005338 } finally {
5339 restoreCallingIdentity(identityToken);
5340 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005341 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005342
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005343 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5344 for (String perm : permissions) {
5345 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5346 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5347 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5348 }
5349 final int opCode = AppOpsManager.permissionToOpCode(perm);
5350 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5351 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5352 return true;
5353 }
5354 }
5355 }
5356 return false;
5357 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005358
Amith Yamasani67df64b2012-12-14 12:09:36 -08005359 private int handleIncomingUser(int userId) {
5360 try {
5361 return ActivityManagerNative.getDefault().handleIncomingUser(
5362 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5363 } catch (RemoteException re) {
5364 // Shouldn't happen, local.
5365 }
5366 return userId;
5367 }
5368
Christopher Tateccbf84f2013-05-08 15:25:41 -07005369 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005370 final int callingUserId = UserHandle.getUserId(callingUid);
5371
5372 final PackageManager userPackageManager;
5373 try {
5374 userPackageManager = mContext.createPackageContextAsUser(
5375 "android", 0, new UserHandle(callingUserId)).getPackageManager();
5376 } catch (NameNotFoundException e) {
5377 return false;
5378 }
5379
5380 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005381 for (String name : packages) {
5382 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005383 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08005384 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08005385 && (packageInfo.applicationInfo.privateFlags
5386 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07005387 return true;
5388 }
5389 } catch (PackageManager.NameNotFoundException e) {
5390 return false;
5391 }
5392 }
5393 return false;
5394 }
5395
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005396 private boolean permissionIsGranted(
5397 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07005398 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07005399 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005400 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07005401 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08005402 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005403 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5404 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08005405 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005406 + ": is authenticator? " + fromAuthenticator
5407 + ", has explicit permission? " + hasExplicitGrants);
5408 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07005409 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005410 }
5411
Svetoslavf3f02ac2015-09-08 14:36:35 -07005412 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5413 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005414 if (accountType == null) {
5415 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005416 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005417 return getTypesVisibleToCaller(callingUid, userId,
5418 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005419 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005420 }
5421
5422 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5423 if (accountType == null) {
5424 return false;
5425 } else {
5426 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5427 }
5428 }
5429
Svetoslavf3f02ac2015-09-08 14:36:35 -07005430 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5431 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005432 boolean isPermitted =
5433 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
5434 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005435 return getTypesForCaller(callingUid, userId, isPermitted);
5436 }
5437
5438 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
5439 return getTypesForCaller(callingUid, userId, false);
5440 }
5441
5442 private List<String> getTypesForCaller(
5443 int callingUid, int userId, boolean isOtherwisePermitted) {
5444 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005445 long identityToken = Binder.clearCallingIdentity();
5446 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5447 try {
5448 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5449 } finally {
5450 Binder.restoreCallingIdentity(identityToken);
5451 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005452 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005453 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005454 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5455 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
5456 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005457 }
5458 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005459 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005460 }
5461
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005462 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5463 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5464 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5465 if (account.name.equals(accountName)) {
5466 return true;
5467 }
5468 }
5469 }
5470 return false;
5471 }
5472
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005473 private static void checkManageUsersPermission(String message) {
5474 if (ActivityManager.checkComponentPermission(
5475 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5476 != PackageManager.PERMISSION_GRANTED) {
5477 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5478 }
5479 }
5480
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005481 private static void checkManageOrCreateUsersPermission(String message) {
5482 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5483 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5484 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5485 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5486 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5487 + message);
5488 }
5489 }
5490
Amith Yamasani04e0d262012-02-14 11:50:53 -08005491 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5492 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07005493 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005494 return true;
5495 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005496 UserAccounts accounts = getUserAccountsForCaller();
5497 synchronized (accounts.cacheLock) {
5498 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005499 final boolean permissionGranted = AccountsDbUtils.findMatchingGrantsCount(db, callerUid,
5500 authTokenType, account) != 0;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005501 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5502 // TODO: Skip this check when running automated tests. Replace this
5503 // with a more general solution.
5504 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08005505 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005506 + " but ignoring since device is in test harness.");
5507 return true;
5508 }
5509 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005510 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005511 }
5512
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005513 private boolean isSystemUid(int callingUid) {
5514 String[] packages = null;
5515 long ident = Binder.clearCallingIdentity();
5516 try {
5517 packages = mPackageManager.getPackagesForUid(callingUid);
5518 } finally {
5519 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005520 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005521 if (packages != null) {
5522 for (String name : packages) {
5523 try {
5524 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5525 if (packageInfo != null
5526 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5527 != 0) {
5528 return true;
5529 }
5530 } catch (PackageManager.NameNotFoundException e) {
5531 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5532 }
5533 }
5534 } else {
5535 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005536 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005537 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005538 }
5539
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005540 /** Succeeds if any of the specified permissions are granted. */
5541 private void checkReadAccountsPermitted(
5542 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005543 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005544 int userId,
5545 String opPackageName) {
5546 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005547 String msg = String.format(
5548 "caller uid %s cannot access %s accounts",
5549 callingUid,
5550 accountType);
5551 Log.w(TAG, " " + msg);
5552 throw new SecurityException(msg);
5553 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005554 }
5555
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005556 private boolean canUserModifyAccounts(int userId, int callingUid) {
5557 // the managing app can always modify accounts
5558 if (isProfileOwner(callingUid)) {
5559 return true;
5560 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005561 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5562 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5563 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005564 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005565 return true;
5566 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005567
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005568 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5569 // the managing app can always modify accounts
5570 if (isProfileOwner(callingUid)) {
5571 return true;
5572 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005573 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5574 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005575 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005576 if (typesArray == null) {
5577 return true;
5578 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005579 for (String forbiddenType : typesArray) {
5580 if (forbiddenType.equals(accountType)) {
5581 return false;
5582 }
5583 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005584 return true;
5585 }
5586
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005587 private boolean isProfileOwner(int uid) {
5588 final DevicePolicyManagerInternal dpmi =
5589 LocalServices.getService(DevicePolicyManagerInternal.class);
5590 return (dpmi != null)
5591 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5592 }
5593
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005594 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005595 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5596 throws RemoteException {
5597 final int callingUid = getCallingUid();
5598
Amith Yamasani27db4682013-03-30 17:07:47 -07005599 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005600 throw new SecurityException();
5601 }
5602
5603 if (value) {
5604 grantAppPermission(account, authTokenType, uid);
5605 } else {
5606 revokeAppPermission(account, authTokenType, uid);
5607 }
5608 }
5609
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005610 /**
5611 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5612 * <p>
5613 * Although this is public it can only be accessed via the AccountManagerService object
5614 * which is in the system. This means we don't need to protect it with permissions.
5615 * @hide
5616 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005617 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005618 if (account == null || authTokenType == null) {
5619 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005620 return;
5621 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005622 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005623 synchronized (accounts.cacheLock) {
5624 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005625 long accountId = AccountsDbUtils.findAccountId(db, account);
5626 if (accountId >= 0) {
5627 AccountsDbUtils.insertGrant(db, accountId, authTokenType, uid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005628 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005629 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005630 UserHandle.of(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005631 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005632 }
5633
5634 /**
5635 * Don't allow callers with the given uid permission to get credentials for
5636 * account/authTokenType.
5637 * <p>
5638 * Although this is public it can only be accessed via the AccountManagerService object
5639 * which is in the system. This means we don't need to protect it with permissions.
5640 * @hide
5641 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005642 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005643 if (account == null || authTokenType == null) {
5644 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005645 return;
5646 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005647 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08005648 synchronized (accounts.cacheLock) {
5649 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005650 db.beginTransaction();
5651 try {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005652 long accountId = AccountsDbUtils.findAccountId(db, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005653 if (accountId >= 0) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005654 AccountsDbUtils.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5655 db, accountId, authTokenType, uid);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005656 db.setTransactionSuccessful();
5657 }
5658 } finally {
5659 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005660 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07005661 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
5662 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005663 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005664 }
Fred Quintana56285a62010-12-02 14:20:51 -08005665
5666 static final private String stringArrayToString(String[] value) {
5667 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
5668 }
5669
Amith Yamasani04e0d262012-02-14 11:50:53 -08005670 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5671 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005672 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005673 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005674 for (Account curAccount : oldAccountsForType) {
5675 if (!curAccount.equals(account)) {
5676 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005677 }
5678 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005679 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005680 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005681 } else {
5682 Account[] newAccountsForType = new Account[newAccountsList.size()];
5683 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005684 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005685 }
Fred Quintana56285a62010-12-02 14:20:51 -08005686 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005687 accounts.userDataCache.remove(account);
5688 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005689 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005690 }
5691
5692 /**
5693 * This assumes that the caller has already checked that the account is not already present.
5694 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08005695 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
5696 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005697 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5698 Account[] newAccountsForType = new Account[oldLength + 1];
5699 if (accountsForType != null) {
5700 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005701 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005702 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005703 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08005704 }
5705
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005706 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07005707 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005708 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07005709 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005710 return unfiltered;
5711 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005712 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005713 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005714 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005715 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005716 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005717 // This might be a temporary way to specify a visible list
5718 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005719 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5720 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005721 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005722 return unfiltered;
5723 }
5724 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005725 ArrayList<Account> allowed = new ArrayList<>();
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005726 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
5727 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005728 String requiredAccountType = "";
5729 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005730 // If there's an explicit callingPackage specified, check if that package
5731 // opted in to see restricted accounts.
5732 if (callingPackage != null) {
5733 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005734 if (pi != null && pi.restrictedAccountType != null) {
5735 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005736 }
5737 } else {
5738 // Otherwise check if the callingUid has a package that has opted in
5739 for (String packageName : packages) {
5740 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5741 if (pi != null && pi.restrictedAccountType != null) {
5742 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005743 break;
5744 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005745 }
5746 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005747 } catch (NameNotFoundException nnfe) {
5748 }
5749 for (Account account : unfiltered) {
5750 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005751 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005752 } else {
5753 boolean found = false;
5754 for (Account shared : sharedAccounts) {
5755 if (shared.equals(account)) {
5756 found = true;
5757 break;
5758 }
5759 }
5760 if (!found) {
5761 allowed.add(account);
5762 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005763 }
5764 }
5765 Account[] filtered = new Account[allowed.size()];
5766 allowed.toArray(filtered);
5767 return filtered;
5768 } else {
5769 return unfiltered;
5770 }
5771 }
5772
Amith Yamasani27db4682013-03-30 17:07:47 -07005773 /*
5774 * packageName can be null. If not null, it should be used to filter out restricted accounts
5775 * that the package is not allowed to access.
5776 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005777 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07005778 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005779 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005780 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005781 if (accounts == null) {
5782 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005783 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005784 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07005785 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005786 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005787 } else {
5788 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005789 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005790 totalLength += accounts.length;
5791 }
5792 if (totalLength == 0) {
5793 return EMPTY_ACCOUNT_ARRAY;
5794 }
5795 Account[] accounts = new Account[totalLength];
5796 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005797 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005798 System.arraycopy(accountsOfType, 0, accounts, totalLength,
5799 accountsOfType.length);
5800 totalLength += accountsOfType.length;
5801 }
Amith Yamasani27db4682013-03-30 17:07:47 -07005802 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08005803 }
5804 }
5805
Amith Yamasani04e0d262012-02-14 11:50:53 -08005806 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5807 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005808 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005809 if (userDataForAccount == null) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005810 userDataForAccount = AccountsDbUtils.findUserExtrasForAccount(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005811 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005812 }
5813 if (value == null) {
5814 userDataForAccount.remove(key);
5815 } else {
5816 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005817 }
5818 }
5819
Carlos Valdivia91979be2015-05-22 14:11:35 -07005820 protected String readCachedTokenInternal(
5821 UserAccounts accounts,
5822 Account account,
5823 String tokenType,
5824 String callingPackage,
5825 byte[] pkgSigDigest) {
5826 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005827 return accounts.accountTokenCaches.get(
5828 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005829 }
5830 }
5831
Amith Yamasani04e0d262012-02-14 11:50:53 -08005832 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
5833 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005834 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005835 if (authTokensForAccount == null) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005836 authTokensForAccount = AccountsDbUtils.findAuthTokensByAccount(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005837 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005838 }
5839 if (value == null) {
5840 authTokensForAccount.remove(key);
5841 } else {
5842 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005843 }
5844 }
5845
Amith Yamasani04e0d262012-02-14 11:50:53 -08005846 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5847 String authTokenType) {
5848 synchronized (accounts.cacheLock) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005849 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005850 if (authTokensForAccount == null) {
5851 // need to populate the cache for this account
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005852 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005853 authTokensForAccount = AccountsDbUtils
5854 .findAuthTokensByAccount(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005855 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005856 }
5857 return authTokensForAccount.get(authTokenType);
5858 }
5859 }
5860
Simranjit Kohli858511c2016-03-10 18:36:11 +00005861 protected String readUserDataInternalLocked(
5862 UserAccounts accounts, Account account, String key) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005863 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Simranjit Kohli858511c2016-03-10 18:36:11 +00005864 if (userDataForAccount == null) {
5865 // need to populate the cache for this account
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07005866 final SQLiteDatabase db = accounts.openHelper.getReadableDatabaseUserIsUnlocked();
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005867 userDataForAccount = AccountsDbUtils.findUserExtrasForAccount(db, account);
Simranjit Kohli858511c2016-03-10 18:36:11 +00005868 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005869 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00005870 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08005871 }
5872
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005873 private Context getContextForUser(UserHandle user) {
5874 try {
5875 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
5876 } catch (NameNotFoundException e) {
5877 // Default to mContext, not finding the package system is running as is unlikely.
5878 return mContext;
5879 }
5880 }
Sandra Kwan78812282015-11-04 11:19:47 -08005881
5882 private void sendResponse(IAccountManagerResponse response, Bundle result) {
5883 try {
5884 response.onResult(result);
5885 } catch (RemoteException e) {
5886 // if the caller is dead then there is no one to care about remote
5887 // exceptions
5888 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5889 Log.v(TAG, "failure while notifying response", e);
5890 }
5891 }
5892 }
5893
5894 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
5895 String errorMessage) {
5896 try {
5897 response.onError(errorCode, errorMessage);
5898 } catch (RemoteException e) {
5899 // if the caller is dead then there is no one to care about remote
5900 // exceptions
5901 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5902 Log.v(TAG, "failure while notifying response", e);
5903 }
5904 }
5905 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005906
5907 static class AccountsDbUtils {
5908
5909 static String findAccountPasswordByNameAndType(SQLiteDatabase db, String name,
5910 String type) {
5911 Cursor cursor = db.query(CE_TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
5912 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
5913 new String[]{name, type}, null, null, null);
5914 try {
5915 if (cursor.moveToNext()) {
5916 return cursor.getString(0);
5917 }
5918 return null;
5919 } finally {
5920 cursor.close();
5921 }
5922 }
5923
5924 static Map<Long, Account> findAllAccounts(SQLiteDatabase db) {
5925 LinkedHashMap<Long, Account> map = new LinkedHashMap<>();
5926 Cursor cursor = db.query(TABLE_ACCOUNTS,
5927 new String[] {ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
5928 null, null, null, null, ACCOUNTS_ID);
5929 try {
5930 while (cursor.moveToNext()) {
5931 final long accountId = cursor.getLong(0);
5932 final String accountType = cursor.getString(1);
5933 final String accountName = cursor.getString(2);
5934
5935 final Account account = new Account(accountName, accountType);
5936 map.put(accountId, account);
5937 }
5938 } finally {
5939 cursor.close();
5940 }
5941 return map;
5942 }
5943
5944 static String findAccountPreviousName(SQLiteDatabase db, Account account) {
5945 Cursor cursor = db.query(
5946 TABLE_ACCOUNTS,
5947 new String[]{ ACCOUNTS_PREVIOUS_NAME },
5948 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
5949 new String[] { account.name, account.type },
5950 null,
5951 null,
5952 null);
5953 try {
5954 if (cursor.moveToNext()) {
5955 return cursor.getString(0);
5956 }
5957 } finally {
5958 cursor.close();
5959 }
5960 return null;
5961 }
5962
5963 static List<Account> findCeAccountsNotInDe(SQLiteDatabase db) {
5964 // Select accounts from CE that do not exist in DE
5965 Cursor cursor = db.rawQuery(
5966 "SELECT " + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE
5967 + " FROM " + CE_TABLE_ACCOUNTS
5968 + " WHERE NOT EXISTS "
5969 + " (SELECT " + ACCOUNTS_ID + " FROM " + TABLE_ACCOUNTS
5970 + " WHERE " + ACCOUNTS_ID + "=" + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
5971 + " )", null);
5972 try {
5973 List<Account> accounts = new ArrayList<>(cursor.getCount());
5974 while (cursor.moveToNext()) {
5975 String accountName = cursor.getString(0);
5976 String accountType = cursor.getString(1);
5977 accounts.add(new Account(accountName, accountType));
5978 }
5979 return accounts;
5980 } finally {
5981 cursor.close();
5982 }
5983 }
5984
5985 static boolean deleteAccount(SQLiteDatabase db, long accountId) {
5986 return db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null) > 0;
5987 }
5988
5989 static boolean deleteCeAccount(SQLiteDatabase db, long accountId) {
5990 return db.delete(CE_TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null) > 0;
5991 }
5992
5993 /**
5994 * Returns information about auth tokens and their account for the specified query parameters.
5995 * Output is in the format:
5996 * <pre><code> | AUTHTOKEN_ID | ACCOUNT_NAME | AUTH_TOKEN_TYPE |</code></pre>
5997 */
5998 static Cursor findAuthtokenForAllAccounts(SQLiteDatabase db, String accountType,
5999 String authToken) {
6000 return db.rawQuery(
6001 "SELECT " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
6002 + ", " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
6003 + ", " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
6004 + " FROM " + CE_TABLE_ACCOUNTS
6005 + " JOIN " + CE_TABLE_AUTHTOKENS
6006 + " ON " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_ID
6007 + " = " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_ACCOUNTS_ID
6008 + " WHERE " + CE_TABLE_AUTHTOKENS + "." + AUTHTOKENS_AUTHTOKEN
6009 + " = ? AND " + CE_TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
6010 new String[]{authToken, accountType});
6011 }
6012
6013 static boolean deleteAuthtokensByAccountIdAndType(SQLiteDatabase db, long accountId,
6014 String authtokenType) {
6015 return db.delete(CE_TABLE_AUTHTOKENS,
6016 AUTHTOKENS_ACCOUNTS_ID + "=?" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
6017 new String[] {String.valueOf(accountId), authtokenType}) > 0;
6018 }
6019
6020 static boolean deleteAuthToken(SQLiteDatabase db, String authTokenId) {
6021 return db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ID + "= ?",
6022 new String[] {authTokenId}) > 0;
6023 }
6024
6025 static long insertAuthToken(SQLiteDatabase db, long accountId, String authTokenType,
6026 String authToken) {
6027 ContentValues values = new ContentValues();
6028 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
6029 values.put(AUTHTOKENS_TYPE, authTokenType);
6030 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
6031 return db.insert(CE_TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values);
6032 }
6033
6034 static Map<String, String> findAuthTokensByAccount(final SQLiteDatabase db, Account account) {
6035 HashMap<String, String> authTokensForAccount = new HashMap<>();
6036 Cursor cursor = db.query(CE_TABLE_AUTHTOKENS,
6037 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
6038 SELECTION_AUTHTOKENS_BY_ACCOUNT,
6039 new String[]{account.name, account.type},
6040 null, null, null);
6041 try {
6042 while (cursor.moveToNext()) {
6043 final String type = cursor.getString(0);
6044 final String authToken = cursor.getString(1);
6045 authTokensForAccount.put(type, authToken);
6046 }
6047 } finally {
6048 cursor.close();
6049 }
6050 return authTokensForAccount;
6051 }
6052
6053 static int updateAccountPassword(SQLiteDatabase db, long accountId, String password) {
6054 final ContentValues values = new ContentValues();
6055 values.put(ACCOUNTS_PASSWORD, password);
6056 return db.update(CE_TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?",
6057 new String[] {String.valueOf(accountId)});
6058 }
6059
6060 static boolean deleteAuthTokensByAccountId(SQLiteDatabase db, long accountId) {
6061 return db.delete(CE_TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?",
6062 new String[] {String.valueOf(accountId)}) > 0;
6063 }
6064
6065 static long insertSharedAccount(SQLiteDatabase db, Account account) {
6066 ContentValues values = new ContentValues();
6067 values.put(ACCOUNTS_NAME, account.name);
6068 values.put(ACCOUNTS_TYPE, account.type);
6069 return db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
6070 }
6071
6072 static boolean deleteSharedAccount(SQLiteDatabase db, Account account) {
6073 return db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
6074 new String[] {account.name, account.type}) > 0;
6075 }
6076
6077 static int renameSharedAccount(SQLiteDatabase db, Account account, String newName) {
6078 final ContentValues values = new ContentValues();
6079 values.put(ACCOUNTS_NAME, newName);
6080 return db.update(TABLE_SHARED_ACCOUNTS,
6081 values,
6082 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
6083 new String[] { account.name, account.type });
6084 }
6085
6086 static List<Account> getSharedAccounts(SQLiteDatabase db) {
6087 ArrayList<Account> accountList = new ArrayList<>();
6088 Cursor cursor = null;
6089 try {
6090 cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[] {ACCOUNTS_NAME, ACCOUNTS_TYPE},
6091 null, null, null, null, null);
6092 if (cursor != null && cursor.moveToFirst()) {
6093 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
6094 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
6095 do {
6096 accountList.add(new Account(cursor.getString(nameIndex),
6097 cursor.getString(typeIndex)));
6098 } while (cursor.moveToNext());
6099 }
6100 } finally {
6101 if (cursor != null) {
6102 cursor.close();
6103 }
6104 }
6105 return accountList;
6106 }
6107
6108 static long findSharedAccountId(SQLiteDatabase db, Account account) {
6109 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
6110 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
6111 try {
6112 if (cursor.moveToNext()) {
6113 return cursor.getLong(0);
6114 }
6115 return -1;
6116 } finally {
6117 cursor.close();
6118 }
6119 }
6120
6121 static long findAccountId(SQLiteDatabase db, Account account) {
6122 Cursor cursor = db.query(
6123 TABLE_ACCOUNTS, new String[] {ACCOUNTS_ID},
6124 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
6125 try {
6126 if (cursor.moveToNext()) {
6127 return cursor.getLong(0);
6128 }
6129 return -1;
6130 } finally {
6131 cursor.close();
6132 }
6133 }
6134
6135 static long findExtrasIdByAccountId(SQLiteDatabase db, long accountId, String key) {
6136 Cursor cursor = db.query(
6137 CE_TABLE_EXTRAS, new String[] {EXTRAS_ID},
6138 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
6139 new String[]{key}, null, null, null);
6140 try {
6141 if (cursor.moveToNext()) {
6142 return cursor.getLong(0);
6143 }
6144 return -1;
6145 } finally {
6146 cursor.close();
6147 }
6148 }
6149
6150 static boolean updateExtra(SQLiteDatabase db, long extrasId, String value) {
6151 ContentValues values = new ContentValues();
6152 values.put(EXTRAS_VALUE, value);
6153 int rows = db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=?",
6154 new String[]{String.valueOf(extrasId)});
6155 return rows == 1;
6156 }
6157
6158 static long insertExtra(SQLiteDatabase db, long accountId, String key, String value) {
6159 ContentValues values = new ContentValues();
6160 values.put(EXTRAS_KEY, key);
6161 values.put(EXTRAS_ACCOUNTS_ID, accountId);
6162 values.put(EXTRAS_VALUE, value);
6163 return db.insert(CE_TABLE_EXTRAS, EXTRAS_KEY, values);
6164 }
6165
6166 static Map<String, String> findUserExtrasForAccount(SQLiteDatabase db, Account account) {
6167 Map<String, String> userExtrasForAccount = new HashMap<>();
6168 Cursor cursor = db.query(CE_TABLE_EXTRAS,
6169 COLUMNS_EXTRAS_KEY_AND_VALUE,
6170 SELECTION_USERDATA_BY_ACCOUNT,
6171 new String[] {account.name, account.type},
6172 null, null, null);
6173 try {
6174 while (cursor.moveToNext()) {
6175 final String tmpkey = cursor.getString(0);
6176 final String value = cursor.getString(1);
6177 userExtrasForAccount.put(tmpkey, value);
6178 }
6179 } finally {
6180 cursor.close();
6181 }
6182 return userExtrasForAccount;
6183 }
6184
6185 static long insertGrant(SQLiteDatabase db, long accountId, String authTokenType, int uid) {
6186 ContentValues values = new ContentValues();
6187 values.put(GRANTS_ACCOUNTS_ID, accountId);
6188 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
6189 values.put(GRANTS_GRANTEE_UID, uid);
6190 return db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
6191 }
6192
6193 static boolean deleteGrantsByUid(SQLiteDatabase db, int uid) {
6194 return db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
6195 new String[] {Integer.toString(uid)}) > 0;
6196 }
6197
6198 static boolean deleteGrantsByAccountIdAuthTokenTypeAndUid(SQLiteDatabase db, long accountId, String authTokenType, long uid) {
6199 return db.delete(TABLE_GRANTS,
6200 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
6201 + GRANTS_GRANTEE_UID + "=?",
6202 new String[] {String.valueOf(accountId), authTokenType, String.valueOf(uid)}) > 0;
6203 }
6204
6205 static List<Integer> findAllUidGrants(SQLiteDatabase db) {
6206 List<Integer> result = new ArrayList<>();
6207 final Cursor cursor = db.query(TABLE_GRANTS,
6208 new String[] {GRANTS_GRANTEE_UID},
6209 null, null, GRANTS_GRANTEE_UID, null, null);
6210 try {
6211 while (cursor.moveToNext()) {
6212 final int uid = cursor.getInt(0);
6213 result.add(uid);
6214 }
6215 } finally {
6216 cursor.close();
6217 }
6218 return result;
6219 }
6220
6221 static long findMatchingGrantsCount(SQLiteDatabase db,
6222 int uid, String authTokenType, Account account) {
6223 String[] args = { String.valueOf(uid), authTokenType,
6224 account.name, account.type};
6225 return DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args);
6226 }
6227
6228 static long insertMetaAuthTypeAndUid(SQLiteDatabase db, String authenticatorType, int uid) {
6229 ContentValues values = new ContentValues();
6230 values.put(META_KEY,
6231 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + authenticatorType);
6232 values.put(META_VALUE, uid);
6233 return db.insert(TABLE_META, null, values);
6234 }
6235
6236 static long insertOrReplaceMetaAuthTypeAndUid(SQLiteDatabase db, String authenticatorType,
6237 int uid) {
6238 ContentValues values = new ContentValues();
6239 values.put(META_KEY,
6240 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + authenticatorType);
6241 values.put(META_VALUE, uid);
6242 return db.insertWithOnConflict(TABLE_META, null, values,
6243 SQLiteDatabase.CONFLICT_REPLACE);
6244 }
6245
6246
6247 static Map<String, Integer> findMetaAuthUid(SQLiteDatabase db) {
6248 Cursor metaCursor = db.query(
6249 TABLE_META,
6250 new String[] {META_KEY, META_VALUE},
6251 SELECTION_META_BY_AUTHENTICATOR_TYPE,
6252 new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
6253 null /* groupBy */,
6254 null /* having */,
6255 META_KEY);
6256 Map<String, Integer> map = new LinkedHashMap<>();
6257 try {
6258 while (metaCursor.moveToNext()) {
6259 String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
6260 String uidStr = metaCursor.getString(1);
6261 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uidStr)) {
6262 // Should never happen.
6263 Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
6264 + ", uid empty: " + TextUtils.isEmpty(uidStr));
6265 continue;
6266 }
6267 int uid = Integer.parseInt(metaCursor.getString(1));
6268 map.put(type, uid);
6269 }
6270 } finally {
6271 metaCursor.close();
6272 }
6273 return map;
6274 }
6275
6276 static boolean deleteMetaByAuthTypeAndUid(SQLiteDatabase db, String type, int uid) {
6277 return db.delete(
6278 TABLE_META,
6279 META_KEY + "=? AND " + META_VALUE + "=?",
6280 new String[] {
6281 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
6282 String.valueOf(uid)}
6283 ) > 0;
6284 }
6285
6286 static void dumpAccountsTable(SQLiteDatabase db, PrintWriter pw) {
6287 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
6288 null, null, ACCOUNTS_TYPE, null, null);
6289 try {
6290 while (cursor.moveToNext()) {
6291 // print type,count
6292 pw.println(cursor.getString(0) + "," + cursor.getString(1));
6293 }
6294 } finally {
6295 if (cursor != null) {
6296 cursor.close();
6297 }
6298 }
6299 }
6300
6301 static void dumpDebugTable(SQLiteDatabase db, PrintWriter pw) {
6302 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
6303 null, null, null, null, DebugDbHelper.TIMESTAMP);
6304 pw.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
6305 pw.println("Accounts History");
6306 try {
6307 while (cursor.moveToNext()) {
6308 // print type,count
6309 pw.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
6310 cursor.getString(2) + "," + cursor.getString(3) + ","
6311 + cursor.getString(4) + "," + cursor.getString(5));
6312 }
6313 } finally {
6314 cursor.close();
6315 }
6316 }
6317
6318 }
Fred Quintana60307342009-03-24 22:48:12 -07006319}