blob: 8310c97de4aa6cc6f25d78a22d95a363925c1935 [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;
Fred Quintanaa698f422009-04-08 19:14:54 -070068import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.os.IBinder;
70import android.os.Looper;
71import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070072import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070073import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070074import android.os.RemoteException;
75import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070076import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070077import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070078import android.text.TextUtils;
79import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070080import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070081import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080082import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070083
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070084import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080085import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080086import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070087import com.android.server.FgThread;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000088import com.android.server.LocalServices;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070089import com.google.android.collect.Lists;
90import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070091
Oscar Montemayora8529f62009-11-18 10:14:20 -080092import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070093import java.io.FileDescriptor;
94import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -080095import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -070096import java.security.MessageDigest;
97import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070098import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -070099import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800100import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700101import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700102import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700103import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700104import java.util.HashSet;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800105import java.util.Iterator;
Fred Quintana56285a62010-12-02 14:20:51 -0800106import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700107import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800108import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800109import java.util.Map.Entry;
110import java.util.Set;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700111import java.util.concurrent.atomic.AtomicInteger;
112import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700113
Fred Quintana60307342009-03-24 22:48:12 -0700114/**
115 * A system service that provides account, password, and authtoken management for all
116 * accounts on the device. Some of these calls are implemented with the help of the corresponding
117 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
118 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700119 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700120 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700121 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700122public class AccountManagerService
123 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800124 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Sandra Kwan78812282015-11-04 11:19:47 -0800125
Fred Quintana60307342009-03-24 22:48:12 -0700126 private static final String TAG = "AccountManagerService";
127
Fred Quintana60307342009-03-24 22:48:12 -0700128 private static final String DATABASE_NAME = "accounts.db";
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800129 private static final int DATABASE_VERSION = 9;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700130
131 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700132
133 private final Context mContext;
134
Fred Quintana56285a62010-12-02 14:20:51 -0800135 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700136 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700137 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800138
Fred Quintana60307342009-03-24 22:48:12 -0700139 private final MessageHandler mMessageHandler;
140
141 // Messages that can be sent on mHandler
142 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700143 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700144
Fred Quintana56285a62010-12-02 14:20:51 -0800145 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700146
147 private static final String TABLE_ACCOUNTS = "accounts";
148 private static final String ACCOUNTS_ID = "_id";
149 private static final String ACCOUNTS_NAME = "name";
150 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700151 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700152 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700153 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800154 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
155 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700156
157 private static final String TABLE_AUTHTOKENS = "authtokens";
158 private static final String AUTHTOKENS_ID = "_id";
159 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
160 private static final String AUTHTOKENS_TYPE = "type";
161 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
162
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700163 private static final String TABLE_GRANTS = "grants";
164 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
165 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
166 private static final String GRANTS_GRANTEE_UID = "uid";
167
Fred Quintana60307342009-03-24 22:48:12 -0700168 private static final String TABLE_EXTRAS = "extras";
169 private static final String EXTRAS_ID = "_id";
170 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
171 private static final String EXTRAS_KEY = "key";
172 private static final String EXTRAS_VALUE = "value";
173
174 private static final String TABLE_META = "meta";
175 private static final String META_KEY = "key";
176 private static final String META_VALUE = "value";
177
Amith Yamasani67df64b2012-12-14 12:09:36 -0800178 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
179
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700180 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
181 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700182 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800183
Carlos Valdivia91979be2015-05-22 14:11:35 -0700184 static {
185 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
186 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
187 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700188
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700189 private static final String COUNT_OF_MATCHING_GRANTS = ""
190 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
191 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
192 + " AND " + GRANTS_GRANTEE_UID + "=?"
193 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
194 + " AND " + ACCOUNTS_NAME + "=?"
195 + " AND " + ACCOUNTS_TYPE + "=?";
196
Fred Quintana56285a62010-12-02 14:20:51 -0800197 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
198 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700199
Fred Quintana56285a62010-12-02 14:20:51 -0800200 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
201 AUTHTOKENS_AUTHTOKEN};
202
203 private static final String SELECTION_USERDATA_BY_ACCOUNT =
204 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
205 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
206
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800207 private static final String META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX =
208 "auth_uid_for_type:";
209 private static final String META_KEY_DELIMITER = ":";
210 private static final String SELECTION_META_BY_AUTHENTICATOR_TYPE = META_KEY + " LIKE ?";
211
Fred Quintanaa698f422009-04-08 19:14:54 -0700212 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700213 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
214
Amith Yamasani04e0d262012-02-14 11:50:53 -0800215 static class UserAccounts {
216 private final int userId;
217 private final DatabaseHelper openHelper;
218 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
219 credentialsPermissionNotificationIds =
220 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
221 private final HashMap<Account, Integer> signinRequiredNotificationIds =
222 new HashMap<Account, Integer>();
223 private final Object cacheLock = new Object();
224 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700225 private final HashMap<String, Account[]> accountCache =
226 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800227 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800228 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800229 new HashMap<Account, HashMap<String, String>>();
230 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800231 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800232 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700233
234 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700235 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700236
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700237 /**
238 * protected by the {@link #cacheLock}
239 *
240 * Caches the previous names associated with an account. Previous names
241 * should be cached because we expect that when an Account is renamed,
242 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
243 * want to know if the accounts they care about have been renamed.
244 *
245 * The previous names are wrapped in an {@link AtomicReference} so that
246 * we can distinguish between those accounts with no previous names and
247 * those whose previous names haven't been cached (yet).
248 */
249 private final HashMap<Account, AtomicReference<String>> previousNameCache =
250 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800251
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700252 private int debugDbInsertionPoint = -1;
253 private SQLiteStatement statementForLogging;
254
Amith Yamasani04e0d262012-02-14 11:50:53 -0800255 UserAccounts(Context context, int userId) {
256 this.userId = userId;
257 synchronized (cacheLock) {
258 openHelper = new DatabaseHelper(context, userId);
259 }
260 }
261 }
262
263 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
264
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700265 private static AtomicReference<AccountManagerService> sThis =
266 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700267 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700268
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700269 /**
270 * This should only be called by system code. One should only call this after the service
271 * has started.
272 * @return a reference to the AccountManagerService instance
273 * @hide
274 */
275 public static AccountManagerService getSingleton() {
276 return sThis.get();
277 }
Fred Quintana60307342009-03-24 22:48:12 -0700278
Fred Quintana56285a62010-12-02 14:20:51 -0800279 public AccountManagerService(Context context) {
280 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700281 }
282
Fred Quintana56285a62010-12-02 14:20:51 -0800283 public AccountManagerService(Context context, PackageManager packageManager,
284 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700285 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800286 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700287 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700288
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700289 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700290
Fred Quintana56285a62010-12-02 14:20:51 -0800291 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800292 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700293
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700294 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800295
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800296 IntentFilter intentFilter = new IntentFilter();
297 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
298 intentFilter.addDataScheme("package");
299 mContext.registerReceiver(new BroadcastReceiver() {
300 @Override
301 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700302 // Don't delete accounts when updating a authenticator's
303 // package.
304 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700305 /* Purging data requires file io, don't block the main thread. This is probably
306 * less than ideal because we are introducing a race condition where old grants
307 * could be exercised until they are purged. But that race condition existed
308 * anyway with the broadcast receiver.
309 *
310 * Ideally, we would completely clear the cache, purge data from the database,
311 * and then rebuild the cache. All under the cache lock. But that change is too
312 * large at this point.
313 */
314 Runnable r = new Runnable() {
315 @Override
316 public void run() {
317 purgeOldGrantsAll();
318 }
319 };
320 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700321 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800322 }
323 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800324
Amith Yamasani13593602012-03-22 16:16:17 -0700325 IntentFilter userFilter = new IntentFilter();
326 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Fyodor Kupolov041232a2016-02-22 15:01:45 -0800327 userFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800328 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700329 @Override
330 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800331 String action = intent.getAction();
332 if (Intent.ACTION_USER_REMOVED.equals(action)) {
333 onUserRemoved(intent);
Fyodor Kupolov041232a2016-02-22 15:01:45 -0800334 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
335 onUserUnlocked(intent);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800336 }
Amith Yamasani13593602012-03-22 16:16:17 -0700337 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800338 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800339 }
340
Dianne Hackborn164371f2013-10-01 19:10:13 -0700341 @Override
342 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
343 throws RemoteException {
344 try {
345 return super.onTransact(code, data, reply, flags);
346 } catch (RuntimeException e) {
347 // The account manager only throws security exceptions, so let's
348 // log all others.
349 if (!(e instanceof SecurityException)) {
350 Slog.wtf(TAG, "Account Manager Crash", e);
351 }
352 throw e;
353 }
354 }
355
Kenny Root26ff6622012-07-30 12:58:03 -0700356 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700357 }
358
Amith Yamasani258848d2012-08-10 17:06:33 -0700359 private UserManager getUserManager() {
360 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700361 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700362 }
363 return mUserManager;
364 }
365
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700366 /**
367 * Validate internal set of accounts against installed authenticators for
368 * given user. Clears cached authenticators before validating.
369 */
370 public void validateAccounts(int userId) {
371 final UserAccounts accounts = getUserAccounts(userId);
372
373 // Invalidate user-specific cache to make sure we catch any
374 // removed authenticators.
375 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
376 }
377
378 /**
379 * Validate internal set of accounts against installed authenticators for
380 * given user. Clear cached authenticators before validating when requested.
381 */
382 private void validateAccountsInternal(
383 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
384 if (invalidateAuthenticatorCache) {
385 mAuthenticatorCache.invalidateCache(accounts.userId);
386 }
387
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800388 final HashMap<String, Integer> knownAuth = new HashMap<>();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700389 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
390 mAuthenticatorCache.getAllServices(accounts.userId)) {
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800391 knownAuth.put(service.type.type, service.uid);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700392 }
393
Amith Yamasani04e0d262012-02-14 11:50:53 -0800394 synchronized (accounts.cacheLock) {
395 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800396 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800397
398 // Get a list of stored authenticator type and UID
399 Cursor metaCursor = db.query(
400 TABLE_META,
401 new String[] {META_KEY, META_VALUE},
402 SELECTION_META_BY_AUTHENTICATOR_TYPE,
403 new String[] {META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + "%"},
404 null /* groupBy */,
405 null /* having */,
406 META_KEY);
407 // Create a list of authenticator type whose previous uid no longer exists
408 HashSet<String> obsoleteAuthType = Sets.newHashSet();
409 try {
410 while (metaCursor.moveToNext()) {
411 String type = TextUtils.split(metaCursor.getString(0), META_KEY_DELIMITER)[1];
412 String uid = metaCursor.getString(1);
413 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(uid)) {
414 // Should never happen.
415 Slog.e(TAG, "Auth type empty: " + TextUtils.isEmpty(type)
416 + ", uid empty: " + TextUtils.isEmpty(uid));
417 continue;
418 }
419 Integer knownUid = knownAuth.get(type);
420 if (knownUid != null && uid.equals(knownUid.toString())) {
421 // Remove it from the knownAuth list if it's unchanged.
422 knownAuth.remove(type);
423 } else {
424 // Only add it to the list if it no longer exists or uid different
425 obsoleteAuthType.add(type);
426 // And delete it from the TABLE_META
427 db.delete(
428 TABLE_META,
429 META_KEY + "=? AND " + META_VALUE + "=?",
430 new String[] {
431 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + type,
432 uid}
433 );
434 }
435 }
436 } finally {
437 metaCursor.close();
438 }
439
440 // Add the newly registered authenticator to TABLE_META
441 Iterator<Entry<String, Integer>> iterator = knownAuth.entrySet().iterator();
442 while (iterator.hasNext()) {
443 Entry<String, Integer> entry = iterator.next();
444 ContentValues values = new ContentValues();
445 values.put(META_KEY,
446 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
447 values.put(META_VALUE, entry.getValue());
448 db.insert(TABLE_META, null, values);
449 }
450
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800451 Cursor cursor = db.query(TABLE_ACCOUNTS,
452 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800453 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800454 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800455 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800456 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700457 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800458 while (cursor.moveToNext()) {
459 final long accountId = cursor.getLong(0);
460 final String accountType = cursor.getString(1);
461 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700462
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800463 if (obsoleteAuthType.contains(accountType)) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700464 Slog.w(TAG, "deleting account " + accountName + " because type "
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800465 + accountType + "'s registered authenticator no longer exist.");
Fred Quintana56285a62010-12-02 14:20:51 -0800466 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
467 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700468
469 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
470 accountId, accounts);
471
Fred Quintana56285a62010-12-02 14:20:51 -0800472 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800473 accounts.userDataCache.remove(account);
474 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700475 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800476 } else {
477 ArrayList<String> accountNames = accountNamesByType.get(accountType);
478 if (accountNames == null) {
479 accountNames = new ArrayList<String>();
480 accountNamesByType.put(accountType, accountNames);
481 }
482 accountNames.add(accountName);
483 }
484 }
Andy McFadden2f362292012-01-20 14:43:38 -0800485 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800486 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800487 final String accountType = cur.getKey();
488 final ArrayList<String> accountNames = cur.getValue();
489 final Account[] accountsForType = new Account[accountNames.size()];
490 int i = 0;
491 for (String accountName : accountNames) {
492 accountsForType[i] = new Account(accountName, accountType);
493 ++i;
494 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800495 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800496 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800497 } finally {
498 cursor.close();
499 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800500 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800501 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800502 }
503 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700504 }
505
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800506 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
507 Context context,
508 int userId) {
509 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
510 HashMap<String, Integer> knownAuth = new HashMap<>();
511 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
512 .getAllServices(userId)) {
513 knownAuth.put(service.type.type, service.uid);
514 }
515 return knownAuth;
516 }
517
Amith Yamasani04e0d262012-02-14 11:50:53 -0800518 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700519 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800520 }
521
522 protected UserAccounts getUserAccounts(int userId) {
523 synchronized (mUsers) {
524 UserAccounts accounts = mUsers.get(userId);
525 if (accounts == null) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700526 accounts = new UserAccounts(mContext, userId);
527 initializeDebugDbSizeAndCompileSqlStatementForLogging(
528 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800529 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700530 purgeOldGrants(accounts);
531 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800532 }
533 return accounts;
534 }
535 }
536
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700537 private void purgeOldGrantsAll() {
538 synchronized (mUsers) {
539 for (int i = 0; i < mUsers.size(); i++) {
540 purgeOldGrants(mUsers.valueAt(i));
541 }
542 }
543 }
544
545 private void purgeOldGrants(UserAccounts accounts) {
546 synchronized (accounts.cacheLock) {
547 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
548 final Cursor cursor = db.query(TABLE_GRANTS,
549 new String[]{GRANTS_GRANTEE_UID},
550 null, null, GRANTS_GRANTEE_UID, null, null);
551 try {
552 while (cursor.moveToNext()) {
553 final int uid = cursor.getInt(0);
554 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
555 if (packageExists) {
556 continue;
557 }
558 Log.d(TAG, "deleting grants for UID " + uid
559 + " because its package is no longer installed");
560 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
561 new String[]{Integer.toString(uid)});
562 }
563 } finally {
564 cursor.close();
565 }
566 }
567 }
568
Amith Yamasani13593602012-03-22 16:16:17 -0700569 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700570 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700571 if (userId < 1) return;
572
573 UserAccounts accounts;
574 synchronized (mUsers) {
575 accounts = mUsers.get(userId);
576 mUsers.remove(userId);
577 }
578 if (accounts == null) {
579 File dbFile = new File(getDatabaseName(userId));
580 dbFile.delete();
581 return;
582 }
583
584 synchronized (accounts.cacheLock) {
585 accounts.openHelper.close();
586 File dbFile = new File(getDatabaseName(userId));
587 dbFile.delete();
588 }
589 }
590
Fyodor Kupolov041232a2016-02-22 15:01:45 -0800591 private void onUserUnlocked(Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800592 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
593 if (userId < 1) return;
594
595 // Check if there's a shared account that needs to be created as an account
596 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
597 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700598 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700599 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -0700600 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700601 : UserHandle.USER_SYSTEM;
602 if (parentUserId < 0) {
603 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
604 return;
605 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800606 for (Account sa : sharedAccounts) {
607 if (ArrayUtils.contains(accounts, sa)) continue;
608 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700609 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800610 }
611 }
612
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700613 @Override
614 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700615 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700616 }
617
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800618 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700619 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700620 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800621 if (Log.isLoggable(TAG, Log.VERBOSE)) {
622 Log.v(TAG, "getPassword: " + account
623 + ", caller's uid " + Binder.getCallingUid()
624 + ", pid " + Binder.getCallingPid());
625 }
Fred Quintana382601f2010-03-25 12:25:10 -0700626 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000627 int userId = UserHandle.getCallingUserId();
628 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700629 String msg = String.format(
630 "uid %s cannot get secrets for accounts of type: %s",
631 callingUid,
632 account.type);
633 throw new SecurityException(msg);
634 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700635 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700636 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700637 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800638 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700639 } finally {
640 restoreCallingIdentity(identityToken);
641 }
642 }
643
Amith Yamasani04e0d262012-02-14 11:50:53 -0800644 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700645 if (account == null) {
646 return null;
647 }
648
Amith Yamasani04e0d262012-02-14 11:50:53 -0800649 synchronized (accounts.cacheLock) {
650 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800651 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
652 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
653 new String[]{account.name, account.type}, null, null, null);
654 try {
655 if (cursor.moveToNext()) {
656 return cursor.getString(0);
657 }
658 return null;
659 } finally {
660 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700661 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700662 }
663 }
664
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800665 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700666 public String getPreviousName(Account account) {
667 if (Log.isLoggable(TAG, Log.VERBOSE)) {
668 Log.v(TAG, "getPreviousName: " + account
669 + ", caller's uid " + Binder.getCallingUid()
670 + ", pid " + Binder.getCallingPid());
671 }
672 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700673 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700674 long identityToken = clearCallingIdentity();
675 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700676 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700677 return readPreviousNameInternal(accounts, account);
678 } finally {
679 restoreCallingIdentity(identityToken);
680 }
681 }
682
683 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
684 if (account == null) {
685 return null;
686 }
687 synchronized (accounts.cacheLock) {
688 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
689 if (previousNameRef == null) {
690 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
691 Cursor cursor = db.query(
692 TABLE_ACCOUNTS,
693 new String[]{ ACCOUNTS_PREVIOUS_NAME },
694 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
695 new String[] { account.name, account.type },
696 null,
697 null,
698 null);
699 try {
700 if (cursor.moveToNext()) {
701 String previousName = cursor.getString(0);
702 previousNameRef = new AtomicReference<String>(previousName);
703 accounts.previousNameCache.put(account, previousNameRef);
704 return previousName;
705 } else {
706 return null;
707 }
708 } finally {
709 cursor.close();
710 }
711 } else {
712 return previousNameRef.get();
713 }
714 }
715 }
716
717 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700718 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700719 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800720 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700721 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
722 account, key, callingUid, Binder.getCallingPid());
723 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800724 }
Fred Quintana382601f2010-03-25 12:25:10 -0700725 if (account == null) throw new IllegalArgumentException("account is null");
726 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000727 int userId = UserHandle.getCallingUserId();
728 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700729 String msg = String.format(
730 "uid %s cannot get user data for accounts of type: %s",
731 callingUid,
732 account.type);
733 throw new SecurityException(msg);
734 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700735 long identityToken = clearCallingIdentity();
736 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700737 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +0000738 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700739 } finally {
740 restoreCallingIdentity(identityToken);
741 }
742 }
743
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800744 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100745 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700746 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800747 if (Log.isLoggable(TAG, Log.VERBOSE)) {
748 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100749 + "for user id " + userId
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700750 + "caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800751 + ", pid " + Binder.getCallingPid());
752 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100753 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700754 if (isCrossUser(callingUid, userId)) {
755 throw new SecurityException(
756 String.format(
757 "User %s tying to get authenticator types for %s" ,
758 UserHandle.getCallingUserId(),
759 userId));
760 }
761
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700762 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700763 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000764 return getAuthenticatorTypesInternal(userId);
765
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700766 } finally {
767 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700768 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700769 }
770
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000771 /**
772 * Should only be called inside of a clearCallingIdentity block.
773 */
774 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
775 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
776 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
777 AuthenticatorDescription[] types =
778 new AuthenticatorDescription[authenticatorCollection.size()];
779 int i = 0;
780 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
781 : authenticatorCollection) {
782 types[i] = authenticator.type;
783 i++;
784 }
785 return types;
786 }
787
788
789
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700790 private boolean isCrossUser(int callingUid, int userId) {
791 return (userId != UserHandle.getCallingUserId()
792 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100793 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700794 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
795 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100796 }
797
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700798 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700799 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700800 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800801 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700802 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700803 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800804 + ", pid " + Binder.getCallingPid());
805 }
Fred Quintana382601f2010-03-25 12:25:10 -0700806 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000807 int userId = UserHandle.getCallingUserId();
808 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700809 String msg = String.format(
810 "uid %s cannot explicitly add accounts of type: %s",
811 callingUid,
812 account.type);
813 throw new SecurityException(msg);
814 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700815 /*
816 * Child users are not allowed to add accounts. Only the accounts that are
817 * shared by the parent profile can be added to child profile.
818 *
819 * TODO: Only allow accounts that were shared to be added by
820 * a limited user.
821 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700822
Fred Quintana60307342009-03-24 22:48:12 -0700823 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700824 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700825 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700826 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000827 return addAccountInternal(accounts, account, password, extras, false, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700828 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700829 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700830 }
831 }
832
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000833 @Override
834 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700835 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700836 int callingUid = Binder.getCallingUid();
837 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
838 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000839 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700840 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800841 final UserAccounts fromAccounts = getUserAccounts(userFrom);
842 final UserAccounts toAccounts = getUserAccounts(userTo);
843 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000844 if (response != null) {
845 Bundle result = new Bundle();
846 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
847 try {
848 response.onResult(result);
849 } catch (RemoteException e) {
850 Slog.w(TAG, "Failed to report error back to the client." + e);
851 }
852 }
853 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800854 }
855
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000856 Slog.d(TAG, "Copying account " + account.name
857 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800858 long identityToken = clearCallingIdentity();
859 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000860 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800861 false /* stripAuthTokenFromResult */, account.name,
862 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700863 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800864 protected String toDebugString(long now) {
865 return super.toDebugString(now) + ", getAccountCredentialsForClone"
866 + ", " + account.type;
867 }
868
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700869 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800870 public void run() throws RemoteException {
871 mAuthenticator.getAccountCredentialsForCloning(this, account);
872 }
873
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700874 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800875 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000876 if (result != null
877 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
878 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700879 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800880 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800881 super.onResult(result);
882 }
883 }
884 }.bind();
885 } finally {
886 restoreCallingIdentity(identityToken);
887 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800888 }
889
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800890 @Override
891 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700892 final int callingUid = Binder.getCallingUid();
893 if (Log.isLoggable(TAG, Log.VERBOSE)) {
894 String msg = String.format(
895 "accountAuthenticated( account: %s, callerUid: %s)",
896 account,
897 callingUid);
898 Log.v(TAG, msg);
899 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800900 if (account == null) {
901 throw new IllegalArgumentException("account is null");
902 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000903 int userId = UserHandle.getCallingUserId();
904 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700905 String msg = String.format(
906 "uid %s cannot notify authentication for accounts of type: %s",
907 callingUid,
908 account.type);
909 throw new SecurityException(msg);
910 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000911
Benjamin Franzb6c0ce42015-11-05 10:06:51 +0000912 if (!canUserModifyAccounts(userId, callingUid) ||
913 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800914 return false;
915 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000916
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700917 long identityToken = clearCallingIdentity();
918 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000919 UserAccounts accounts = getUserAccounts(userId);
920 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700921 } finally {
922 restoreCallingIdentity(identityToken);
923 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -0700924 }
925
926 private boolean updateLastAuthenticatedTime(Account account) {
927 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800928 synchronized (accounts.cacheLock) {
929 final ContentValues values = new ContentValues();
930 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
931 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
932 int i = db.update(
933 TABLE_ACCOUNTS,
934 values,
935 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
936 new String[] {
937 account.name, account.type
938 });
939 if (i > 0) {
940 return true;
941 }
942 }
943 return false;
944 }
945
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000946 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700947 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
948 final int parentUserId){
Amith Yamasani67df64b2012-12-14 12:09:36 -0800949 long id = clearCallingIdentity();
950 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000951 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800952 false /* stripAuthTokenFromResult */, account.name,
953 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700954 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800955 protected String toDebugString(long now) {
956 return super.toDebugString(now) + ", getAccountCredentialsForClone"
957 + ", " + account.type;
958 }
959
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700960 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800961 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700962 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700963 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700964 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700965 for (Account acc : getAccounts(parentUserId,
966 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700967 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000968 mAuthenticator.addAccountFromCredentials(
969 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700970 break;
971 }
972 }
973 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800974 }
975
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700976 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800977 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000978 // TODO: Anything to do if if succedded?
979 // TODO: If it failed: Show error notification? Should we remove the shadow
980 // account to avoid retries?
981 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800982 }
983
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700984 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800985 public void onError(int errorCode, String errorMessage) {
986 super.onError(errorCode, errorMessage);
987 // TODO: Show error notification to user
988 // TODO: Should we remove the shadow account so that it doesn't keep trying?
989 }
990
991 }.bind();
992 } finally {
993 restoreCallingIdentity(id);
994 }
995 }
996
Amith Yamasani04e0d262012-02-14 11:50:53 -0800997 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700998 Bundle extras, boolean restricted, int callingUid) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700999 if (account == null) {
1000 return false;
1001 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001002 synchronized (accounts.cacheLock) {
1003 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001004 db.beginTransaction();
1005 try {
1006 long numMatches = DatabaseUtils.longForQuery(db,
1007 "select count(*) from " + TABLE_ACCOUNTS
1008 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
1009 new String[]{account.name, account.type});
1010 if (numMatches > 0) {
1011 Log.w(TAG, "insertAccountIntoDatabase: " + account
1012 + ", skipping since the account already exists");
1013 return false;
1014 }
1015 ContentValues values = new ContentValues();
1016 values.put(ACCOUNTS_NAME, account.name);
1017 values.put(ACCOUNTS_TYPE, account.type);
1018 values.put(ACCOUNTS_PASSWORD, password);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001019 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001020 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
1021 if (accountId < 0) {
1022 Log.w(TAG, "insertAccountIntoDatabase: " + account
1023 + ", skipping the DB insert failed");
1024 return false;
1025 }
1026 if (extras != null) {
1027 for (String key : extras.keySet()) {
1028 final String value = extras.getString(key);
1029 if (insertExtraLocked(db, accountId, key, value) < 0) {
1030 Log.w(TAG, "insertAccountIntoDatabase: " + account
1031 + ", skipping since insertExtra failed for key " + key);
1032 return false;
1033 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001034 }
1035 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001036 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001037
1038 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
1039 accounts, callingUid);
1040
Amith Yamasani04e0d262012-02-14 11:50:53 -08001041 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001042 } finally {
1043 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001044 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001045 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001046 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001047 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1048 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001049 }
1050 return true;
1051 }
1052
1053 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001054 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001055 * running, then clone the account too.
1056 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001057 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001058 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001059 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001060 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001061 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001062 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001063 addSharedAccountAsUser(account, user.id);
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001064 if (getUserManager().isUserUnlocked(user.id)) {
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001065 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
1066 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001067 }
1068 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001069 }
1070 }
1071
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001072 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -07001073 ContentValues values = new ContentValues();
1074 values.put(EXTRAS_KEY, key);
1075 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1076 values.put(EXTRAS_VALUE, value);
1077 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
1078 }
1079
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001080 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001081 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001082 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001083 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001084 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1085 Log.v(TAG, "hasFeatures: " + account
1086 + ", response " + response
1087 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001088 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001089 + ", pid " + Binder.getCallingPid());
1090 }
Fred Quintana382601f2010-03-25 12:25:10 -07001091 if (response == null) throw new IllegalArgumentException("response is null");
1092 if (account == null) throw new IllegalArgumentException("account is null");
1093 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001094 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001095 checkReadAccountsPermitted(callingUid, account.type, userId,
1096 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001097
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001098 long identityToken = clearCallingIdentity();
1099 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001100 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001101 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001102 } finally {
1103 restoreCallingIdentity(identityToken);
1104 }
1105 }
1106
1107 private class TestFeaturesSession extends Session {
1108 private final String[] mFeatures;
1109 private final Account mAccount;
1110
Amith Yamasani04e0d262012-02-14 11:50:53 -08001111 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001112 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001113 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001114 true /* stripAuthTokenFromResult */, account.name,
1115 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001116 mFeatures = features;
1117 mAccount = account;
1118 }
1119
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001120 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001121 public void run() throws RemoteException {
1122 try {
1123 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1124 } catch (RemoteException e) {
1125 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1126 }
1127 }
1128
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001129 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001130 public void onResult(Bundle result) {
1131 IAccountManagerResponse response = getResponseAndClose();
1132 if (response != null) {
1133 try {
1134 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001135 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001136 return;
1137 }
Fred Quintana56285a62010-12-02 14:20:51 -08001138 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1139 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1140 + response);
1141 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001142 final Bundle newResult = new Bundle();
1143 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1144 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1145 response.onResult(newResult);
1146 } catch (RemoteException e) {
1147 // if the caller is dead then there is no one to care about remote exceptions
1148 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1149 Log.v(TAG, "failure while notifying response", e);
1150 }
1151 }
1152 }
1153 }
1154
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001155 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001156 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001157 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001158 + ", " + mAccount
1159 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1160 }
1161 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001162
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001163 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001164 public void renameAccount(
1165 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001166 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001167 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1168 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001169 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001170 + ", pid " + Binder.getCallingPid());
1171 }
1172 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001173 int userId = UserHandle.getCallingUserId();
1174 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001175 String msg = String.format(
1176 "uid %s cannot rename accounts of type: %s",
1177 callingUid,
1178 accountToRename.type);
1179 throw new SecurityException(msg);
1180 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001181 long identityToken = clearCallingIdentity();
1182 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001183 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001184 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001185 Bundle result = new Bundle();
1186 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1187 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1188 try {
1189 response.onResult(result);
1190 } catch (RemoteException e) {
1191 Log.w(TAG, e.getMessage());
1192 }
1193 } finally {
1194 restoreCallingIdentity(identityToken);
1195 }
1196 }
1197
1198 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001199 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001200 Account resultAccount = null;
1201 /*
1202 * Cancel existing notifications. Let authenticators
1203 * re-post notifications as required. But we don't know if
1204 * the authenticators have bound their notifications to
1205 * now stale account name data.
1206 *
1207 * With a rename api, we might not need to do this anymore but it
1208 * shouldn't hurt.
1209 */
1210 cancelNotification(
1211 getSigninRequiredNotificationId(accounts, accountToRename),
1212 new UserHandle(accounts.userId));
1213 synchronized(accounts.credentialsPermissionNotificationIds) {
1214 for (Pair<Pair<Account, String>, Integer> pair:
1215 accounts.credentialsPermissionNotificationIds.keySet()) {
1216 if (accountToRename.equals(pair.first.first)) {
1217 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1218 cancelNotification(id, new UserHandle(accounts.userId));
1219 }
1220 }
1221 }
1222 synchronized (accounts.cacheLock) {
1223 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1224 db.beginTransaction();
1225 boolean isSuccessful = false;
1226 Account renamedAccount = new Account(newName, accountToRename.type);
1227 try {
1228 final ContentValues values = new ContentValues();
1229 values.put(ACCOUNTS_NAME, newName);
1230 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
1231 final long accountId = getAccountIdLocked(db, accountToRename);
1232 if (accountId >= 0) {
1233 final String[] argsAccountId = { String.valueOf(accountId) };
1234 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1235 db.setTransactionSuccessful();
1236 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001237 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1238 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001239 }
1240 } finally {
1241 db.endTransaction();
1242 if (isSuccessful) {
1243 /*
1244 * Database transaction was successful. Clean up cached
1245 * data associated with the account in the user profile.
1246 */
1247 insertAccountIntoCacheLocked(accounts, renamedAccount);
1248 /*
1249 * Extract the data and token caches before removing the
1250 * old account to preserve the user data associated with
1251 * the account.
1252 */
1253 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1254 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1255 removeAccountFromCacheLocked(accounts, accountToRename);
1256 /*
1257 * Update the cached data associated with the renamed
1258 * account.
1259 */
1260 accounts.userDataCache.put(renamedAccount, tmpData);
1261 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1262 accounts.previousNameCache.put(
1263 renamedAccount,
1264 new AtomicReference<String>(accountToRename.name));
1265 resultAccount = renamedAccount;
1266
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001267 int parentUserId = accounts.userId;
1268 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001269 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001270 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001271 * those users with which the account was shared.
1272 */
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001273 List<UserInfo> users = getUserManager().getUsers(true);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001274 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001275 if (user.isRestricted()
1276 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001277 renameSharedAccountAsUser(accountToRename, newName, user.id);
1278 }
1279 }
1280 }
1281 sendAccountsChangedBroadcast(accounts.userId);
1282 }
1283 }
1284 }
1285 return resultAccount;
1286 }
1287
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001288 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001289 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001290 return userInfo != null && userInfo.canHaveProfile();
1291 }
1292
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001293 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001294 public void removeAccount(IAccountManagerResponse response, Account account,
1295 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001296 removeAccountAsUser(
1297 response,
1298 account,
1299 expectActivityLaunch,
1300 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001301 }
1302
1303 @Override
1304 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001305 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001306 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001307 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1308 Log.v(TAG, "removeAccount: " + account
1309 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001310 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001311 + ", pid " + Binder.getCallingPid()
1312 + ", for user id " + userId);
1313 }
1314 if (response == null) throw new IllegalArgumentException("response is null");
1315 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001316 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001317 if (isCrossUser(callingUid, userId)) {
1318 throw new SecurityException(
1319 String.format(
1320 "User %s tying remove account for %s" ,
1321 UserHandle.getCallingUserId(),
1322 userId));
1323 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001324 /*
1325 * Only the system or authenticator should be allowed to remove accounts for that
1326 * authenticator. This will let users remove accounts (via Settings in the system) but not
1327 * arbitrary applications (like competing authenticators).
1328 */
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001329 UserHandle user = new UserHandle(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00001330 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1331 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001332 String msg = String.format(
1333 "uid %s cannot remove accounts of type: %s",
1334 callingUid,
1335 account.type);
1336 throw new SecurityException(msg);
1337 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001338 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001339 try {
1340 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1341 "User cannot modify accounts");
1342 } catch (RemoteException re) {
1343 }
1344 return;
1345 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001346 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001347 try {
1348 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1349 "User cannot modify accounts of this type (policy).");
1350 } catch (RemoteException re) {
1351 }
1352 return;
1353 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001354 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001355 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001356 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001357 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001358 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001359 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001360 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001361 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001362 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001363 }
1364 }
1365 }
1366
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001367 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1368
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001369 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001370 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1371 } finally {
1372 restoreCallingIdentity(identityToken);
1373 }
1374 }
1375
1376 @Override
1377 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001378 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001379 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1380 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001381 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001382 + ", pid " + Binder.getCallingPid());
1383 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001384 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001385 if (account == null) {
1386 /*
1387 * Null accounts should result in returning false, as per
1388 * AccountManage.addAccountExplicitly(...) java doc.
1389 */
1390 Log.e(TAG, "account is null");
1391 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001392 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001393 String msg = String.format(
1394 "uid %s cannot explicitly add accounts of type: %s",
1395 callingUid,
1396 account.type);
1397 throw new SecurityException(msg);
1398 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001399 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001400 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001401 long identityToken = clearCallingIdentity();
1402 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001403 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001404 } finally {
1405 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001406 }
Fred Quintana60307342009-03-24 22:48:12 -07001407 }
1408
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001409 private class RemoveAccountSession extends Session {
1410 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001411 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001412 Account account, boolean expectActivityLaunch) {
1413 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001414 true /* stripAuthTokenFromResult */, account.name,
1415 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001416 mAccount = account;
1417 }
1418
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001419 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001420 protected String toDebugString(long now) {
1421 return super.toDebugString(now) + ", removeAccount"
1422 + ", account " + mAccount;
1423 }
1424
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001425 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001426 public void run() throws RemoteException {
1427 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1428 }
1429
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001430 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001431 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001432 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1433 && !result.containsKey(AccountManager.KEY_INTENT)) {
1434 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001435 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001436 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001437 }
1438 IAccountManagerResponse response = getResponseAndClose();
1439 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001440 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1441 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1442 + response);
1443 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001444 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001445 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001446 try {
1447 response.onResult(result2);
1448 } catch (RemoteException e) {
1449 // ignore
1450 }
1451 }
1452 }
1453 super.onResult(result);
1454 }
1455 }
1456
Amith Yamasani04e0d262012-02-14 11:50:53 -08001457 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001458 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001459 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001460 }
1461
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001462 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001463 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001464 synchronized (accounts.cacheLock) {
1465 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001466 final long accountId = getAccountIdLocked(db, account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001467 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1468 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001469 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001470 removeAccountFromCacheLocked(accounts, account);
1471 sendAccountsChangedBroadcast(accounts.userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001472
1473 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001474 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001475 long id = Binder.clearCallingIdentity();
1476 try {
1477 int parentUserId = accounts.userId;
1478 if (canHaveProfile(parentUserId)) {
1479 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001480 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001481 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001482 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001483 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001484 }
1485 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001486 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001487 } finally {
1488 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001489 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001490 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001491 }
1492
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001493 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001494 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001495 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001496 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1497 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001498 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001499 + ", pid " + Binder.getCallingPid());
1500 }
Fred Quintana382601f2010-03-25 12:25:10 -07001501 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1502 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001503 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001504 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001505 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001506 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001507 synchronized (accounts.cacheLock) {
1508 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001509 db.beginTransaction();
1510 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001511 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001512 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001513 db.setTransactionSuccessful();
1514 } finally {
1515 db.endTransaction();
1516 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001517 }
Fred Quintana60307342009-03-24 22:48:12 -07001518 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001519 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001520 }
1521 }
1522
Carlos Valdivia91979be2015-05-22 14:11:35 -07001523 private void invalidateCustomTokenLocked(
1524 UserAccounts accounts,
1525 String accountType,
1526 String authToken) {
1527 if (authToken == null || accountType == null) {
1528 return;
1529 }
1530 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001531 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001532 }
1533
Amith Yamasani04e0d262012-02-14 11:50:53 -08001534 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1535 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001536 if (authToken == null || accountType == null) {
1537 return;
1538 }
Fred Quintana33269202009-04-20 16:05:10 -07001539 Cursor cursor = db.rawQuery(
1540 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1541 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1542 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1543 + " FROM " + TABLE_ACCOUNTS
1544 + " JOIN " + TABLE_AUTHTOKENS
1545 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1546 + " = " + AUTHTOKENS_ACCOUNTS_ID
1547 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1548 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1549 new String[]{authToken, accountType});
1550 try {
1551 while (cursor.moveToNext()) {
1552 long authTokenId = cursor.getLong(0);
1553 String accountName = cursor.getString(1);
1554 String authTokenType = cursor.getString(2);
1555 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001556 writeAuthTokenIntoCacheLocked(
1557 accounts,
1558 db,
1559 new Account(accountName, accountType),
1560 authTokenType,
1561 null);
Fred Quintana60307342009-03-24 22:48:12 -07001562 }
Fred Quintana33269202009-04-20 16:05:10 -07001563 } finally {
1564 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001565 }
1566 }
1567
Carlos Valdivia91979be2015-05-22 14:11:35 -07001568 private void saveCachedToken(
1569 UserAccounts accounts,
1570 Account account,
1571 String callerPkg,
1572 byte[] callerSigDigest,
1573 String tokenType,
1574 String token,
1575 long expiryMillis) {
1576
1577 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1578 return;
1579 }
1580 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1581 new UserHandle(accounts.userId));
1582 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001583 accounts.accountTokenCaches.put(
1584 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001585 }
1586 }
1587
Amith Yamasani04e0d262012-02-14 11:50:53 -08001588 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1589 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001590 if (account == null || type == null) {
1591 return false;
1592 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001593 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1594 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001595 synchronized (accounts.cacheLock) {
1596 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001597 db.beginTransaction();
1598 try {
1599 long accountId = getAccountIdLocked(db, account);
1600 if (accountId < 0) {
1601 return false;
1602 }
1603 db.delete(TABLE_AUTHTOKENS,
1604 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1605 new String[]{type});
1606 ContentValues values = new ContentValues();
1607 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1608 values.put(AUTHTOKENS_TYPE, type);
1609 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1610 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1611 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001612 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001613 return true;
1614 }
Fred Quintana33269202009-04-20 16:05:10 -07001615 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001616 } finally {
1617 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001618 }
Fred Quintana60307342009-03-24 22:48:12 -07001619 }
1620 }
1621
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001622 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001623 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001624 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001625 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1626 Log.v(TAG, "peekAuthToken: " + account
1627 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001628 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001629 + ", pid " + Binder.getCallingPid());
1630 }
Fred Quintana382601f2010-03-25 12:25:10 -07001631 if (account == null) throw new IllegalArgumentException("account is null");
1632 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001633 int userId = UserHandle.getCallingUserId();
1634 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001635 String msg = String.format(
1636 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1637 callingUid,
1638 account.type);
1639 throw new SecurityException(msg);
1640 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001641 long identityToken = clearCallingIdentity();
1642 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001643 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001644 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001645 } finally {
1646 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001647 }
Fred Quintana60307342009-03-24 22:48:12 -07001648 }
1649
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001650 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001651 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001652 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001653 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1654 Log.v(TAG, "setAuthToken: " + account
1655 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001656 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001657 + ", pid " + Binder.getCallingPid());
1658 }
Fred Quintana382601f2010-03-25 12:25:10 -07001659 if (account == null) throw new IllegalArgumentException("account is null");
1660 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001661 int userId = UserHandle.getCallingUserId();
1662 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001663 String msg = String.format(
1664 "uid %s cannot set auth tokens associated with accounts of type: %s",
1665 callingUid,
1666 account.type);
1667 throw new SecurityException(msg);
1668 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001669 long identityToken = clearCallingIdentity();
1670 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001671 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001672 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001673 } finally {
1674 restoreCallingIdentity(identityToken);
1675 }
Fred Quintana60307342009-03-24 22:48:12 -07001676 }
1677
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001678 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001679 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001680 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001681 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1682 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001683 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001684 + ", pid " + Binder.getCallingPid());
1685 }
Fred Quintana382601f2010-03-25 12:25:10 -07001686 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001687 int userId = UserHandle.getCallingUserId();
1688 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001689 String msg = String.format(
1690 "uid %s cannot set secrets for accounts of type: %s",
1691 callingUid,
1692 account.type);
1693 throw new SecurityException(msg);
1694 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001695 long identityToken = clearCallingIdentity();
1696 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001697 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001698 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001699 } finally {
1700 restoreCallingIdentity(identityToken);
1701 }
Fred Quintana60307342009-03-24 22:48:12 -07001702 }
1703
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001704 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1705 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001706 if (account == null) {
1707 return;
1708 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001709 synchronized (accounts.cacheLock) {
1710 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001711 db.beginTransaction();
1712 try {
1713 final ContentValues values = new ContentValues();
1714 values.put(ACCOUNTS_PASSWORD, password);
1715 final long accountId = getAccountIdLocked(db, account);
1716 if (accountId >= 0) {
1717 final String[] argsAccountId = {String.valueOf(accountId)};
1718 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1719 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001720 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001721 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001722 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001723
1724 String action = (password == null || password.length() == 0) ?
1725 DebugDbHelper.ACTION_CLEAR_PASSWORD
1726 : DebugDbHelper.ACTION_SET_PASSWORD;
1727 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001728 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001729 } finally {
1730 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001731 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001732 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001733 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001734 }
1735
Amith Yamasani04e0d262012-02-14 11:50:53 -08001736 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001737 Log.i(TAG, "the accounts changed, sending broadcast of "
1738 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001739 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001740 }
1741
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001742 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001743 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001744 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001745 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1746 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001747 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001748 + ", pid " + Binder.getCallingPid());
1749 }
Fred Quintana382601f2010-03-25 12:25:10 -07001750 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001751 int userId = UserHandle.getCallingUserId();
1752 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001753 String msg = String.format(
1754 "uid %s cannot clear passwords for accounts of type: %s",
1755 callingUid,
1756 account.type);
1757 throw new SecurityException(msg);
1758 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001759 long identityToken = clearCallingIdentity();
1760 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001761 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001762 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001763 } finally {
1764 restoreCallingIdentity(identityToken);
1765 }
Fred Quintana60307342009-03-24 22:48:12 -07001766 }
1767
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001768 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001769 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001770 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001771 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1772 Log.v(TAG, "setUserData: " + account
1773 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001774 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001775 + ", pid " + Binder.getCallingPid());
1776 }
Fred Quintana382601f2010-03-25 12:25:10 -07001777 if (key == null) throw new IllegalArgumentException("key is null");
1778 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001779 int userId = UserHandle.getCallingUserId();
1780 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001781 String msg = String.format(
1782 "uid %s cannot set user data for accounts of type: %s",
1783 callingUid,
1784 account.type);
1785 throw new SecurityException(msg);
1786 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001787 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001788 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001789 UserAccounts accounts = getUserAccounts(userId);
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001790 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001791 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001792 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001793 }
1794 }
1795
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001796 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001797 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001798 if (account == null || key == null) {
1799 return;
1800 }
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001801 synchronized (accounts.cacheLock) {
1802 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1803 db.beginTransaction();
1804 try {
1805 long accountId = getAccountIdLocked(db, account);
1806 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001807 return;
1808 }
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001809 long extrasId = getExtrasIdLocked(db, accountId, key);
1810 if (extrasId < 0 ) {
1811 extrasId = insertExtraLocked(db, accountId, key, value);
1812 if (extrasId < 0) {
1813 return;
1814 }
1815 } else {
1816 ContentValues values = new ContentValues();
1817 values.put(EXTRAS_VALUE, value);
1818 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1819 return;
1820 }
Simranjit Singh Kohlia666d742015-08-07 13:34:09 -07001821
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00001822 }
1823 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
1824 db.setTransactionSuccessful();
1825 } finally {
1826 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001827 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001828 }
1829 }
1830
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001831 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001832 if (result == null) {
1833 Log.e(TAG, "the result is unexpectedly null", new Exception());
1834 }
1835 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1836 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1837 + response);
1838 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001839 try {
1840 response.onResult(result);
1841 } catch (RemoteException e) {
1842 // if the caller is dead then there is no one to care about remote
1843 // exceptions
1844 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1845 Log.v(TAG, "failure while notifying response", e);
1846 }
1847 }
1848 }
1849
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001850 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001851 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1852 final String authTokenType)
1853 throws RemoteException {
1854 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001855 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1856
Fred Quintanad9640ec2012-05-23 12:37:00 -07001857 final int callingUid = getCallingUid();
1858 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001859 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001860 throw new SecurityException("can only call from system");
1861 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001862 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001863 long identityToken = clearCallingIdentity();
1864 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001865 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001866 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1867 false /* stripAuthTokenFromResult */, null /* accountName */,
1868 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001869 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001870 protected String toDebugString(long now) {
1871 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001872 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001873 + ", authTokenType " + authTokenType;
1874 }
1875
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001876 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001877 public void run() throws RemoteException {
1878 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1879 }
1880
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001881 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001882 public void onResult(Bundle result) {
1883 if (result != null) {
1884 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1885 Bundle bundle = new Bundle();
1886 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1887 super.onResult(bundle);
1888 return;
1889 } else {
1890 super.onResult(result);
1891 }
1892 }
1893 }.bind();
1894 } finally {
1895 restoreCallingIdentity(identityToken);
1896 }
1897 }
1898
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001899 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07001900 public void getAuthToken(
1901 IAccountManagerResponse response,
1902 final Account account,
1903 final String authTokenType,
1904 final boolean notifyOnAuthFailure,
1905 final boolean expectActivityLaunch,
1906 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001907 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1908 Log.v(TAG, "getAuthToken: " + account
1909 + ", response " + response
1910 + ", authTokenType " + authTokenType
1911 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1912 + ", expectActivityLaunch " + expectActivityLaunch
1913 + ", caller's uid " + Binder.getCallingUid()
1914 + ", pid " + Binder.getCallingPid());
1915 }
Fred Quintana382601f2010-03-25 12:25:10 -07001916 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001917 try {
1918 if (account == null) {
1919 Slog.w(TAG, "getAuthToken called with null account");
1920 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1921 return;
1922 }
1923 if (authTokenType == null) {
1924 Slog.w(TAG, "getAuthToken called with null authTokenType");
1925 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1926 return;
1927 }
1928 } catch (RemoteException e) {
1929 Slog.w(TAG, "Failed to report error back to the client." + e);
1930 return;
1931 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001932 int userId = UserHandle.getCallingUserId();
1933 long ident = Binder.clearCallingIdentity();
1934 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001935 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001936 try {
1937 accounts = getUserAccounts(userId);
1938 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1939 AuthenticatorDescription.newKey(account.type), accounts.userId);
1940 } finally {
1941 Binder.restoreCallingIdentity(ident);
1942 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001943
Costin Manolachea40c6302010-12-13 14:50:45 -08001944 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07001945 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08001946
1947 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001948 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001949 final boolean permissionGranted =
1950 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001951
Carlos Valdivia91979be2015-05-22 14:11:35 -07001952 // Get the calling package. We will use it for the purpose of caching.
1953 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07001954 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001955 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07001956 try {
1957 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
1958 } finally {
1959 Binder.restoreCallingIdentity(ident);
1960 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001961 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
1962 String msg = String.format(
1963 "Uid %s is attempting to illegally masquerade as package %s!",
1964 callerUid,
1965 callerPkg);
1966 throw new SecurityException(msg);
1967 }
1968
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001969 // let authenticator know the identity of the caller
1970 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1971 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07001972
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001973 if (notifyOnAuthFailure) {
1974 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001975 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001976
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001977 long identityToken = clearCallingIdentity();
1978 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07001979 // Distill the caller's package signatures into a single digest.
1980 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
1981
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001982 // if the caller has permission, do the peek. otherwise go the more expensive
1983 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001984 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001985 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001986 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001987 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001988 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1989 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1990 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001991 onResult(response, result);
1992 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001993 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001994 }
1995
Carlos Valdivia91979be2015-05-22 14:11:35 -07001996 if (customTokens) {
1997 /*
1998 * Look up tokens in the new cache only if the loginOptions don't have parameters
1999 * outside of those expected to be injected by the AccountManager, e.g.
2000 * ANDORID_PACKAGE_NAME.
2001 */
2002 String token = readCachedTokenInternal(
2003 accounts,
2004 account,
2005 authTokenType,
2006 callerPkg,
2007 callerPkgSigDigest);
2008 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002009 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2010 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2011 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002012 Bundle result = new Bundle();
2013 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2014 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2015 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2016 onResult(response, result);
2017 return;
2018 }
2019 }
2020
Amith Yamasani04e0d262012-02-14 11:50:53 -08002021 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002022 false /* stripAuthTokenFromResult */, account.name,
2023 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002024 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002025 protected String toDebugString(long now) {
2026 if (loginOptions != null) loginOptions.keySet();
2027 return super.toDebugString(now) + ", getAuthToken"
2028 + ", " + account
2029 + ", authTokenType " + authTokenType
2030 + ", loginOptions " + loginOptions
2031 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2032 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002033
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002034 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002035 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002036 // If the caller doesn't have permission then create and return the
2037 // "grant permission" intent instead of the "getAuthToken" intent.
2038 if (!permissionGranted) {
2039 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2040 } else {
2041 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2042 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002043 }
2044
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002045 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002046 public void onResult(Bundle result) {
2047 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002048 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002049 Intent intent = newGrantCredentialsPermissionIntent(
2050 account,
2051 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002052 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002053 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002054 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002055 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002056 onResult(bundle);
2057 return;
2058 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002059 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002060 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002061 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2062 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002063 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002064 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002065 "the type and name should not be empty");
2066 return;
2067 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002068 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002069 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002070 saveAuthTokenToDatabase(
2071 mAccounts,
2072 resultAccount,
2073 authTokenType,
2074 authToken);
2075 }
2076 long expiryMillis = result.getLong(
2077 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2078 if (customTokens
2079 && expiryMillis > System.currentTimeMillis()) {
2080 saveCachedToken(
2081 mAccounts,
2082 account,
2083 callerPkg,
2084 callerPkgSigDigest,
2085 authTokenType,
2086 authToken,
2087 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002088 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002089 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002090
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002091 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002092 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002093 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002094 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002095 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002096 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002097 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002098 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002099 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002100 }.bind();
2101 } finally {
2102 restoreCallingIdentity(identityToken);
2103 }
Fred Quintana60307342009-03-24 22:48:12 -07002104 }
2105
Carlos Valdivia91979be2015-05-22 14:11:35 -07002106 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2107 MessageDigest digester;
2108 try {
2109 digester = MessageDigest.getInstance("SHA-256");
2110 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2111 callerPkg, PackageManager.GET_SIGNATURES);
2112 for (Signature sig : pkgInfo.signatures) {
2113 digester.update(sig.toByteArray());
2114 }
2115 } catch (NoSuchAlgorithmException x) {
2116 Log.wtf(TAG, "SHA-256 should be available", x);
2117 digester = null;
2118 } catch (NameNotFoundException e) {
2119 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2120 digester = null;
2121 }
2122 return (digester == null) ? null : digester.digest();
2123 }
2124
Dianne Hackborn41203752012-08-31 14:05:51 -07002125 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2126 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002127 int uid = intent.getIntExtra(
2128 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2129 String authTokenType = intent.getStringExtra(
2130 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002131 final String titleAndSubtitle =
2132 mContext.getString(R.string.permission_request_notification_with_subtitle,
2133 account.name);
2134 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002135 String title = titleAndSubtitle;
2136 String subtitle = "";
2137 if (index > 0) {
2138 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002139 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002140 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002141 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002142 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002143 Notification n = new Notification.Builder(contextForUser)
2144 .setSmallIcon(android.R.drawable.stat_sys_warning)
2145 .setWhen(0)
2146 .setColor(contextForUser.getColor(
2147 com.android.internal.R.color.system_notification_accent_color))
2148 .setContentTitle(title)
2149 .setContentText(subtitle)
2150 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2151 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2152 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002153 installNotification(getCredentialPermissionNotificationId(
2154 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002155 }
2156
Costin Manolache5f383ad92010-12-02 16:44:46 -08002157 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002158 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002159
2160 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002161 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002162 // Since it was set in Eclair+ we can't change it without breaking apps using
2163 // the intent from a non-Activity context.
2164 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002165 intent.addCategory(
2166 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002167
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002168 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002169 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2170 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002171 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002172
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002173 return intent;
2174 }
2175
2176 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2177 int uid) {
2178 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002179 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002180 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002181 final Pair<Pair<Account, String>, Integer> key =
2182 new Pair<Pair<Account, String>, Integer>(
2183 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002184 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002185 if (id == null) {
2186 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002187 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002188 }
2189 }
2190 return id;
2191 }
2192
Amith Yamasani04e0d262012-02-14 11:50:53 -08002193 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002194 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002195 synchronized (accounts.signinRequiredNotificationIds) {
2196 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002197 if (id == null) {
2198 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002199 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002200 }
2201 }
2202 return id;
2203 }
2204
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002205 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002206 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002207 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002208 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08002209 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2210 Log.v(TAG, "addAccount: accountType " + accountType
2211 + ", response " + response
2212 + ", authTokenType " + authTokenType
2213 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2214 + ", expectActivityLaunch " + expectActivityLaunch
2215 + ", caller's uid " + Binder.getCallingUid()
2216 + ", pid " + Binder.getCallingPid());
2217 }
Fred Quintana382601f2010-03-25 12:25:10 -07002218 if (response == null) throw new IllegalArgumentException("response is null");
2219 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002220
Amith Yamasani71e6c692013-03-24 17:39:28 -07002221 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002222 final int uid = Binder.getCallingUid();
2223 final int userId = UserHandle.getUserId(uid);
2224 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002225 try {
2226 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2227 "User is not allowed to add an account!");
2228 } catch (RemoteException re) {
2229 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002230 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002231 return;
2232 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002233 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002234 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002235 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2236 "User cannot modify accounts of this type (policy).");
2237 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002238 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002239 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2240 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002241 return;
2242 }
2243
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002244 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002245 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2246 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2247 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2248
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002249 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002250 long identityToken = clearCallingIdentity();
2251 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002252 UserAccounts accounts = getUserAccounts(usrId);
2253 logRecordWithUid(
2254 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002255 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002256 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002257 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002258 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002259 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002260 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002261 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002262 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002263
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002264 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002265 protected String toDebugString(long now) {
2266 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002267 + ", accountType " + accountType
2268 + ", requiredFeatures "
2269 + (requiredFeatures != null
2270 ? TextUtils.join(",", requiredFeatures)
2271 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002272 }
2273 }.bind();
2274 } finally {
2275 restoreCallingIdentity(identityToken);
2276 }
Fred Quintana60307342009-03-24 22:48:12 -07002277 }
2278
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002279 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002280 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2281 final String authTokenType, final String[] requiredFeatures,
2282 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002283 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002284 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2285 Log.v(TAG, "addAccount: accountType " + accountType
2286 + ", response " + response
2287 + ", authTokenType " + authTokenType
2288 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2289 + ", expectActivityLaunch " + expectActivityLaunch
2290 + ", caller's uid " + Binder.getCallingUid()
2291 + ", pid " + Binder.getCallingPid()
2292 + ", for user id " + userId);
2293 }
2294 if (response == null) throw new IllegalArgumentException("response is null");
2295 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002296 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002297 if (isCrossUser(callingUid, userId)) {
2298 throw new SecurityException(
2299 String.format(
2300 "User %s trying to add account for %s" ,
2301 UserHandle.getCallingUserId(),
2302 userId));
2303 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002304
2305 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002306 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002307 try {
2308 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2309 "User is not allowed to add an account!");
2310 } catch (RemoteException re) {
2311 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002312 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002313 return;
2314 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002315 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002316 try {
2317 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2318 "User cannot modify accounts of this type (policy).");
2319 } catch (RemoteException re) {
2320 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002321 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2322 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002323 return;
2324 }
2325
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002326 final int pid = Binder.getCallingPid();
2327 final int uid = Binder.getCallingUid();
2328 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2329 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2330 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2331
2332 long identityToken = clearCallingIdentity();
2333 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002334 UserAccounts accounts = getUserAccounts(userId);
2335 logRecordWithUid(
2336 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002337 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002338 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002339 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002340 @Override
2341 public void run() throws RemoteException {
2342 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2343 options);
2344 }
2345
2346 @Override
2347 protected String toDebugString(long now) {
2348 return super.toDebugString(now) + ", addAccount"
2349 + ", accountType " + accountType
2350 + ", requiredFeatures "
2351 + (requiredFeatures != null
2352 ? TextUtils.join(",", requiredFeatures)
2353 : null);
2354 }
2355 }.bind();
2356 } finally {
2357 restoreCallingIdentity(identityToken);
2358 }
2359 }
2360
Sandra Kwan78812282015-11-04 11:19:47 -08002361 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002362 public void startAddAccountSession(
2363 final IAccountManagerResponse response,
2364 final String accountType,
2365 final String authTokenType,
2366 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002367 final boolean expectActivityLaunch,
2368 final Bundle optionsIn) {
2369 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2370 Log.v(TAG,
2371 "startAddAccountSession: accountType " + accountType
2372 + ", response " + response
2373 + ", authTokenType " + authTokenType
2374 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2375 + ", expectActivityLaunch " + expectActivityLaunch
2376 + ", caller's uid " + Binder.getCallingUid()
2377 + ", pid " + Binder.getCallingPid());
2378 }
2379 if (response == null) {
2380 throw new IllegalArgumentException("response is null");
2381 }
2382 if (accountType == null) {
2383 throw new IllegalArgumentException("accountType is null");
2384 }
2385
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002386 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002387 // Only allow system to start session
2388 if (!isSystemUid(uid)) {
2389 String msg = String.format(
2390 "uid %s cannot stat add account session.",
2391 uid);
2392 throw new SecurityException(msg);
2393 }
2394
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002395 final int userId = UserHandle.getUserId(uid);
2396 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002397 try {
2398 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2399 "User is not allowed to add an account!");
2400 } catch (RemoteException re) {
2401 }
2402 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2403 return;
2404 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002405 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002406 try {
2407 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2408 "User cannot modify accounts of this type (policy).");
2409 } catch (RemoteException re) {
2410 }
2411 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2412 userId);
2413 return;
2414 }
2415
2416 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08002417 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2418 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2419 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2420
2421 int usrId = UserHandle.getCallingUserId();
2422 long identityToken = clearCallingIdentity();
2423 try {
2424 UserAccounts accounts = getUserAccounts(usrId);
2425 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2426 TABLE_ACCOUNTS, uid);
2427 new StartAccountSession(accounts, response, accountType, expectActivityLaunch,
2428 null /* accountName */, false /* authDetailsRequired */,
2429 true /* updateLastAuthenticationTime */) {
2430 @Override
2431 public void run() throws RemoteException {
2432 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2433 requiredFeatures, options);
2434 }
2435
2436 @Override
2437 protected String toDebugString(long now) {
2438 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2439 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2440 + accountType + ", requiredFeatures "
2441 + (requiredFeatures != null ? requiredFeaturesStr : null);
2442 }
2443 }.bind();
2444 } finally {
2445 restoreCallingIdentity(identityToken);
2446 }
2447 }
2448
2449 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2450 private abstract class StartAccountSession extends Session {
2451
2452 public StartAccountSession(UserAccounts accounts, IAccountManagerResponse response,
2453 String accountType, boolean expectActivityLaunch, String accountName,
2454 boolean authDetailsRequired, boolean updateLastAuthenticationTime) {
2455 super(accounts, response, accountType, expectActivityLaunch,
2456 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2457 updateLastAuthenticationTime);
2458 }
2459
2460 @Override
2461 public void onResult(Bundle result) {
2462 mNumResults++;
2463 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08002464 if (result != null
2465 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08002466 checkKeyIntent(
2467 Binder.getCallingUid(),
2468 intent);
Sandra Kwan78812282015-11-04 11:19:47 -08002469 }
Sandra Kwan78812282015-11-04 11:19:47 -08002470 IAccountManagerResponse response;
2471 if (mExpectActivityLaunch && result != null
2472 && result.containsKey(AccountManager.KEY_INTENT)) {
2473 response = mResponse;
2474 } else {
2475 response = getResponseAndClose();
2476 }
2477 if (response == null) {
2478 return;
2479 }
2480 if (result == null) {
2481 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2482 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2483 + response);
2484 }
2485 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2486 "null bundle returned");
2487 return;
2488 }
2489
2490 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2491 // All AccountManager error codes are greater
2492 // than 0
2493 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2494 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2495 return;
2496 }
2497
2498 // Strip auth token from result.
2499 result.remove(AccountManager.KEY_AUTHTOKEN);
2500
2501 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2502 Log.v(TAG,
2503 getClass().getSimpleName() + " calling onResult() on response " + response);
2504 }
2505
2506 // Get the session bundle created by authenticator. The
2507 // bundle contains data necessary for finishing the session
2508 // later. The session bundle will be encrypted here and
2509 // decrypted later when trying to finish the session.
2510 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2511 if (sessionBundle != null) {
2512 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2513 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08002514 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002515 Log.w(TAG, "Account type in session bundle doesn't match request.");
2516 }
2517 // Add accountType info to session bundle. This will
2518 // override any value set by authenticator.
2519 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2520
2521 // Encrypt session bundle before returning to caller.
2522 try {
2523 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2524 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2525 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2526 } catch (GeneralSecurityException e) {
2527 if (Log.isLoggable(TAG, Log.DEBUG)) {
2528 Log.v(TAG, "Failed to encrypt session bundle!", e);
2529 }
2530 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2531 "failed to encrypt session bundle");
2532 return;
2533 }
2534 }
2535
2536 sendResponse(response, result);
2537 }
2538 }
2539
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002540 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08002541 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002542 @NonNull Bundle sessionBundle,
2543 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002544 Bundle appInfo,
2545 int userId) {
2546 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002547 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2548 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002549 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002550 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08002551 + ", caller's uid " + callingUid
2552 + ", caller's user id " + UserHandle.getCallingUserId()
2553 + ", pid " + Binder.getCallingPid()
2554 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002555 }
2556 if (response == null) {
2557 throw new IllegalArgumentException("response is null");
2558 }
2559
2560 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2561 // Account type is added to it before encryption.
2562 if (sessionBundle == null || sessionBundle.size() == 0) {
2563 throw new IllegalArgumentException("sessionBundle is empty");
2564 }
2565
Sandra Kwan0b84b452016-01-20 15:25:42 -08002566 // Only allow the system process to finish session for other users
2567 if (isCrossUser(callingUid, userId)) {
2568 throw new SecurityException(
2569 String.format(
2570 "User %s trying to finish session for %s without cross user permission",
2571 UserHandle.getCallingUserId(),
2572 userId));
2573 }
2574
Sandra Kwana578d112015-12-16 16:01:43 -08002575 // Only allow system to finish session
Sandra Kwan0b84b452016-01-20 15:25:42 -08002576 if (!isSystemUid(callingUid)) {
Sandra Kwana578d112015-12-16 16:01:43 -08002577 String msg = String.format(
Sandra Kwan0b84b452016-01-20 15:25:42 -08002578 "uid %s cannot finish session because it's not system uid.",
2579 callingUid);
Sandra Kwana578d112015-12-16 16:01:43 -08002580 throw new SecurityException(msg);
2581 }
2582
Sandra Kwan0b84b452016-01-20 15:25:42 -08002583 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002584 sendErrorResponse(response,
2585 AccountManager.ERROR_CODE_USER_RESTRICTED,
2586 "User is not allowed to add an account!");
2587 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2588 return;
2589 }
2590
2591 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002592 final Bundle decryptedBundle;
2593 final String accountType;
2594 // First decrypt session bundle to get account type for checking permission.
2595 try {
2596 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2597 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2598 if (decryptedBundle == null) {
2599 sendErrorResponse(
2600 response,
2601 AccountManager.ERROR_CODE_BAD_REQUEST,
2602 "failed to decrypt session bundle");
2603 return;
2604 }
2605 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2606 // Account type cannot be null. This should not happen if session bundle was created
2607 // properly by #StartAccountSession.
2608 if (TextUtils.isEmpty(accountType)) {
2609 sendErrorResponse(
2610 response,
2611 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2612 "accountType is empty");
2613 return;
2614 }
2615
2616 // If by any chances, decryptedBundle contains colliding keys with
2617 // system info
2618 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2619 // update credentials flow, we should replace with the new values of the current call.
2620 if (appInfo != null) {
2621 decryptedBundle.putAll(appInfo);
2622 }
2623
2624 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08002625 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002626 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2627 } catch (GeneralSecurityException e) {
2628 if (Log.isLoggable(TAG, Log.DEBUG)) {
2629 Log.v(TAG, "Failed to decrypt session bundle!", e);
2630 }
2631 sendErrorResponse(
2632 response,
2633 AccountManager.ERROR_CODE_BAD_REQUEST,
2634 "failed to decrypt session bundle");
2635 return;
2636 }
2637
Sandra Kwan0b84b452016-01-20 15:25:42 -08002638 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002639 sendErrorResponse(
2640 response,
2641 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2642 "User cannot modify accounts of this type (policy).");
2643 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2644 userId);
2645 return;
2646 }
2647
2648 long identityToken = clearCallingIdentity();
2649 try {
2650 UserAccounts accounts = getUserAccounts(userId);
2651 logRecordWithUid(
2652 accounts,
2653 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2654 TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08002655 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002656 new Session(
2657 accounts,
2658 response,
2659 accountType,
2660 expectActivityLaunch,
2661 true /* stripAuthTokenFromResult */,
2662 null /* accountName */,
2663 false /* authDetailsRequired */,
2664 true /* updateLastAuthenticationTime */) {
2665 @Override
2666 public void run() throws RemoteException {
2667 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2668 }
2669
2670 @Override
2671 protected String toDebugString(long now) {
2672 return super.toDebugString(now)
2673 + ", finishSession"
2674 + ", accountType " + accountType;
2675 }
2676 }.bind();
2677 } finally {
2678 restoreCallingIdentity(identityToken);
2679 }
2680 }
2681
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002682 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002683 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2684 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2685 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2686 long identityToken = clearCallingIdentity();
2687 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002688 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002689 } finally {
2690 restoreCallingIdentity(identityToken);
2691 }
2692 }
2693
2694 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002695 public void confirmCredentialsAsUser(
2696 IAccountManagerResponse response,
2697 final Account account,
2698 final Bundle options,
2699 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002700 int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002701 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002702 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2703 Log.v(TAG, "confirmCredentials: " + account
2704 + ", response " + response
2705 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002706 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002707 + ", pid " + Binder.getCallingPid());
2708 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002709 // Only allow the system process to read accounts of other users
2710 if (isCrossUser(callingUid, userId)) {
2711 throw new SecurityException(
2712 String.format(
2713 "User %s trying to confirm account credentials for %s" ,
2714 UserHandle.getCallingUserId(),
2715 userId));
2716 }
Fred Quintana382601f2010-03-25 12:25:10 -07002717 if (response == null) throw new IllegalArgumentException("response is null");
2718 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002719 long identityToken = clearCallingIdentity();
2720 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002721 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002722 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002723 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002724 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002725 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002726 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002727 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002728 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002729 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002730 protected String toDebugString(long now) {
2731 return super.toDebugString(now) + ", confirmCredentials"
2732 + ", " + account;
2733 }
2734 }.bind();
2735 } finally {
2736 restoreCallingIdentity(identityToken);
2737 }
Fred Quintana60307342009-03-24 22:48:12 -07002738 }
2739
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002740 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002741 public void updateCredentials(IAccountManagerResponse response, final Account account,
2742 final String authTokenType, final boolean expectActivityLaunch,
2743 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08002744 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2745 Log.v(TAG, "updateCredentials: " + account
2746 + ", response " + response
2747 + ", authTokenType " + authTokenType
2748 + ", expectActivityLaunch " + expectActivityLaunch
2749 + ", caller's uid " + Binder.getCallingUid()
2750 + ", pid " + Binder.getCallingPid());
2751 }
Fred Quintana382601f2010-03-25 12:25:10 -07002752 if (response == null) throw new IllegalArgumentException("response is null");
2753 if (account == null) throw new IllegalArgumentException("account is null");
2754 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002755 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002756 long identityToken = clearCallingIdentity();
2757 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002758 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002759 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002760 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002761 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002762 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002763 public void run() throws RemoteException {
2764 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2765 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002766 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002767 protected String toDebugString(long now) {
2768 if (loginOptions != null) loginOptions.keySet();
2769 return super.toDebugString(now) + ", updateCredentials"
2770 + ", " + account
2771 + ", authTokenType " + authTokenType
2772 + ", loginOptions " + loginOptions;
2773 }
2774 }.bind();
2775 } finally {
2776 restoreCallingIdentity(identityToken);
2777 }
Fred Quintana60307342009-03-24 22:48:12 -07002778 }
2779
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002780 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002781 public void startUpdateCredentialsSession(
2782 IAccountManagerResponse response,
2783 final Account account,
2784 final String authTokenType,
2785 final boolean expectActivityLaunch,
2786 final Bundle loginOptions) {
2787 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2788 Log.v(TAG,
2789 "startUpdateCredentialsSession: " + account + ", response " + response
2790 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
2791 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
2792 + ", pid " + Binder.getCallingPid());
2793 }
2794 if (response == null) {
2795 throw new IllegalArgumentException("response is null");
2796 }
2797 if (account == null) {
2798 throw new IllegalArgumentException("account is null");
2799 }
Sandra Kwana578d112015-12-16 16:01:43 -08002800
2801 final int uid = Binder.getCallingUid();
2802 // Only allow system to start session
2803 if (!isSystemUid(uid)) {
2804 String msg = String.format(
2805 "uid %s cannot start update credentials session.",
2806 uid);
2807 throw new SecurityException(msg);
2808 }
2809
Sandra Kwane68c37e2015-11-12 17:11:49 -08002810 int userId = UserHandle.getCallingUserId();
2811 long identityToken = clearCallingIdentity();
2812 try {
2813 UserAccounts accounts = getUserAccounts(userId);
2814 new StartAccountSession(
2815 accounts,
2816 response,
2817 account.type,
2818 expectActivityLaunch,
2819 account.name,
2820 false /* authDetailsRequired */,
2821 true /* updateLastCredentialTime */) {
2822 @Override
2823 public void run() throws RemoteException {
2824 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
2825 loginOptions);
2826 }
2827
2828 @Override
2829 protected String toDebugString(long now) {
2830 if (loginOptions != null)
2831 loginOptions.keySet();
2832 return super.toDebugString(now)
2833 + ", startUpdateCredentialsSession"
2834 + ", " + account
2835 + ", authTokenType " + authTokenType
2836 + ", loginOptions " + loginOptions;
2837 }
2838 }.bind();
2839 } finally {
2840 restoreCallingIdentity(identityToken);
2841 }
2842 }
2843
2844 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08002845 public void isCredentialsUpdateSuggested(
2846 IAccountManagerResponse response,
2847 final Account account,
2848 final String statusToken) {
2849 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2850 Log.v(TAG,
2851 "isCredentialsUpdateSuggested: " + account + ", response " + response
2852 + ", caller's uid " + Binder.getCallingUid()
2853 + ", pid " + Binder.getCallingPid());
2854 }
2855 if (response == null) {
2856 throw new IllegalArgumentException("response is null");
2857 }
2858 if (account == null) {
2859 throw new IllegalArgumentException("account is null");
2860 }
2861 if (TextUtils.isEmpty(statusToken)) {
2862 throw new IllegalArgumentException("status token is empty");
2863 }
2864
2865 int uid = Binder.getCallingUid();
2866 // Only allow system to start session
2867 if (!isSystemUid(uid)) {
2868 String msg = String.format(
2869 "uid %s cannot stat add account session.",
2870 uid);
2871 throw new SecurityException(msg);
2872 }
2873
2874 int usrId = UserHandle.getCallingUserId();
2875 long identityToken = clearCallingIdentity();
2876 try {
2877 UserAccounts accounts = getUserAccounts(usrId);
2878 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
2879 false /* stripAuthTokenFromResult */, account.name,
2880 false /* authDetailsRequired */) {
2881 @Override
2882 protected String toDebugString(long now) {
2883 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
2884 + ", " + account;
2885 }
2886
2887 @Override
2888 public void run() throws RemoteException {
2889 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
2890 }
2891
2892 @Override
2893 public void onResult(Bundle result) {
2894 IAccountManagerResponse response = getResponseAndClose();
2895 if (response == null) {
2896 return;
2897 }
2898
2899 if (result == null) {
2900 sendErrorResponse(
2901 response,
2902 AccountManager.ERROR_CODE_INVALID_RESPONSE,
2903 "null bundle");
2904 return;
2905 }
2906
2907 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2908 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2909 + response);
2910 }
2911 // Check to see if an error occurred. We know if an error occurred because all
2912 // error codes are greater than 0.
2913 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
2914 sendErrorResponse(response,
2915 result.getInt(AccountManager.KEY_ERROR_CODE),
2916 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2917 return;
2918 }
2919 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
2920 sendErrorResponse(
2921 response,
2922 AccountManager.ERROR_CODE_INVALID_RESPONSE,
2923 "no result in response");
2924 return;
2925 }
2926 final Bundle newResult = new Bundle();
2927 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
2928 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
2929 sendResponse(response, newResult);
2930 }
2931 }.bind();
2932 } finally {
2933 restoreCallingIdentity(identityToken);
2934 }
2935 }
2936
2937 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002938 public void editProperties(IAccountManagerResponse response, final String accountType,
2939 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002940 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002941 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2942 Log.v(TAG, "editProperties: accountType " + accountType
2943 + ", response " + response
2944 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002945 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002946 + ", pid " + Binder.getCallingPid());
2947 }
Fred Quintana382601f2010-03-25 12:25:10 -07002948 if (response == null) throw new IllegalArgumentException("response is null");
2949 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002950 int userId = UserHandle.getCallingUserId();
2951 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002952 String msg = String.format(
2953 "uid %s cannot edit authenticator properites for account type: %s",
2954 callingUid,
2955 accountType);
2956 throw new SecurityException(msg);
2957 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002958 long identityToken = clearCallingIdentity();
2959 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002960 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002961 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002962 true /* stripAuthTokenFromResult */, null /* accountName */,
2963 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002964 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002965 public void run() throws RemoteException {
2966 mAuthenticator.editProperties(this, mAccountType);
2967 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002968 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002969 protected String toDebugString(long now) {
2970 return super.toDebugString(now) + ", editProperties"
2971 + ", accountType " + accountType;
2972 }
2973 }.bind();
2974 } finally {
2975 restoreCallingIdentity(identityToken);
2976 }
Fred Quintana60307342009-03-24 22:48:12 -07002977 }
2978
Amith Yamasani12747872015-12-07 14:19:49 -08002979 @Override
2980 public boolean someUserHasAccount(@NonNull final Account account) {
2981 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
2982 throw new SecurityException("Only system can check for accounts across users");
2983 }
2984 final long token = Binder.clearCallingIdentity();
2985 try {
2986 AccountAndUser[] allAccounts = getAllAccounts();
2987 for (int i = allAccounts.length - 1; i >= 0; i--) {
2988 if (allAccounts[i].account.equals(account)) {
2989 return true;
2990 }
2991 }
2992 return false;
2993 } finally {
2994 Binder.restoreCallingIdentity(token);
2995 }
2996 }
2997
Fred Quintana33269202009-04-20 16:05:10 -07002998 private class GetAccountsByTypeAndFeatureSession extends Session {
2999 private final String[] mFeatures;
3000 private volatile Account[] mAccountsOfType = null;
3001 private volatile ArrayList<Account> mAccountsWithFeatures = null;
3002 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003003 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003004
Amith Yamasani04e0d262012-02-14 11:50:53 -08003005 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003006 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003007 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003008 true /* stripAuthTokenFromResult */, null /* accountName */,
3009 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003010 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07003011 mFeatures = features;
3012 }
3013
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003014 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003015 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08003016 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003017 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
3018 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003019 }
Fred Quintana33269202009-04-20 16:05:10 -07003020 // check whether each account matches the requested features
3021 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
3022 mCurrentAccount = 0;
3023
3024 checkAccount();
3025 }
3026
3027 public void checkAccount() {
3028 if (mCurrentAccount >= mAccountsOfType.length) {
3029 sendResult();
3030 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07003031 }
Fred Quintana33269202009-04-20 16:05:10 -07003032
Fred Quintana29e94b82010-03-10 12:11:51 -08003033 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
3034 if (accountAuthenticator == null) {
3035 // It is possible that the authenticator has died, which is indicated by
3036 // mAuthenticator being set to null. If this happens then just abort.
3037 // There is no need to send back a result or error in this case since
3038 // that already happened when mAuthenticator was cleared.
3039 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3040 Log.v(TAG, "checkAccount: aborting session since we are no longer"
3041 + " connected to the authenticator, " + toDebugString());
3042 }
3043 return;
3044 }
Fred Quintana33269202009-04-20 16:05:10 -07003045 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08003046 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07003047 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003048 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07003049 }
3050 }
3051
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003052 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003053 public void onResult(Bundle result) {
3054 mNumResults++;
3055 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003056 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07003057 return;
3058 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003059 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07003060 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
3061 }
3062 mCurrentAccount++;
3063 checkAccount();
3064 }
3065
3066 public void sendResult() {
3067 IAccountManagerResponse response = getResponseAndClose();
3068 if (response != null) {
3069 try {
3070 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3071 for (int i = 0; i < accounts.length; i++) {
3072 accounts[i] = mAccountsWithFeatures.get(i);
3073 }
Fred Quintana56285a62010-12-02 14:20:51 -08003074 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3075 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3076 + response);
3077 }
Fred Quintana33269202009-04-20 16:05:10 -07003078 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003079 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003080 response.onResult(result);
3081 } catch (RemoteException e) {
3082 // if the caller is dead then there is no one to care about remote exceptions
3083 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3084 Log.v(TAG, "failure while notifying response", e);
3085 }
3086 }
3087 }
3088 }
3089
3090
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003091 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003092 protected String toDebugString(long now) {
3093 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3094 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3095 }
3096 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003097
Amith Yamasani04e0d262012-02-14 11:50:53 -08003098 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003099 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003100 * @hide
3101 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003102 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003103 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003104 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003105 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3106 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003107 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003108 return new Account[0];
3109 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003110 long identityToken = clearCallingIdentity();
3111 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003112 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003113 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003114 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003115 callingUid,
3116 null, // packageName
3117 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003118 } finally {
3119 restoreCallingIdentity(identityToken);
3120 }
3121 }
3122
Amith Yamasanif29f2362012-04-05 18:29:52 -07003123 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003124 * Returns accounts for all running users.
3125 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003126 * @hide
3127 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003128 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003129 public AccountAndUser[] getRunningAccounts() {
3130 final int[] runningUserIds;
3131 try {
3132 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3133 } catch (RemoteException e) {
3134 // Running in system_server; should never happen
3135 throw new RuntimeException(e);
3136 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003137 return getAccounts(runningUserIds);
3138 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003139
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003140 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003141 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003142 public AccountAndUser[] getAllAccounts() {
3143 final List<UserInfo> users = getUserManager().getUsers();
3144 final int[] userIds = new int[users.size()];
3145 for (int i = 0; i < userIds.length; i++) {
3146 userIds[i] = users.get(i).id;
3147 }
3148 return getAccounts(userIds);
3149 }
3150
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003151 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003152 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003153 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003154 for (int userId : userIds) {
3155 UserAccounts userAccounts = getUserAccounts(userId);
3156 if (userAccounts == null) continue;
3157 synchronized (userAccounts.cacheLock) {
3158 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3159 Binder.getCallingUid(), null);
3160 for (int a = 0; a < accounts.length; a++) {
3161 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003162 }
3163 }
3164 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003165
3166 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3167 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003168 }
3169
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003170 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003171 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003172 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3173 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003174 }
3175
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003176 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003177 private Account[] getAccountsAsUser(
3178 String type,
3179 int userId,
3180 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003181 int packageUid,
3182 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003183 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003184 // Only allow the system process to read accounts of other users
3185 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003186 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003187 && mContext.checkCallingOrSelfPermission(
3188 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3189 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003190 throw new SecurityException("User " + UserHandle.getCallingUserId()
3191 + " trying to get account for " + userId);
3192 }
3193
Fred Quintana56285a62010-12-02 14:20:51 -08003194 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3195 Log.v(TAG, "getAccounts: accountType " + type
3196 + ", caller's uid " + Binder.getCallingUid()
3197 + ", pid " + Binder.getCallingPid());
3198 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003199 // If the original calling app was using the framework account chooser activity, we'll
3200 // be passed in the original caller's uid here, which is what should be used for filtering.
3201 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3202 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003203 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003204 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003205
Svetoslavf3f02ac2015-09-08 14:36:35 -07003206 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3207 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003208 if (visibleAccountTypes.isEmpty()
3209 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003210 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003211 } else if (visibleAccountTypes.contains(type)) {
3212 // Prune the list down to just the requested type.
3213 visibleAccountTypes = new ArrayList<>();
3214 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003215 } // else aggregate all the visible accounts (it won't matter if the
3216 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003217
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003218 long identityToken = clearCallingIdentity();
3219 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003220 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003221 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003222 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003223 callingUid,
3224 callingPackage,
3225 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003226 } finally {
3227 restoreCallingIdentity(identityToken);
3228 }
3229 }
3230
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003231 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003232 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003233 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003234 int callingUid,
3235 String callingPackage,
3236 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003237 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003238 ArrayList<Account> visibleAccounts = new ArrayList<>();
3239 for (String visibleType : visibleAccountTypes) {
3240 Account[] accountsForType = getAccountsFromCacheLocked(
3241 userAccounts, visibleType, callingUid, callingPackage);
3242 if (accountsForType != null) {
3243 visibleAccounts.addAll(Arrays.asList(accountsForType));
3244 }
3245 }
3246 Account[] result = new Account[visibleAccounts.size()];
3247 for (int i = 0; i < visibleAccounts.size(); i++) {
3248 result[i] = visibleAccounts.get(i);
3249 }
3250 return result;
3251 }
3252 }
3253
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003254 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003255 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
3256 checkManageUsersPermission("addSharedAccountsFromParentUser");
3257 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3258 for (Account account : accounts) {
3259 addSharedAccountAsUser(account, userId);
3260 }
3261 }
3262
3263 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003264 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003265 UserAccounts accounts = getUserAccounts(userId);
3266 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003267 ContentValues values = new ContentValues();
3268 values.put(ACCOUNTS_NAME, account.name);
3269 values.put(ACCOUNTS_TYPE, account.type);
3270 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3271 new String[] {account.name, account.type});
3272 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3273 if (accountId < 0) {
3274 Log.w(TAG, "insertAccountIntoDatabase: " + account
3275 + ", skipping the DB insert failed");
3276 return false;
3277 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003278 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003279 return true;
3280 }
3281
3282 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003283 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3284 userId = handleIncomingUser(userId);
3285 UserAccounts accounts = getUserAccounts(userId);
3286 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003287 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003288 final ContentValues values = new ContentValues();
3289 values.put(ACCOUNTS_NAME, newName);
3290 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
3291 int r = db.update(
3292 TABLE_SHARED_ACCOUNTS,
3293 values,
3294 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3295 new String[] { account.name, account.type });
3296 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003297 int callingUid = getCallingUid();
3298 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3299 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003300 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003301 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003302 }
3303 return r > 0;
3304 }
3305
3306 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003307 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003308 return removeSharedAccountAsUser(account, userId, getCallingUid());
3309 }
3310
3311 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003312 userId = handleIncomingUser(userId);
3313 UserAccounts accounts = getUserAccounts(userId);
3314 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003315 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003316 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3317 new String[] {account.name, account.type});
3318 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003319 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3320 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003321 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003322 }
3323 return r > 0;
3324 }
3325
3326 @Override
3327 public Account[] getSharedAccountsAsUser(int userId) {
3328 userId = handleIncomingUser(userId);
3329 UserAccounts accounts = getUserAccounts(userId);
3330 ArrayList<Account> accountList = new ArrayList<Account>();
3331 Cursor cursor = null;
3332 try {
3333 cursor = accounts.openHelper.getReadableDatabase()
3334 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3335 null, null, null, null, null);
3336 if (cursor != null && cursor.moveToFirst()) {
3337 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3338 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3339 do {
3340 accountList.add(new Account(cursor.getString(nameIndex),
3341 cursor.getString(typeIndex)));
3342 } while (cursor.moveToNext());
3343 }
3344 } finally {
3345 if (cursor != null) {
3346 cursor.close();
3347 }
3348 }
3349 Account[] accountArray = new Account[accountList.size()];
3350 accountList.toArray(accountArray);
3351 return accountArray;
3352 }
3353
3354 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003355 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003356 public Account[] getAccounts(String type, String opPackageName) {
3357 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003358 }
3359
Amith Yamasani27db4682013-03-30 17:07:47 -07003360 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003361 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003362 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003363 int callingUid = Binder.getCallingUid();
3364 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3365 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3366 + callingUid + " with uid=" + uid);
3367 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003368 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3369 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003370 }
3371
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003372 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003373 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003374 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3375 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003376 int packageUid = -1;
3377 try {
3378 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07003379 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3380 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003381 } catch (RemoteException re) {
3382 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3383 return new Account[0];
3384 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003385 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3386 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003387 }
3388
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003389 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003390 public void getAccountsByFeatures(
3391 IAccountManagerResponse response,
3392 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003393 String[] features,
3394 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003395 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003396 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3397 Log.v(TAG, "getAccounts: accountType " + type
3398 + ", response " + response
3399 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003400 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003401 + ", pid " + Binder.getCallingPid());
3402 }
Fred Quintana382601f2010-03-25 12:25:10 -07003403 if (response == null) throw new IllegalArgumentException("response is null");
3404 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003405 int userId = UserHandle.getCallingUserId();
3406
Svetoslavf3f02ac2015-09-08 14:36:35 -07003407 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3408 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003409 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003410 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003411 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003412 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3413 try {
3414 response.onResult(result);
3415 } catch (RemoteException e) {
3416 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3417 }
3418 return;
3419 }
Fred Quintana33269202009-04-20 16:05:10 -07003420 long identityToken = clearCallingIdentity();
3421 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003422 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003423 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003424 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003425 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003426 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003427 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08003428 Bundle result = new Bundle();
3429 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3430 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003431 return;
3432 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003433 new GetAccountsByTypeAndFeatureSession(
3434 userAccounts,
3435 response,
3436 type,
3437 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003438 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07003439 } finally {
3440 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07003441 }
3442 }
3443
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003444 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3445 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3446 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3447 try {
3448 if (cursor.moveToNext()) {
3449 return cursor.getLong(0);
3450 }
3451 return -1;
3452 } finally {
3453 cursor.close();
3454 }
3455 }
3456
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003457 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07003458 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003459 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07003460 try {
3461 if (cursor.moveToNext()) {
3462 return cursor.getLong(0);
3463 }
3464 return -1;
3465 } finally {
3466 cursor.close();
3467 }
3468 }
3469
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003470 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07003471 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
3472 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3473 new String[]{key}, null, null, null);
3474 try {
3475 if (cursor.moveToNext()) {
3476 return cursor.getLong(0);
3477 }
3478 return -1;
3479 } finally {
3480 cursor.close();
3481 }
3482 }
3483
Fred Quintanaa698f422009-04-08 19:14:54 -07003484 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07003485 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07003486 IAccountManagerResponse mResponse;
3487 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003488 final boolean mExpectActivityLaunch;
3489 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003490 final String mAccountName;
3491 // Indicates if we need to add auth details(like last credential time)
3492 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003493 // If set, we need to update the last authenticated time. This is
3494 // currently
3495 // used on
3496 // successful confirming credentials.
3497 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07003498
Fred Quintana33269202009-04-20 16:05:10 -07003499 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07003500 private int mNumRequestContinued = 0;
3501 private int mNumErrors = 0;
3502
Fred Quintana60307342009-03-24 22:48:12 -07003503 IAccountAuthenticator mAuthenticator = null;
3504
Fred Quintana8570f742010-02-18 10:32:54 -08003505 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003506 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003507
Amith Yamasani04e0d262012-02-14 11:50:53 -08003508 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003509 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3510 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003511 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3512 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3513 }
3514
3515 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3516 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3517 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07003518 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003519 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07003520 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08003521 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003522 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07003523 mResponse = response;
3524 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003525 mExpectActivityLaunch = expectActivityLaunch;
3526 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003527 mAccountName = accountName;
3528 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003529 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003530
Fred Quintanaa698f422009-04-08 19:14:54 -07003531 synchronized (mSessions) {
3532 mSessions.put(toString(), this);
3533 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003534 if (response != null) {
3535 try {
3536 response.asBinder().linkToDeath(this, 0 /* flags */);
3537 } catch (RemoteException e) {
3538 mResponse = null;
3539 binderDied();
3540 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003541 }
Fred Quintana60307342009-03-24 22:48:12 -07003542 }
3543
Fred Quintanaa698f422009-04-08 19:14:54 -07003544 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07003545 if (mResponse == null) {
3546 // this session has already been closed
3547 return null;
3548 }
Fred Quintana60307342009-03-24 22:48:12 -07003549 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07003550 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07003551 return response;
3552 }
3553
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003554 /**
3555 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
3556 * security policy.
3557 *
3558 * In particular we want to make sure that the Authenticator doesn't try to trick users
3559 * into launching aribtrary intents on the device via by tricking to click authenticator
3560 * supplied entries in the system Settings app.
3561 */
3562 protected void checkKeyIntent(
3563 int authUid,
3564 Intent intent) throws SecurityException {
3565 long bid = Binder.clearCallingIdentity();
3566 try {
3567 PackageManager pm = mContext.getPackageManager();
3568 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3569 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
3570 int targetUid = targetActivityInfo.applicationInfo.uid;
3571 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid)) {
3572 String pkgName = targetActivityInfo.packageName;
3573 String activityName = targetActivityInfo.name;
3574 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
3575 + "does not share a signature with the supplying authenticator (%s).";
3576 throw new SecurityException(
3577 String.format(tmpl, activityName, pkgName, mAccountType));
3578 }
3579 } finally {
3580 Binder.restoreCallingIdentity(bid);
3581 }
3582 }
3583
Fred Quintanaa698f422009-04-08 19:14:54 -07003584 private void close() {
3585 synchronized (mSessions) {
3586 if (mSessions.remove(toString()) == null) {
3587 // the session was already closed, so bail out now
3588 return;
3589 }
3590 }
3591 if (mResponse != null) {
3592 // stop listening for response deaths
3593 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3594
3595 // clear this so that we don't accidentally send any further results
3596 mResponse = null;
3597 }
3598 cancelTimeout();
3599 unbind();
3600 }
3601
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003602 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003603 public void binderDied() {
3604 mResponse = null;
3605 close();
3606 }
3607
3608 protected String toDebugString() {
3609 return toDebugString(SystemClock.elapsedRealtime());
3610 }
3611
3612 protected String toDebugString(long now) {
3613 return "Session: expectLaunch " + mExpectActivityLaunch
3614 + ", connected " + (mAuthenticator != null)
3615 + ", stats (" + mNumResults + "/" + mNumRequestContinued
3616 + "/" + mNumErrors + ")"
3617 + ", lifetime " + ((now - mCreationTime) / 1000.0);
3618 }
3619
Fred Quintana60307342009-03-24 22:48:12 -07003620 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003621 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3622 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3623 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003624 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003625 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003626 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003627 }
3628 }
3629
3630 private void unbind() {
3631 if (mAuthenticator != null) {
3632 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003633 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003634 }
3635 }
3636
Fred Quintana60307342009-03-24 22:48:12 -07003637 public void cancelTimeout() {
3638 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3639 }
3640
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003641 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003642 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003643 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003644 try {
3645 run();
3646 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003647 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003648 "remote exception");
3649 }
Fred Quintana60307342009-03-24 22:48:12 -07003650 }
3651
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003652 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003653 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003654 mAuthenticator = null;
3655 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003656 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003657 try {
3658 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3659 "disconnected");
3660 } catch (RemoteException e) {
3661 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3662 Log.v(TAG, "Session.onServiceDisconnected: "
3663 + "caught RemoteException while responding", e);
3664 }
3665 }
Fred Quintana60307342009-03-24 22:48:12 -07003666 }
3667 }
3668
Fred Quintanab839afc2009-10-14 15:57:28 -07003669 public abstract void run() throws RemoteException;
3670
Fred Quintana60307342009-03-24 22:48:12 -07003671 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003672 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003673 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003674 try {
3675 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3676 "timeout");
3677 } catch (RemoteException e) {
3678 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3679 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3680 e);
3681 }
3682 }
Fred Quintana60307342009-03-24 22:48:12 -07003683 }
3684 }
3685
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003686 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003687 public void onResult(Bundle result) {
3688 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003689 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003690 if (result != null) {
3691 boolean isSuccessfulConfirmCreds = result.getBoolean(
3692 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003693 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003694 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3695 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003696 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003697 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3698 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003699 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003700 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003701 if (needUpdate || mAuthDetailsRequired) {
3702 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3703 if (needUpdate && accountPresent) {
3704 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3705 }
3706 if (mAuthDetailsRequired) {
3707 long lastAuthenticatedTime = -1;
3708 if (accountPresent) {
3709 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3710 mAccounts.openHelper.getReadableDatabase(),
3711 "select " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3712 + " from " +
3713 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3714 + ACCOUNTS_TYPE + "=?",
3715 new String[] {
3716 mAccountName, mAccountType
3717 });
3718 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003719 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003720 lastAuthenticatedTime);
3721 }
3722 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003723 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003724 if (result != null
3725 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003726 checkKeyIntent(
3727 Binder.getCallingUid(),
3728 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003729 }
3730 if (result != null
3731 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003732 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3733 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003734 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3735 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003736 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3737 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003738 }
Fred Quintana60307342009-03-24 22:48:12 -07003739 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003740 IAccountManagerResponse response;
3741 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003742 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003743 response = mResponse;
3744 } else {
3745 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003746 }
Fred Quintana60307342009-03-24 22:48:12 -07003747 if (response != null) {
3748 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07003749 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08003750 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3751 Log.v(TAG, getClass().getSimpleName()
3752 + " calling onError() on response " + response);
3753 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003754 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07003755 "null bundle returned");
3756 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08003757 if (mStripAuthTokenFromResult) {
3758 result.remove(AccountManager.KEY_AUTHTOKEN);
3759 }
Fred Quintana56285a62010-12-02 14:20:51 -08003760 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3761 Log.v(TAG, getClass().getSimpleName()
3762 + " calling onResult() on response " + response);
3763 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003764 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3765 (intent == null)) {
3766 // All AccountManager error codes are greater than 0
3767 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3768 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3769 } else {
3770 response.onResult(result);
3771 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003772 }
Fred Quintana60307342009-03-24 22:48:12 -07003773 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003774 // if the caller is dead then there is no one to care about remote exceptions
3775 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3776 Log.v(TAG, "failure while notifying response", e);
3777 }
Fred Quintana60307342009-03-24 22:48:12 -07003778 }
3779 }
3780 }
Fred Quintana60307342009-03-24 22:48:12 -07003781
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003782 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003783 public void onRequestContinued() {
3784 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003785 }
3786
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003787 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003788 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003789 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003790 IAccountManagerResponse response = getResponseAndClose();
3791 if (response != null) {
3792 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003793 Log.v(TAG, getClass().getSimpleName()
3794 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003795 }
3796 try {
3797 response.onError(errorCode, errorMessage);
3798 } catch (RemoteException e) {
3799 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3800 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3801 }
3802 }
3803 } else {
3804 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3805 Log.v(TAG, "Session.onError: already closed");
3806 }
Fred Quintana60307342009-03-24 22:48:12 -07003807 }
3808 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003809
3810 /**
3811 * find the component name for the authenticator and initiate a bind
3812 * if no authenticator or the bind fails then return false, otherwise return true
3813 */
3814 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003815 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3816 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3817 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003818 if (authenticatorInfo == null) {
3819 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3820 Log.v(TAG, "there is no authenticator for " + authenticatorType
3821 + ", bailing out");
3822 }
3823 return false;
3824 }
3825
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07003826 final ActivityManager am = mContext.getSystemService(ActivityManager.class);
3827 if (am.isUserRunningAndLocked(mAccounts.userId)
3828 && !authenticatorInfo.componentInfo.encryptionAware) {
3829 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
3830 + " which isn't encryption aware");
3831 return false;
3832 }
3833
Fred Quintanab839afc2009-10-14 15:57:28 -07003834 Intent intent = new Intent();
3835 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3836 intent.setComponent(authenticatorInfo.componentName);
3837 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3838 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3839 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003840 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
3841 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003842 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3843 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3844 }
3845 return false;
3846 }
3847
Fred Quintanab839afc2009-10-14 15:57:28 -07003848 return true;
3849 }
Fred Quintana60307342009-03-24 22:48:12 -07003850 }
3851
3852 private class MessageHandler extends Handler {
3853 MessageHandler(Looper looper) {
3854 super(looper);
3855 }
Costin Manolache3348f142009-09-29 18:58:36 -07003856
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003857 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003858 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07003859 switch (msg.what) {
3860 case MESSAGE_TIMED_OUT:
3861 Session session = (Session)msg.obj;
3862 session.onTimedOut();
3863 break;
3864
Amith Yamasani5be347b2013-03-31 17:44:31 -07003865 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00003866 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07003867 break;
3868
Fred Quintana60307342009-03-24 22:48:12 -07003869 default:
3870 throw new IllegalStateException("unhandled message: " + msg.what);
3871 }
3872 }
3873 }
3874
Amith Yamasani04e0d262012-02-14 11:50:53 -08003875 private static String getDatabaseName(int userId) {
Jeff Sharkey8212ae02016-02-10 14:46:43 -07003876 File systemDir = Environment.getDataSystemDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07003877 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003878 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07003879 // Migrate old file, if it exists, to the new location.
3880 // Make sure the new file doesn't already exist. A dummy file could have been
3881 // accidentally created in the old location, causing the new one to become corrupted
3882 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08003883 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07003884 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07003885 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07003886 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07003887 if (!userDir.exists()) {
3888 if (!userDir.mkdirs()) {
3889 throw new IllegalStateException("User dir cannot be created: " + userDir);
3890 }
3891 }
3892 if (!oldFile.renameTo(databaseFile)) {
3893 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
3894 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003895 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003896 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003897 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08003898 }
3899
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003900 private static class DebugDbHelper{
3901 private DebugDbHelper() {
3902 }
3903
3904 private static String TABLE_DEBUG = "debug_table";
3905
3906 // Columns for the table
3907 private static String ACTION_TYPE = "action_type";
3908 private static String TIMESTAMP = "time";
3909 private static String CALLER_UID = "caller_uid";
3910 private static String TABLE_NAME = "table_name";
3911 private static String KEY = "primary_key";
3912
3913 // These actions correspond to the occurrence of real actions. Since
3914 // these are called by the authenticators, the uid associated will be
3915 // of the authenticator.
3916 private static String ACTION_SET_PASSWORD = "action_set_password";
3917 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
3918 private static String ACTION_ACCOUNT_ADD = "action_account_add";
3919 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
3920 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
3921 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
3922
3923 // These actions don't necessarily correspond to any action on
3924 // accountDb taking place. As an example, there might be a request for
3925 // addingAccount, which might not lead to addition of account on grounds
3926 // of bad authentication. We will still be logging it to keep track of
3927 // who called.
3928 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
3929 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003930
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003931 //This action doesn't add account to accountdb. Account is only
3932 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08003933 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003934 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
3935 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08003936
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003937 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3938
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003939 private static void createDebugTable(SQLiteDatabase db) {
3940 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
3941 + ACCOUNTS_ID + " INTEGER,"
3942 + ACTION_TYPE + " TEXT NOT NULL, "
3943 + TIMESTAMP + " DATETIME,"
3944 + CALLER_UID + " INTEGER NOT NULL,"
3945 + TABLE_NAME + " TEXT NOT NULL,"
3946 + KEY + " INTEGER PRIMARY KEY)");
3947 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
3948 }
3949 }
3950
3951 private void logRecord(UserAccounts accounts, String action, String tableName) {
3952 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3953 logRecord(db, action, tableName, -1, accounts);
3954 }
3955
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003956 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
3957 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3958 logRecord(db, action, tableName, -1, accounts, uid);
3959 }
3960
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003961 /*
3962 * This function receives an opened writable database.
3963 */
3964 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3965 UserAccounts userAccount) {
3966 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
3967 }
3968
3969 /*
3970 * This function receives an opened writable database.
3971 */
3972 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3973 UserAccounts userAccount, int callingUid) {
3974 SQLiteStatement logStatement = userAccount.statementForLogging;
3975 logStatement.bindLong(1, accountId);
3976 logStatement.bindString(2, action);
3977 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
3978 logStatement.bindLong(4, callingUid);
3979 logStatement.bindString(5, tableName);
3980 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
3981 logStatement.execute();
3982 logStatement.clearBindings();
3983 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
3984 % MAX_DEBUG_DB_SIZE;
3985 }
3986
3987 /*
3988 * This should only be called once to compile the sql statement for logging
3989 * and to find the insertion point.
3990 */
3991 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
3992 UserAccounts userAccount) {
3993 // Initialize the count if not done earlier.
3994 int size = (int) getDebugTableRowCount(db);
3995 if (size >= MAX_DEBUG_DB_SIZE) {
3996 // Table is full, and we need to find the point where to insert.
3997 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
3998 } else {
3999 userAccount.debugDbInsertionPoint = size;
4000 }
4001 compileSqlStatementForLogging(db, userAccount);
4002 }
4003
4004 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
4005 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
4006 + " VALUES (?,?,?,?,?,?)";
4007 userAccount.statementForLogging = db.compileStatement(sql);
4008 }
4009
4010 private long getDebugTableRowCount(SQLiteDatabase db) {
4011 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
4012 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4013 }
4014
4015 /*
4016 * Finds the row key where the next insertion should take place. This should
4017 * be invoked only if the table has reached its full capacity.
4018 */
4019 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
4020 // This query finds the smallest timestamp value (and if 2 records have
4021 // same timestamp, the choose the lower id).
4022 String queryCountDebugDbRows = new StringBuilder()
4023 .append("SELECT ").append(DebugDbHelper.KEY)
4024 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
4025 .append(" ORDER BY ")
4026 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
4027 .append(" LIMIT 1")
4028 .toString();
4029 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
4030 }
4031
Amith Yamasani04e0d262012-02-14 11:50:53 -08004032 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08004033
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004034 private final Context mContext;
4035 private final int mUserId;
4036
Amith Yamasani04e0d262012-02-14 11:50:53 -08004037 public DatabaseHelper(Context context, int userId) {
4038 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004039 mContext = context;
4040 mUserId = userId;
Fred Quintana60307342009-03-24 22:48:12 -07004041 }
4042
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004043 /**
4044 * This call needs to be made while the mCacheLock is held. The way to
4045 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
4046 * @param db The database.
4047 */
Fred Quintana60307342009-03-24 22:48:12 -07004048 @Override
4049 public void onCreate(SQLiteDatabase db) {
4050 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
4051 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4052 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4053 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4054 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004055 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004056 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
Fred Quintana60307342009-03-24 22:48:12 -07004057 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4058
4059 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
4060 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4061 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4062 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
4063 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
4064 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
4065
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004066 createGrantsTable(db);
4067
Fred Quintana60307342009-03-24 22:48:12 -07004068 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
4069 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4070 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
4071 + EXTRAS_KEY + " TEXT NOT NULL, "
4072 + EXTRAS_VALUE + " TEXT, "
4073 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
4074
4075 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
4076 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
4077 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07004078
Amith Yamasani67df64b2012-12-14 12:09:36 -08004079 createSharedAccountsTable(db);
4080
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004081 createAccountsDeletionTrigger(db);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004082
4083 DebugDbHelper.createDebugTable(db);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004084 }
4085
Amith Yamasani67df64b2012-12-14 12:09:36 -08004086 private void createSharedAccountsTable(SQLiteDatabase db) {
4087 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4088 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4089 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4090 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4091 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4092 }
4093
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004094 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4095 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4096 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4097 }
4098
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004099 private void addOldAccountNameColumn(SQLiteDatabase db) {
4100 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4101 }
4102
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004103 private void addDebugTable(SQLiteDatabase db) {
4104 DebugDbHelper.createDebugTable(db);
4105 }
4106
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004107 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004108 db.execSQL(""
4109 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4110 + " BEGIN"
4111 + " DELETE FROM " + TABLE_AUTHTOKENS
4112 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4113 + " DELETE FROM " + TABLE_EXTRAS
4114 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004115 + " DELETE FROM " + TABLE_GRANTS
4116 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004117 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004118 }
4119
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004120 private void createGrantsTable(SQLiteDatabase db) {
4121 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4122 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4123 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4124 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4125 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4126 + "," + GRANTS_GRANTEE_UID + "))");
4127 }
4128
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004129 private void populateMetaTableWithAuthTypeAndUID(
4130 SQLiteDatabase db,
4131 Map<String, Integer> authTypeAndUIDMap) {
4132 Iterator<Entry<String, Integer>> iterator = authTypeAndUIDMap.entrySet().iterator();
4133 while (iterator.hasNext()) {
4134 Entry<String, Integer> entry = iterator.next();
4135 ContentValues values = new ContentValues();
4136 values.put(META_KEY,
4137 META_KEY_FOR_AUTHENTICATOR_UID_FOR_TYPE_PREFIX + entry.getKey());
4138 values.put(META_VALUE, entry.getValue());
4139 db.insert(TABLE_META, null, values);
4140 }
4141 }
4142
Fred Quintana60307342009-03-24 22:48:12 -07004143 @Override
4144 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004145 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004146
Fred Quintanaa698f422009-04-08 19:14:54 -07004147 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004148 // no longer need to do anything since the work is done
4149 // when upgrading from version 2
4150 oldVersion++;
4151 }
4152
4153 if (oldVersion == 2) {
4154 createGrantsTable(db);
4155 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4156 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004157 oldVersion++;
4158 }
Costin Manolache3348f142009-09-29 18:58:36 -07004159
4160 if (oldVersion == 3) {
4161 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4162 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4163 oldVersion++;
4164 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004165
4166 if (oldVersion == 4) {
4167 createSharedAccountsTable(db);
4168 oldVersion++;
4169 }
4170
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004171 if (oldVersion == 5) {
4172 addOldAccountNameColumn(db);
4173 oldVersion++;
4174 }
4175
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004176 if (oldVersion == 6) {
4177 addLastSuccessfullAuthenticatedTimeColumn(db);
4178 oldVersion++;
4179 }
4180
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004181 if (oldVersion == 7) {
4182 addDebugTable(db);
4183 oldVersion++;
4184 }
4185
Sandra Kwan1c9026d2016-02-23 10:22:15 -08004186 if (oldVersion == 8) {
4187 populateMetaTableWithAuthTypeAndUID(
4188 db,
4189 AccountManagerService.getAuthenticatorTypeAndUIDForUser(mContext, mUserId));
4190 oldVersion++;
4191 }
4192
Amith Yamasani67df64b2012-12-14 12:09:36 -08004193 if (oldVersion != newVersion) {
4194 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4195 }
Fred Quintana60307342009-03-24 22:48:12 -07004196 }
4197
4198 @Override
4199 public void onOpen(SQLiteDatabase db) {
4200 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4201 }
4202 }
4203
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004204 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004205 return asBinder();
4206 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004207
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004208 /**
4209 * Searches array of arguments for the specified string
4210 * @param args array of argument strings
4211 * @param value value to search for
4212 * @return true if the value is contained in the array
4213 */
4214 private static boolean scanArgs(String[] args, String value) {
4215 if (args != null) {
4216 for (String arg : args) {
4217 if (value.equals(arg)) {
4218 return true;
4219 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004220 }
4221 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004222 return false;
4223 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004224
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004225 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004226 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07004227 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4228 != PackageManager.PERMISSION_GRANTED) {
4229 fout.println("Permission Denial: can't dump AccountsManager from from pid="
4230 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4231 + " without permission " + android.Manifest.permission.DUMP);
4232 return;
4233 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004234 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004235 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004236
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004237 final List<UserInfo> users = getUserManager().getUsers();
4238 for (UserInfo user : users) {
4239 ipw.println("User " + user + ":");
4240 ipw.increaseIndent();
4241 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4242 ipw.println();
4243 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08004244 }
4245 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004246
Amith Yamasani04e0d262012-02-14 11:50:53 -08004247 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4248 String[] args, boolean isCheckinRequest) {
4249 synchronized (userAccounts.cacheLock) {
4250 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004251
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004252 if (isCheckinRequest) {
4253 // This is a checkin request. *Only* upload the account types and the count of each.
4254 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4255 null, null, ACCOUNTS_TYPE, null, null);
4256 try {
4257 while (cursor.moveToNext()) {
4258 // print type,count
4259 fout.println(cursor.getString(0) + "," + cursor.getString(1));
4260 }
4261 } finally {
4262 if (cursor != null) {
4263 cursor.close();
4264 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004265 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004266 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004267 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07004268 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004269 fout.println("Accounts: " + accounts.length);
4270 for (Account account : accounts) {
4271 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004272 }
Fred Quintana307da1a2010-01-21 14:24:20 -08004273
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004274 // Add debug information.
4275 fout.println();
4276 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4277 null, null, null, null, DebugDbHelper.TIMESTAMP);
4278 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4279 fout.println("Accounts History");
4280 try {
4281 while (cursor.moveToNext()) {
4282 // print type,count
4283 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4284 cursor.getString(2) + "," + cursor.getString(3) + ","
4285 + cursor.getString(4) + "," + cursor.getString(5));
4286 }
4287 } finally {
4288 cursor.close();
4289 }
4290
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004291 fout.println();
4292 synchronized (mSessions) {
4293 final long now = SystemClock.elapsedRealtime();
4294 fout.println("Active Sessions: " + mSessions.size());
4295 for (Session session : mSessions.values()) {
4296 fout.println(" " + session.toDebugString(now));
4297 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004298 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004299
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004300 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004301 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004302 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004303 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004304 }
4305
Amith Yamasani04e0d262012-02-14 11:50:53 -08004306 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07004307 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004308 long identityToken = clearCallingIdentity();
4309 try {
4310 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4311 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4312 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004313
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004314 if (intent.getComponent() != null &&
4315 GrantCredentialsPermissionActivity.class.getName().equals(
4316 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004317 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004318 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004319 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004320 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004321 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004322 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07004323 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004324 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004325 Notification n = new Notification.Builder(contextForUser)
4326 .setWhen(0)
4327 .setSmallIcon(android.R.drawable.stat_sys_warning)
4328 .setColor(contextForUser.getColor(
4329 com.android.internal.R.color.system_notification_accent_color))
4330 .setContentTitle(String.format(notificationTitleFormat, account.name))
4331 .setContentText(message)
4332 .setContentIntent(PendingIntent.getActivityAsUser(
4333 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4334 null, user))
4335 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004336 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004337 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004338 } finally {
4339 restoreCallingIdentity(identityToken);
4340 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004341 }
4342
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004343 protected void installNotification(final int notificationId, final Notification n,
4344 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08004345 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004346 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08004347 }
4348
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004349 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004350 long identityToken = clearCallingIdentity();
4351 try {
4352 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004353 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004354 } finally {
4355 restoreCallingIdentity(identityToken);
4356 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004357 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004358
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004359 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
4360 for (String perm : permissions) {
4361 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
4362 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4363 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
4364 }
4365 final int opCode = AppOpsManager.permissionToOpCode(perm);
4366 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
4367 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
4368 return true;
4369 }
4370 }
4371 }
4372 return false;
4373 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004374
Amith Yamasani67df64b2012-12-14 12:09:36 -08004375 private int handleIncomingUser(int userId) {
4376 try {
4377 return ActivityManagerNative.getDefault().handleIncomingUser(
4378 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
4379 } catch (RemoteException re) {
4380 // Shouldn't happen, local.
4381 }
4382 return userId;
4383 }
4384
Christopher Tateccbf84f2013-05-08 15:25:41 -07004385 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004386 final int callingUserId = UserHandle.getUserId(callingUid);
4387
4388 final PackageManager userPackageManager;
4389 try {
4390 userPackageManager = mContext.createPackageContextAsUser(
4391 "android", 0, new UserHandle(callingUserId)).getPackageManager();
4392 } catch (NameNotFoundException e) {
4393 return false;
4394 }
4395
4396 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07004397 for (String name : packages) {
4398 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004399 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08004400 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08004401 && (packageInfo.applicationInfo.privateFlags
4402 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07004403 return true;
4404 }
4405 } catch (PackageManager.NameNotFoundException e) {
4406 return false;
4407 }
4408 }
4409 return false;
4410 }
4411
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004412 private boolean permissionIsGranted(
4413 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07004414 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07004415 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004416 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07004417 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08004418 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004419 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4420 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08004421 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004422 + ": is authenticator? " + fromAuthenticator
4423 + ", has explicit permission? " + hasExplicitGrants);
4424 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07004425 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004426 }
4427
Svetoslavf3f02ac2015-09-08 14:36:35 -07004428 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
4429 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004430 if (accountType == null) {
4431 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004432 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07004433 return getTypesVisibleToCaller(callingUid, userId,
4434 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004435 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004436 }
4437
4438 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
4439 if (accountType == null) {
4440 return false;
4441 } else {
4442 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
4443 }
4444 }
4445
Svetoslavf3f02ac2015-09-08 14:36:35 -07004446 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
4447 String opPackageName) {
Ian Pedowitz358e51f2016-03-15 17:08:27 +00004448 boolean isPermitted =
4449 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
4450 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004451 return getTypesForCaller(callingUid, userId, isPermitted);
4452 }
4453
4454 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
4455 return getTypesForCaller(callingUid, userId, false);
4456 }
4457
4458 private List<String> getTypesForCaller(
4459 int callingUid, int userId, boolean isOtherwisePermitted) {
4460 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004461 long identityToken = Binder.clearCallingIdentity();
4462 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
4463 try {
4464 serviceInfos = mAuthenticatorCache.getAllServices(userId);
4465 } finally {
4466 Binder.restoreCallingIdentity(identityToken);
4467 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004468 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004469 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004470 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
4471 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
4472 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004473 }
4474 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004475 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004476 }
4477
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004478 private boolean isAccountPresentForCaller(String accountName, String accountType) {
4479 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
4480 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
4481 if (account.name.equals(accountName)) {
4482 return true;
4483 }
4484 }
4485 }
4486 return false;
4487 }
4488
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004489 private static void checkManageUsersPermission(String message) {
4490 if (ActivityManager.checkComponentPermission(
4491 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
4492 != PackageManager.PERMISSION_GRANTED) {
4493 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
4494 }
4495 }
4496
Amith Yamasani04e0d262012-02-14 11:50:53 -08004497 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
4498 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004499 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004500 return true;
4501 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004502 UserAccounts accounts = getUserAccountsForCaller();
4503 synchronized (accounts.cacheLock) {
4504 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
4505 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004506 account.name, account.type};
4507 final boolean permissionGranted =
4508 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
4509 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
4510 // TODO: Skip this check when running automated tests. Replace this
4511 // with a more general solution.
4512 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08004513 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004514 + " but ignoring since device is in test harness.");
4515 return true;
4516 }
4517 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004518 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004519 }
4520
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004521 private boolean isSystemUid(int callingUid) {
4522 String[] packages = null;
4523 long ident = Binder.clearCallingIdentity();
4524 try {
4525 packages = mPackageManager.getPackagesForUid(callingUid);
4526 } finally {
4527 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004528 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004529 if (packages != null) {
4530 for (String name : packages) {
4531 try {
4532 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
4533 if (packageInfo != null
4534 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
4535 != 0) {
4536 return true;
4537 }
4538 } catch (PackageManager.NameNotFoundException e) {
4539 Log.w(TAG, String.format("Could not find package [%s]", name), e);
4540 }
4541 }
4542 } else {
4543 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004544 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004545 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00004546 }
4547
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004548 /** Succeeds if any of the specified permissions are granted. */
4549 private void checkReadAccountsPermitted(
4550 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004551 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004552 int userId,
4553 String opPackageName) {
4554 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004555 String msg = String.format(
4556 "caller uid %s cannot access %s accounts",
4557 callingUid,
4558 accountType);
4559 Log.w(TAG, " " + msg);
4560 throw new SecurityException(msg);
4561 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004562 }
4563
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004564 private boolean canUserModifyAccounts(int userId, int callingUid) {
4565 // the managing app can always modify accounts
4566 if (isProfileOwner(callingUid)) {
4567 return true;
4568 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004569 if (getUserManager().getUserRestrictions(new UserHandle(userId))
4570 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
4571 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08004572 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004573 return true;
4574 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004575
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004576 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
4577 // the managing app can always modify accounts
4578 if (isProfileOwner(callingUid)) {
4579 return true;
4580 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004581 DevicePolicyManager dpm = (DevicePolicyManager) mContext
4582 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004583 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02004584 if (typesArray == null) {
4585 return true;
4586 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004587 for (String forbiddenType : typesArray) {
4588 if (forbiddenType.equals(accountType)) {
4589 return false;
4590 }
4591 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08004592 return true;
4593 }
4594
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004595 private boolean isProfileOwner(int uid) {
4596 final DevicePolicyManagerInternal dpmi =
4597 LocalServices.getService(DevicePolicyManagerInternal.class);
4598 return (dpmi != null)
4599 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4600 }
4601
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004602 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07004603 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
4604 throws RemoteException {
4605 final int callingUid = getCallingUid();
4606
Amith Yamasani27db4682013-03-30 17:07:47 -07004607 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07004608 throw new SecurityException();
4609 }
4610
4611 if (value) {
4612 grantAppPermission(account, authTokenType, uid);
4613 } else {
4614 revokeAppPermission(account, authTokenType, uid);
4615 }
4616 }
4617
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004618 /**
4619 * Allow callers with the given uid permission to get credentials for account/authTokenType.
4620 * <p>
4621 * Although this is public it can only be accessed via the AccountManagerService object
4622 * which is in the system. This means we don't need to protect it with permissions.
4623 * @hide
4624 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07004625 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07004626 if (account == null || authTokenType == null) {
4627 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07004628 return;
4629 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004630 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08004631 synchronized (accounts.cacheLock) {
4632 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004633 db.beginTransaction();
4634 try {
4635 long accountId = getAccountIdLocked(db, account);
4636 if (accountId >= 0) {
4637 ContentValues values = new ContentValues();
4638 values.put(GRANTS_ACCOUNTS_ID, accountId);
4639 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
4640 values.put(GRANTS_GRANTEE_UID, uid);
4641 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
4642 db.setTransactionSuccessful();
4643 }
4644 } finally {
4645 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004646 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004647 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
4648 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004649 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004650 }
4651
4652 /**
4653 * Don't allow callers with the given uid permission to get credentials for
4654 * account/authTokenType.
4655 * <p>
4656 * Although this is public it can only be accessed via the AccountManagerService object
4657 * which is in the system. This means we don't need to protect it with permissions.
4658 * @hide
4659 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07004660 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07004661 if (account == null || authTokenType == null) {
4662 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07004663 return;
4664 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004665 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08004666 synchronized (accounts.cacheLock) {
4667 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004668 db.beginTransaction();
4669 try {
4670 long accountId = getAccountIdLocked(db, account);
4671 if (accountId >= 0) {
4672 db.delete(TABLE_GRANTS,
4673 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
4674 + GRANTS_GRANTEE_UID + "=?",
4675 new String[]{String.valueOf(accountId), authTokenType,
4676 String.valueOf(uid)});
4677 db.setTransactionSuccessful();
4678 }
4679 } finally {
4680 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004681 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004682 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
4683 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004684 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004685 }
Fred Quintana56285a62010-12-02 14:20:51 -08004686
4687 static final private String stringArrayToString(String[] value) {
4688 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
4689 }
4690
Amith Yamasani04e0d262012-02-14 11:50:53 -08004691 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
4692 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004693 if (oldAccountsForType != null) {
4694 ArrayList<Account> newAccountsList = new ArrayList<Account>();
4695 for (Account curAccount : oldAccountsForType) {
4696 if (!curAccount.equals(account)) {
4697 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004698 }
4699 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004700 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004701 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004702 } else {
4703 Account[] newAccountsForType = new Account[newAccountsList.size()];
4704 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004705 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004706 }
Fred Quintana56285a62010-12-02 14:20:51 -08004707 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004708 accounts.userDataCache.remove(account);
4709 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004710 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004711 }
4712
4713 /**
4714 * This assumes that the caller has already checked that the account is not already present.
4715 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08004716 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
4717 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004718 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
4719 Account[] newAccountsForType = new Account[oldLength + 1];
4720 if (accountsForType != null) {
4721 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08004722 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004723 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004724 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08004725 }
4726
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004727 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07004728 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004729 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07004730 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004731 return unfiltered;
4732 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07004733 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004734 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004735 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004736 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004737 // otherwise return non-shared accounts only.
4738 // This might be a temporary way to specify a whitelist
4739 String whiteList = mContext.getResources().getString(
4740 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
4741 for (String packageName : packages) {
4742 if (whiteList.contains(";" + packageName + ";")) {
4743 return unfiltered;
4744 }
4745 }
4746 ArrayList<Account> allowed = new ArrayList<Account>();
4747 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
4748 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004749 String requiredAccountType = "";
4750 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07004751 // If there's an explicit callingPackage specified, check if that package
4752 // opted in to see restricted accounts.
4753 if (callingPackage != null) {
4754 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004755 if (pi != null && pi.restrictedAccountType != null) {
4756 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07004757 }
4758 } else {
4759 // Otherwise check if the callingUid has a package that has opted in
4760 for (String packageName : packages) {
4761 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
4762 if (pi != null && pi.restrictedAccountType != null) {
4763 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07004764 break;
4765 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004766 }
4767 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004768 } catch (NameNotFoundException nnfe) {
4769 }
4770 for (Account account : unfiltered) {
4771 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004772 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004773 } else {
4774 boolean found = false;
4775 for (Account shared : sharedAccounts) {
4776 if (shared.equals(account)) {
4777 found = true;
4778 break;
4779 }
4780 }
4781 if (!found) {
4782 allowed.add(account);
4783 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004784 }
4785 }
4786 Account[] filtered = new Account[allowed.size()];
4787 allowed.toArray(filtered);
4788 return filtered;
4789 } else {
4790 return unfiltered;
4791 }
4792 }
4793
Amith Yamasani27db4682013-03-30 17:07:47 -07004794 /*
4795 * packageName can be null. If not null, it should be used to filter out restricted accounts
4796 * that the package is not allowed to access.
4797 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004798 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07004799 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004800 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004801 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004802 if (accounts == null) {
4803 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08004804 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004805 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07004806 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004807 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004808 } else {
4809 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004810 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004811 totalLength += accounts.length;
4812 }
4813 if (totalLength == 0) {
4814 return EMPTY_ACCOUNT_ARRAY;
4815 }
4816 Account[] accounts = new Account[totalLength];
4817 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004818 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004819 System.arraycopy(accountsOfType, 0, accounts, totalLength,
4820 accountsOfType.length);
4821 totalLength += accountsOfType.length;
4822 }
Amith Yamasani27db4682013-03-30 17:07:47 -07004823 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004824 }
4825 }
4826
Amith Yamasani04e0d262012-02-14 11:50:53 -08004827 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4828 Account account, String key, String value) {
4829 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004830 if (userDataForAccount == null) {
4831 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004832 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004833 }
4834 if (value == null) {
4835 userDataForAccount.remove(key);
4836 } else {
4837 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004838 }
4839 }
4840
Carlos Valdivia91979be2015-05-22 14:11:35 -07004841 protected String readCachedTokenInternal(
4842 UserAccounts accounts,
4843 Account account,
4844 String tokenType,
4845 String callingPackage,
4846 byte[] pkgSigDigest) {
4847 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004848 return accounts.accountTokenCaches.get(
4849 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004850 }
4851 }
4852
Amith Yamasani04e0d262012-02-14 11:50:53 -08004853 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4854 Account account, String key, String value) {
4855 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004856 if (authTokensForAccount == null) {
4857 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004858 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004859 }
4860 if (value == null) {
4861 authTokensForAccount.remove(key);
4862 } else {
4863 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004864 }
4865 }
4866
Amith Yamasani04e0d262012-02-14 11:50:53 -08004867 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
4868 String authTokenType) {
4869 synchronized (accounts.cacheLock) {
4870 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004871 if (authTokensForAccount == null) {
4872 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004873 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004874 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004875 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004876 }
4877 return authTokensForAccount.get(authTokenType);
4878 }
4879 }
4880
Simranjit Kohli27d0e1f2016-02-25 21:15:02 +00004881 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
4882 synchronized (accounts.cacheLock) {
4883 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
4884 if (userDataForAccount == null) {
4885 // need to populate the cache for this account
4886 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
4887 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
4888 accounts.userDataCache.put(account, userDataForAccount);
4889 }
4890 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08004891 }
4892 }
4893
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004894 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
4895 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004896 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004897 Cursor cursor = db.query(TABLE_EXTRAS,
4898 COLUMNS_EXTRAS_KEY_AND_VALUE,
4899 SELECTION_USERDATA_BY_ACCOUNT,
4900 new String[]{account.name, account.type},
4901 null, null, null);
4902 try {
4903 while (cursor.moveToNext()) {
4904 final String tmpkey = cursor.getString(0);
4905 final String value = cursor.getString(1);
4906 userDataForAccount.put(tmpkey, value);
4907 }
4908 } finally {
4909 cursor.close();
4910 }
4911 return userDataForAccount;
4912 }
4913
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004914 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
4915 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004916 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004917 Cursor cursor = db.query(TABLE_AUTHTOKENS,
4918 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
4919 SELECTION_AUTHTOKENS_BY_ACCOUNT,
4920 new String[]{account.name, account.type},
4921 null, null, null);
4922 try {
4923 while (cursor.moveToNext()) {
4924 final String type = cursor.getString(0);
4925 final String authToken = cursor.getString(1);
4926 authTokensForAccount.put(type, authToken);
4927 }
4928 } finally {
4929 cursor.close();
4930 }
4931 return authTokensForAccount;
4932 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004933
4934 private Context getContextForUser(UserHandle user) {
4935 try {
4936 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
4937 } catch (NameNotFoundException e) {
4938 // Default to mContext, not finding the package system is running as is unlikely.
4939 return mContext;
4940 }
4941 }
Sandra Kwan78812282015-11-04 11:19:47 -08004942
4943 private void sendResponse(IAccountManagerResponse response, Bundle result) {
4944 try {
4945 response.onResult(result);
4946 } catch (RemoteException e) {
4947 // if the caller is dead then there is no one to care about remote
4948 // exceptions
4949 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4950 Log.v(TAG, "failure while notifying response", e);
4951 }
4952 }
4953 }
4954
4955 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
4956 String errorMessage) {
4957 try {
4958 response.onError(errorCode, errorMessage);
4959 } catch (RemoteException e) {
4960 // if the caller is dead then there is no one to care about remote
4961 // exceptions
4962 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4963 Log.v(TAG, "failure while notifying response", e);
4964 }
4965 }
4966 }
Fred Quintana60307342009-03-24 22:48:12 -07004967}