blob: b86b3fd47e072ae734e095aa1151d4e4dd765655 [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;
Doug Zongker885cfc232009-10-21 16:52:44 -070050import android.content.pm.ApplicationInfo;
51import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070052import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070053import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070054import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070055import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070056import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070057import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070058import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070059import android.database.Cursor;
60import android.database.DatabaseUtils;
Fred Quintanaa698f422009-04-08 19:14:54 -070061import android.database.sqlite.SQLiteDatabase;
62import android.database.sqlite.SQLiteOpenHelper;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070063import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070064import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070065import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080066import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070067import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070068import android.os.IBinder;
69import android.os.Looper;
70import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070071import android.os.Parcel;
Amith Yamasani27db4682013-03-30 17:07:47 -070072import android.os.Process;
Fred Quintanaa698f422009-04-08 19:14:54 -070073import android.os.RemoteException;
74import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070075import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070076import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070077import android.text.TextUtils;
78import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070079import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070080import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080081import android.util.SparseArray;
Fred Quintana60307342009-03-24 22:48:12 -070082
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070083import com.android.internal.R;
Amith Yamasani67df64b2012-12-14 12:09:36 -080084import com.android.internal.util.ArrayUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080085import com.android.internal.util.IndentingPrintWriter;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070086import com.android.server.FgThread;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000087import com.android.server.LocalServices;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070088import com.google.android.collect.Lists;
89import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070090
Oscar Montemayora8529f62009-11-18 10:14:20 -080091import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -070092import java.io.FileDescriptor;
93import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -080094import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -070095import java.security.MessageDigest;
96import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070097import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -070098import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -080099import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700100import java.util.Collection;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700101import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700102import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700103import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800104import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700105import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800106import java.util.Map;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700107import java.util.concurrent.atomic.AtomicInteger;
108import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700109
Fred Quintana60307342009-03-24 22:48:12 -0700110/**
111 * A system service that provides account, password, and authtoken management for all
112 * accounts on the device. Some of these calls are implemented with the help of the corresponding
113 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
114 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700115 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700116 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700117 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700118public class AccountManagerService
119 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800120 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Sandra Kwan78812282015-11-04 11:19:47 -0800121
Fred Quintana60307342009-03-24 22:48:12 -0700122 private static final String TAG = "AccountManagerService";
123
Fred Quintana60307342009-03-24 22:48:12 -0700124 private static final String DATABASE_NAME = "accounts.db";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700125 private static final int DATABASE_VERSION = 8;
126
127 private static final int MAX_DEBUG_DB_SIZE = 64;
Fred Quintana60307342009-03-24 22:48:12 -0700128
129 private final Context mContext;
130
Fred Quintana56285a62010-12-02 14:20:51 -0800131 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700132 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700133 private UserManager mUserManager;
Fred Quintana56285a62010-12-02 14:20:51 -0800134
Fred Quintana60307342009-03-24 22:48:12 -0700135 private final MessageHandler mMessageHandler;
136
137 // Messages that can be sent on mHandler
138 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700139 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700140
Fred Quintana56285a62010-12-02 14:20:51 -0800141 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fred Quintana60307342009-03-24 22:48:12 -0700142
143 private static final String TABLE_ACCOUNTS = "accounts";
144 private static final String ACCOUNTS_ID = "_id";
145 private static final String ACCOUNTS_NAME = "name";
146 private static final String ACCOUNTS_TYPE = "type";
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700147 private static final String ACCOUNTS_TYPE_COUNT = "count(type)";
Fred Quintana60307342009-03-24 22:48:12 -0700148 private static final String ACCOUNTS_PASSWORD = "password";
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700149 private static final String ACCOUNTS_PREVIOUS_NAME = "previous_name";
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800150 private static final String ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS =
151 "last_password_entry_time_millis_epoch";
Fred Quintana60307342009-03-24 22:48:12 -0700152
153 private static final String TABLE_AUTHTOKENS = "authtokens";
154 private static final String AUTHTOKENS_ID = "_id";
155 private static final String AUTHTOKENS_ACCOUNTS_ID = "accounts_id";
156 private static final String AUTHTOKENS_TYPE = "type";
157 private static final String AUTHTOKENS_AUTHTOKEN = "authtoken";
158
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700159 private static final String TABLE_GRANTS = "grants";
160 private static final String GRANTS_ACCOUNTS_ID = "accounts_id";
161 private static final String GRANTS_AUTH_TOKEN_TYPE = "auth_token_type";
162 private static final String GRANTS_GRANTEE_UID = "uid";
163
Fred Quintana60307342009-03-24 22:48:12 -0700164 private static final String TABLE_EXTRAS = "extras";
165 private static final String EXTRAS_ID = "_id";
166 private static final String EXTRAS_ACCOUNTS_ID = "accounts_id";
167 private static final String EXTRAS_KEY = "key";
168 private static final String EXTRAS_VALUE = "value";
169
170 private static final String TABLE_META = "meta";
171 private static final String META_KEY = "key";
172 private static final String META_VALUE = "value";
173
Amith Yamasani67df64b2012-12-14 12:09:36 -0800174 private static final String TABLE_SHARED_ACCOUNTS = "shared_accounts";
175
Jason Parks1cd7d0e2009-09-28 14:48:34 -0700176 private static final String[] ACCOUNT_TYPE_COUNT_PROJECTION =
177 new String[] { ACCOUNTS_TYPE, ACCOUNTS_TYPE_COUNT};
Fred Quintana7be59642009-08-24 18:29:25 -0700178 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800179
Carlos Valdivia91979be2015-05-22 14:11:35 -0700180 static {
181 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
182 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
183 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700184
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700185 private static final String COUNT_OF_MATCHING_GRANTS = ""
186 + "SELECT COUNT(*) FROM " + TABLE_GRANTS + ", " + TABLE_ACCOUNTS
187 + " WHERE " + GRANTS_ACCOUNTS_ID + "=" + ACCOUNTS_ID
188 + " AND " + GRANTS_GRANTEE_UID + "=?"
189 + " AND " + GRANTS_AUTH_TOKEN_TYPE + "=?"
190 + " AND " + ACCOUNTS_NAME + "=?"
191 + " AND " + ACCOUNTS_TYPE + "=?";
192
Fred Quintana56285a62010-12-02 14:20:51 -0800193 private static final String SELECTION_AUTHTOKENS_BY_ACCOUNT =
194 AUTHTOKENS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
Carlos Valdivia91979be2015-05-22 14:11:35 -0700195
Fred Quintana56285a62010-12-02 14:20:51 -0800196 private static final String[] COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN = {AUTHTOKENS_TYPE,
197 AUTHTOKENS_AUTHTOKEN};
198
199 private static final String SELECTION_USERDATA_BY_ACCOUNT =
200 EXTRAS_ACCOUNTS_ID + "=(select _id FROM accounts WHERE name=? AND type=?)";
201 private static final String[] COLUMNS_EXTRAS_KEY_AND_VALUE = {EXTRAS_KEY, EXTRAS_VALUE};
202
Fred Quintanaa698f422009-04-08 19:14:54 -0700203 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700204 private final AtomicInteger mNotificationIds = new AtomicInteger(1);
205
Amith Yamasani04e0d262012-02-14 11:50:53 -0800206 static class UserAccounts {
207 private final int userId;
208 private final DatabaseHelper openHelper;
209 private final HashMap<Pair<Pair<Account, String>, Integer>, Integer>
210 credentialsPermissionNotificationIds =
211 new HashMap<Pair<Pair<Account, String>, Integer>, Integer>();
212 private final HashMap<Account, Integer> signinRequiredNotificationIds =
213 new HashMap<Account, Integer>();
214 private final Object cacheLock = new Object();
215 /** protected by the {@link #cacheLock} */
Amith Yamasanib483a992012-05-22 13:14:25 -0700216 private final HashMap<String, Account[]> accountCache =
217 new LinkedHashMap<String, Account[]>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800218 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800219 private final HashMap<Account, HashMap<String, String>> userDataCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800220 new HashMap<Account, HashMap<String, String>>();
221 /** protected by the {@link #cacheLock} */
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800222 private final HashMap<Account, HashMap<String, String>> authTokenCache =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800223 new HashMap<Account, HashMap<String, String>>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700224
225 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700226 private final TokenCache accountTokenCaches = new TokenCache();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700227
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700228 /**
229 * protected by the {@link #cacheLock}
230 *
231 * Caches the previous names associated with an account. Previous names
232 * should be cached because we expect that when an Account is renamed,
233 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
234 * want to know if the accounts they care about have been renamed.
235 *
236 * The previous names are wrapped in an {@link AtomicReference} so that
237 * we can distinguish between those accounts with no previous names and
238 * those whose previous names haven't been cached (yet).
239 */
240 private final HashMap<Account, AtomicReference<String>> previousNameCache =
241 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800242
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700243 private int debugDbInsertionPoint = -1;
244 private SQLiteStatement statementForLogging;
245
Amith Yamasani04e0d262012-02-14 11:50:53 -0800246 UserAccounts(Context context, int userId) {
247 this.userId = userId;
248 synchronized (cacheLock) {
249 openHelper = new DatabaseHelper(context, userId);
250 }
251 }
252 }
253
254 private final SparseArray<UserAccounts> mUsers = new SparseArray<UserAccounts>();
255
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700256 private static AtomicReference<AccountManagerService> sThis =
257 new AtomicReference<AccountManagerService>();
Fred Quintana31957f12009-10-21 13:43:10 -0700258 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700259
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700260 /**
261 * This should only be called by system code. One should only call this after the service
262 * has started.
263 * @return a reference to the AccountManagerService instance
264 * @hide
265 */
266 public static AccountManagerService getSingleton() {
267 return sThis.get();
268 }
Fred Quintana60307342009-03-24 22:48:12 -0700269
Fred Quintana56285a62010-12-02 14:20:51 -0800270 public AccountManagerService(Context context) {
271 this(context, context.getPackageManager(), new AccountAuthenticatorCache(context));
Fred Quintana60307342009-03-24 22:48:12 -0700272 }
273
Fred Quintana56285a62010-12-02 14:20:51 -0800274 public AccountManagerService(Context context, PackageManager packageManager,
275 IAccountAuthenticatorCache authenticatorCache) {
Fred Quintana60307342009-03-24 22:48:12 -0700276 mContext = context;
Fred Quintana56285a62010-12-02 14:20:51 -0800277 mPackageManager = packageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700278 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fred Quintana60307342009-03-24 22:48:12 -0700279
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700280 mMessageHandler = new MessageHandler(FgThread.get().getLooper());
Fred Quintana60307342009-03-24 22:48:12 -0700281
Fred Quintana56285a62010-12-02 14:20:51 -0800282 mAuthenticatorCache = authenticatorCache;
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800283 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700284
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700285 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800286
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800287 IntentFilter intentFilter = new IntentFilter();
288 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
289 intentFilter.addDataScheme("package");
290 mContext.registerReceiver(new BroadcastReceiver() {
291 @Override
292 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700293 // Don't delete accounts when updating a authenticator's
294 // package.
295 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700296 /* Purging data requires file io, don't block the main thread. This is probably
297 * less than ideal because we are introducing a race condition where old grants
298 * could be exercised until they are purged. But that race condition existed
299 * anyway with the broadcast receiver.
300 *
301 * Ideally, we would completely clear the cache, purge data from the database,
302 * and then rebuild the cache. All under the cache lock. But that change is too
303 * large at this point.
304 */
305 Runnable r = new Runnable() {
306 @Override
307 public void run() {
308 purgeOldGrantsAll();
309 }
310 };
311 new Thread(r).start();
Carlos Valdivia23f58262014-09-05 10:52:41 -0700312 }
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800313 }
314 }, intentFilter);
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800315
Amith Yamasani13593602012-03-22 16:16:17 -0700316 IntentFilter userFilter = new IntentFilter();
317 userFilter.addAction(Intent.ACTION_USER_REMOVED);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800318 userFilter.addAction(Intent.ACTION_USER_STARTED);
319 mContext.registerReceiverAsUser(new BroadcastReceiver() {
Amith Yamasani13593602012-03-22 16:16:17 -0700320 @Override
321 public void onReceive(Context context, Intent intent) {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800322 String action = intent.getAction();
323 if (Intent.ACTION_USER_REMOVED.equals(action)) {
324 onUserRemoved(intent);
325 } else if (Intent.ACTION_USER_STARTED.equals(action)) {
326 onUserStarted(intent);
327 }
Amith Yamasani13593602012-03-22 16:16:17 -0700328 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800329 }, UserHandle.ALL, userFilter, null, null);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800330 }
331
Dianne Hackborn164371f2013-10-01 19:10:13 -0700332 @Override
333 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
334 throws RemoteException {
335 try {
336 return super.onTransact(code, data, reply, flags);
337 } catch (RuntimeException e) {
338 // The account manager only throws security exceptions, so let's
339 // log all others.
340 if (!(e instanceof SecurityException)) {
341 Slog.wtf(TAG, "Account Manager Crash", e);
342 }
343 throw e;
344 }
345 }
346
Kenny Root26ff6622012-07-30 12:58:03 -0700347 public void systemReady() {
Kenny Root26ff6622012-07-30 12:58:03 -0700348 }
349
Amith Yamasani258848d2012-08-10 17:06:33 -0700350 private UserManager getUserManager() {
351 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700352 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -0700353 }
354 return mUserManager;
355 }
356
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700357 /**
358 * Validate internal set of accounts against installed authenticators for
359 * given user. Clears cached authenticators before validating.
360 */
361 public void validateAccounts(int userId) {
362 final UserAccounts accounts = getUserAccounts(userId);
363
364 // Invalidate user-specific cache to make sure we catch any
365 // removed authenticators.
366 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
367 }
368
369 /**
370 * Validate internal set of accounts against installed authenticators for
371 * given user. Clear cached authenticators before validating when requested.
372 */
373 private void validateAccountsInternal(
374 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
375 if (invalidateAuthenticatorCache) {
376 mAuthenticatorCache.invalidateCache(accounts.userId);
377 }
378
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700379 final HashSet<AuthenticatorDescription> knownAuth = Sets.newHashSet();
380 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service :
381 mAuthenticatorCache.getAllServices(accounts.userId)) {
382 knownAuth.add(service.type);
383 }
384
Amith Yamasani04e0d262012-02-14 11:50:53 -0800385 synchronized (accounts.cacheLock) {
386 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800387 boolean accountDeleted = false;
388 Cursor cursor = db.query(TABLE_ACCOUNTS,
389 new String[]{ACCOUNTS_ID, ACCOUNTS_TYPE, ACCOUNTS_NAME},
Marvin Paul48fcd4e2014-12-01 18:26:07 -0800390 null, null, null, null, ACCOUNTS_ID);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800391 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800392 accounts.accountCache.clear();
Fred Quintana56285a62010-12-02 14:20:51 -0800393 final HashMap<String, ArrayList<String>> accountNamesByType =
Amith Yamasanib483a992012-05-22 13:14:25 -0700394 new LinkedHashMap<String, ArrayList<String>>();
Fred Quintana56285a62010-12-02 14:20:51 -0800395 while (cursor.moveToNext()) {
396 final long accountId = cursor.getLong(0);
397 final String accountType = cursor.getString(1);
398 final String accountName = cursor.getString(2);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700399
400 if (!knownAuth.contains(AuthenticatorDescription.newKey(accountType))) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700401 Slog.w(TAG, "deleting account " + accountName + " because type "
Fred Quintana56285a62010-12-02 14:20:51 -0800402 + accountType + " no longer has a registered authenticator");
403 db.delete(TABLE_ACCOUNTS, ACCOUNTS_ID + "=" + accountId, null);
404 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700405
406 logRecord(db, DebugDbHelper.ACTION_AUTHENTICATOR_REMOVE, TABLE_ACCOUNTS,
407 accountId, accounts);
408
Fred Quintana56285a62010-12-02 14:20:51 -0800409 final Account account = new Account(accountName, accountType);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800410 accounts.userDataCache.remove(account);
411 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700412 accounts.accountTokenCaches.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -0800413 } else {
414 ArrayList<String> accountNames = accountNamesByType.get(accountType);
415 if (accountNames == null) {
416 accountNames = new ArrayList<String>();
417 accountNamesByType.put(accountType, accountNames);
418 }
419 accountNames.add(accountName);
420 }
421 }
Andy McFadden2f362292012-01-20 14:43:38 -0800422 for (Map.Entry<String, ArrayList<String>> cur
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800423 : accountNamesByType.entrySet()) {
Fred Quintana56285a62010-12-02 14:20:51 -0800424 final String accountType = cur.getKey();
425 final ArrayList<String> accountNames = cur.getValue();
426 final Account[] accountsForType = new Account[accountNames.size()];
427 int i = 0;
428 for (String accountName : accountNames) {
429 accountsForType[i] = new Account(accountName, accountType);
430 ++i;
431 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800432 accounts.accountCache.put(accountType, accountsForType);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800433 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800434 } finally {
435 cursor.close();
436 if (accountDeleted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800437 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800438 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800439 }
440 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700441 }
442
Amith Yamasani04e0d262012-02-14 11:50:53 -0800443 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700444 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -0800445 }
446
447 protected UserAccounts getUserAccounts(int userId) {
448 synchronized (mUsers) {
449 UserAccounts accounts = mUsers.get(userId);
450 if (accounts == null) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700451 accounts = new UserAccounts(mContext, userId);
452 initializeDebugDbSizeAndCompileSqlStatementForLogging(
453 accounts.openHelper.getWritableDatabase(), accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800454 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700455 purgeOldGrants(accounts);
456 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800457 }
458 return accounts;
459 }
460 }
461
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700462 private void purgeOldGrantsAll() {
463 synchronized (mUsers) {
464 for (int i = 0; i < mUsers.size(); i++) {
465 purgeOldGrants(mUsers.valueAt(i));
466 }
467 }
468 }
469
470 private void purgeOldGrants(UserAccounts accounts) {
471 synchronized (accounts.cacheLock) {
472 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
473 final Cursor cursor = db.query(TABLE_GRANTS,
474 new String[]{GRANTS_GRANTEE_UID},
475 null, null, GRANTS_GRANTEE_UID, null, null);
476 try {
477 while (cursor.moveToNext()) {
478 final int uid = cursor.getInt(0);
479 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
480 if (packageExists) {
481 continue;
482 }
483 Log.d(TAG, "deleting grants for UID " + uid
484 + " because its package is no longer installed");
485 db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
486 new String[]{Integer.toString(uid)});
487 }
488 } finally {
489 cursor.close();
490 }
491 }
492 }
493
Amith Yamasani13593602012-03-22 16:16:17 -0700494 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -0700495 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -0700496 if (userId < 1) return;
497
498 UserAccounts accounts;
499 synchronized (mUsers) {
500 accounts = mUsers.get(userId);
501 mUsers.remove(userId);
502 }
503 if (accounts == null) {
504 File dbFile = new File(getDatabaseName(userId));
505 dbFile.delete();
506 return;
507 }
508
509 synchronized (accounts.cacheLock) {
510 accounts.openHelper.close();
511 File dbFile = new File(getDatabaseName(userId));
512 dbFile.delete();
513 }
514 }
515
Amith Yamasani67df64b2012-12-14 12:09:36 -0800516 private void onUserStarted(Intent intent) {
517 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
518 if (userId < 1) return;
519
520 // Check if there's a shared account that needs to be created as an account
521 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
522 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700523 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700524 int parentUserId = UserManager.isSplitSystemUser()
525 ? mUserManager.getUserInfo(userId).restrictedProfileParentId
526 : UserHandle.USER_SYSTEM;
527 if (parentUserId < 0) {
528 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
529 return;
530 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800531 for (Account sa : sharedAccounts) {
532 if (ArrayUtils.contains(accounts, sa)) continue;
533 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700534 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800535 }
536 }
537
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700538 @Override
539 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700540 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -0700541 }
542
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800543 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -0700544 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700545 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800546 if (Log.isLoggable(TAG, Log.VERBOSE)) {
547 Log.v(TAG, "getPassword: " + account
548 + ", caller's uid " + Binder.getCallingUid()
549 + ", pid " + Binder.getCallingPid());
550 }
Fred Quintana382601f2010-03-25 12:25:10 -0700551 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000552 int userId = UserHandle.getCallingUserId();
553 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700554 String msg = String.format(
555 "uid %s cannot get secrets for accounts of type: %s",
556 callingUid,
557 account.type);
558 throw new SecurityException(msg);
559 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700560 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700561 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700562 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800563 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700564 } finally {
565 restoreCallingIdentity(identityToken);
566 }
567 }
568
Amith Yamasani04e0d262012-02-14 11:50:53 -0800569 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -0700570 if (account == null) {
571 return null;
572 }
573
Amith Yamasani04e0d262012-02-14 11:50:53 -0800574 synchronized (accounts.cacheLock) {
575 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800576 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_PASSWORD},
577 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
578 new String[]{account.name, account.type}, null, null, null);
579 try {
580 if (cursor.moveToNext()) {
581 return cursor.getString(0);
582 }
583 return null;
584 } finally {
585 cursor.close();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700586 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700587 }
588 }
589
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800590 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700591 public String getPreviousName(Account account) {
592 if (Log.isLoggable(TAG, Log.VERBOSE)) {
593 Log.v(TAG, "getPreviousName: " + account
594 + ", caller's uid " + Binder.getCallingUid()
595 + ", pid " + Binder.getCallingPid());
596 }
597 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700598 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700599 long identityToken = clearCallingIdentity();
600 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700601 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700602 return readPreviousNameInternal(accounts, account);
603 } finally {
604 restoreCallingIdentity(identityToken);
605 }
606 }
607
608 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
609 if (account == null) {
610 return null;
611 }
612 synchronized (accounts.cacheLock) {
613 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
614 if (previousNameRef == null) {
615 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
616 Cursor cursor = db.query(
617 TABLE_ACCOUNTS,
618 new String[]{ ACCOUNTS_PREVIOUS_NAME },
619 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
620 new String[] { account.name, account.type },
621 null,
622 null,
623 null);
624 try {
625 if (cursor.moveToNext()) {
626 String previousName = cursor.getString(0);
627 previousNameRef = new AtomicReference<String>(previousName);
628 accounts.previousNameCache.put(account, previousNameRef);
629 return previousName;
630 } else {
631 return null;
632 }
633 } finally {
634 cursor.close();
635 }
636 } else {
637 return previousNameRef.get();
638 }
639 }
640 }
641
642 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700643 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700644 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800645 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700646 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
647 account, key, callingUid, Binder.getCallingPid());
648 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -0800649 }
Fred Quintana382601f2010-03-25 12:25:10 -0700650 if (account == null) throw new IllegalArgumentException("account is null");
651 if (key == null) throw new IllegalArgumentException("key is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000652 int userId = UserHandle.getCallingUserId();
653 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700654 String msg = String.format(
655 "uid %s cannot get user data for accounts of type: %s",
656 callingUid,
657 account.type);
658 throw new SecurityException(msg);
659 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700660 long identityToken = clearCallingIdentity();
661 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700662 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800663 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700664 } finally {
665 restoreCallingIdentity(identityToken);
666 }
667 }
668
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -0800669 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100670 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700671 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800672 if (Log.isLoggable(TAG, Log.VERBOSE)) {
673 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100674 + "for user id " + userId
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700675 + "caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800676 + ", pid " + Binder.getCallingPid());
677 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100678 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700679 if (isCrossUser(callingUid, userId)) {
680 throw new SecurityException(
681 String.format(
682 "User %s tying to get authenticator types for %s" ,
683 UserHandle.getCallingUserId(),
684 userId));
685 }
686
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700687 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700688 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000689 return getAuthenticatorTypesInternal(userId);
690
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700691 } finally {
692 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -0700693 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700694 }
695
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000696 /**
697 * Should only be called inside of a clearCallingIdentity block.
698 */
699 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
700 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
701 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
702 AuthenticatorDescription[] types =
703 new AuthenticatorDescription[authenticatorCollection.size()];
704 int i = 0;
705 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
706 : authenticatorCollection) {
707 types[i] = authenticator.type;
708 i++;
709 }
710 return types;
711 }
712
713
714
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700715 private boolean isCrossUser(int callingUid, int userId) {
716 return (userId != UserHandle.getCallingUserId()
717 && callingUid != Process.myUid()
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100718 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700719 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
720 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +0100721 }
722
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700723 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -0700724 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700725 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -0800726 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Amith Yamasani27db4682013-03-30 17:07:47 -0700727 Log.v(TAG, "addAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700728 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -0800729 + ", pid " + Binder.getCallingPid());
730 }
Fred Quintana382601f2010-03-25 12:25:10 -0700731 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000732 int userId = UserHandle.getCallingUserId();
733 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700734 String msg = String.format(
735 "uid %s cannot explicitly add accounts of type: %s",
736 callingUid,
737 account.type);
738 throw new SecurityException(msg);
739 }
Jatin Lodhia3df7d692013-03-27 10:57:23 -0700740 /*
741 * Child users are not allowed to add accounts. Only the accounts that are
742 * shared by the parent profile can be added to child profile.
743 *
744 * TODO: Only allow accounts that were shared to be added by
745 * a limited user.
746 */
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700747
Fred Quintana60307342009-03-24 22:48:12 -0700748 // fails if the account already exists
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700749 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -0700750 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700751 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000752 return addAccountInternal(accounts, account, password, extras, false, callingUid);
Fred Quintana60307342009-03-24 22:48:12 -0700753 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -0700754 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -0700755 }
756 }
757
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000758 @Override
759 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700760 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700761 int callingUid = Binder.getCallingUid();
762 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
763 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000764 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700765 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800766 final UserAccounts fromAccounts = getUserAccounts(userFrom);
767 final UserAccounts toAccounts = getUserAccounts(userTo);
768 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000769 if (response != null) {
770 Bundle result = new Bundle();
771 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
772 try {
773 response.onResult(result);
774 } catch (RemoteException e) {
775 Slog.w(TAG, "Failed to report error back to the client." + e);
776 }
777 }
778 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -0800779 }
780
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000781 Slog.d(TAG, "Copying account " + account.name
782 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800783 long identityToken = clearCallingIdentity();
784 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000785 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800786 false /* stripAuthTokenFromResult */, account.name,
787 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700788 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800789 protected String toDebugString(long now) {
790 return super.toDebugString(now) + ", getAccountCredentialsForClone"
791 + ", " + account.type;
792 }
793
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700794 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800795 public void run() throws RemoteException {
796 mAuthenticator.getAccountCredentialsForCloning(this, account);
797 }
798
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700799 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800800 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000801 if (result != null
802 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
803 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700804 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800805 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -0800806 super.onResult(result);
807 }
808 }
809 }.bind();
810 } finally {
811 restoreCallingIdentity(identityToken);
812 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800813 }
814
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800815 @Override
816 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700817 final int callingUid = Binder.getCallingUid();
818 if (Log.isLoggable(TAG, Log.VERBOSE)) {
819 String msg = String.format(
820 "accountAuthenticated( account: %s, callerUid: %s)",
821 account,
822 callingUid);
823 Log.v(TAG, msg);
824 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800825 if (account == null) {
826 throw new IllegalArgumentException("account is null");
827 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000828 int userId = UserHandle.getCallingUserId();
829 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -0700830 String msg = String.format(
831 "uid %s cannot notify authentication for accounts of type: %s",
832 callingUid,
833 account.type);
834 throw new SecurityException(msg);
835 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000836
Benjamin Franzb6c0ce42015-11-05 10:06:51 +0000837 if (!canUserModifyAccounts(userId, callingUid) ||
838 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800839 return false;
840 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000841
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700842 long identityToken = clearCallingIdentity();
843 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +0000844 UserAccounts accounts = getUserAccounts(userId);
845 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -0700846 } finally {
847 restoreCallingIdentity(identityToken);
848 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -0700849 }
850
851 private boolean updateLastAuthenticatedTime(Account account) {
852 final UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800853 synchronized (accounts.cacheLock) {
854 final ContentValues values = new ContentValues();
855 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
856 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
857 int i = db.update(
858 TABLE_ACCOUNTS,
859 values,
860 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE + "=?",
861 new String[] {
862 account.name, account.type
863 });
864 if (i > 0) {
865 return true;
866 }
867 }
868 return false;
869 }
870
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000871 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700872 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
873 final int parentUserId){
Amith Yamasani67df64b2012-12-14 12:09:36 -0800874 long id = clearCallingIdentity();
875 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000876 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800877 false /* stripAuthTokenFromResult */, account.name,
878 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700879 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800880 protected String toDebugString(long now) {
881 return super.toDebugString(now) + ", getAccountCredentialsForClone"
882 + ", " + account.type;
883 }
884
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700885 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800886 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700887 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700888 UserAccounts owner = getUserAccounts(parentUserId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700889 synchronized (owner.cacheLock) {
Svetoslavf3f02ac2015-09-08 14:36:35 -0700890 for (Account acc : getAccounts(parentUserId,
891 mContext.getOpPackageName())) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700892 if (acc.equals(account)) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000893 mAuthenticator.addAccountFromCredentials(
894 this, account, accountCredentials);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700895 break;
896 }
897 }
898 }
Amith Yamasani67df64b2012-12-14 12:09:36 -0800899 }
900
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700901 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800902 public void onResult(Bundle result) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +0000903 // TODO: Anything to do if if succedded?
904 // TODO: If it failed: Show error notification? Should we remove the shadow
905 // account to avoid retries?
906 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -0800907 }
908
Carlos Valdivia5bab9da2013-09-29 05:11:56 -0700909 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -0800910 public void onError(int errorCode, String errorMessage) {
911 super.onError(errorCode, errorMessage);
912 // TODO: Show error notification to user
913 // TODO: Should we remove the shadow account so that it doesn't keep trying?
914 }
915
916 }.bind();
917 } finally {
918 restoreCallingIdentity(id);
919 }
920 }
921
Amith Yamasani04e0d262012-02-14 11:50:53 -0800922 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700923 Bundle extras, boolean restricted, int callingUid) {
Fred Quintana743dfad2010-07-15 10:59:25 -0700924 if (account == null) {
925 return false;
926 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800927 synchronized (accounts.cacheLock) {
928 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800929 db.beginTransaction();
930 try {
931 long numMatches = DatabaseUtils.longForQuery(db,
932 "select count(*) from " + TABLE_ACCOUNTS
933 + " WHERE " + ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
934 new String[]{account.name, account.type});
935 if (numMatches > 0) {
936 Log.w(TAG, "insertAccountIntoDatabase: " + account
937 + ", skipping since the account already exists");
938 return false;
939 }
940 ContentValues values = new ContentValues();
941 values.put(ACCOUNTS_NAME, account.name);
942 values.put(ACCOUNTS_TYPE, account.type);
943 values.put(ACCOUNTS_PASSWORD, password);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -0800944 values.put(ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS, System.currentTimeMillis());
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800945 long accountId = db.insert(TABLE_ACCOUNTS, ACCOUNTS_NAME, values);
946 if (accountId < 0) {
947 Log.w(TAG, "insertAccountIntoDatabase: " + account
948 + ", skipping the DB insert failed");
949 return false;
950 }
951 if (extras != null) {
952 for (String key : extras.keySet()) {
953 final String value = extras.getString(key);
954 if (insertExtraLocked(db, accountId, key, value) < 0) {
955 Log.w(TAG, "insertAccountIntoDatabase: " + account
956 + ", skipping since insertExtra failed for key " + key);
957 return false;
958 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700959 }
960 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800961 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700962
963 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_ACCOUNTS, accountId,
964 accounts, callingUid);
965
Amith Yamasani04e0d262012-02-14 11:50:53 -0800966 insertAccountIntoCacheLocked(accounts, account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -0800967 } finally {
968 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700969 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800970 sendAccountsChangedBroadcast(accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700971 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700972 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
973 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -0700974 }
975 return true;
976 }
977
978 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700979 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -0700980 * running, then clone the account too.
981 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700982 *
Amith Yamasani5be347b2013-03-31 17:44:31 -0700983 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700984 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -0700985 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -0700986 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700987 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700988 addSharedAccountAsUser(account, user.id);
989 try {
Jeff Sharkeye17ac152015-11-06 22:40:29 -0800990 if (ActivityManagerNative.getDefault().isUserRunning(user.id, 0)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -0700991 mMessageHandler.sendMessage(mMessageHandler.obtainMessage(
Fyodor Kupolov06a484a2015-08-21 16:33:20 -0700992 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -0700993 }
994 } catch (RemoteException re) {
995 // Shouldn't happen
996 }
997 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -0700998 }
999 }
1000
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001001 private long insertExtraLocked(SQLiteDatabase db, long accountId, String key, String value) {
Fred Quintana60307342009-03-24 22:48:12 -07001002 ContentValues values = new ContentValues();
1003 values.put(EXTRAS_KEY, key);
1004 values.put(EXTRAS_ACCOUNTS_ID, accountId);
1005 values.put(EXTRAS_VALUE, value);
1006 return db.insert(TABLE_EXTRAS, EXTRAS_KEY, values);
1007 }
1008
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001009 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001010 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001011 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001012 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001013 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1014 Log.v(TAG, "hasFeatures: " + account
1015 + ", response " + response
1016 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001017 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001018 + ", pid " + Binder.getCallingPid());
1019 }
Fred Quintana382601f2010-03-25 12:25:10 -07001020 if (response == null) throw new IllegalArgumentException("response is null");
1021 if (account == null) throw new IllegalArgumentException("account is null");
1022 if (features == null) throw new IllegalArgumentException("features is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001023 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001024 checkReadAccountsPermitted(callingUid, account.type, userId,
1025 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001026
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001027 long identityToken = clearCallingIdentity();
1028 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001029 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001030 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001031 } finally {
1032 restoreCallingIdentity(identityToken);
1033 }
1034 }
1035
1036 private class TestFeaturesSession extends Session {
1037 private final String[] mFeatures;
1038 private final Account mAccount;
1039
Amith Yamasani04e0d262012-02-14 11:50:53 -08001040 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001041 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001042 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001043 true /* stripAuthTokenFromResult */, account.name,
1044 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001045 mFeatures = features;
1046 mAccount = account;
1047 }
1048
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001049 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001050 public void run() throws RemoteException {
1051 try {
1052 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1053 } catch (RemoteException e) {
1054 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1055 }
1056 }
1057
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001058 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001059 public void onResult(Bundle result) {
1060 IAccountManagerResponse response = getResponseAndClose();
1061 if (response != null) {
1062 try {
1063 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001064 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001065 return;
1066 }
Fred Quintana56285a62010-12-02 14:20:51 -08001067 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1068 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1069 + response);
1070 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001071 final Bundle newResult = new Bundle();
1072 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1073 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1074 response.onResult(newResult);
1075 } catch (RemoteException e) {
1076 // if the caller is dead then there is no one to care about remote exceptions
1077 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1078 Log.v(TAG, "failure while notifying response", e);
1079 }
1080 }
1081 }
1082 }
1083
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001084 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001085 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001086 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001087 + ", " + mAccount
1088 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1089 }
1090 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001091
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001092 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001093 public void renameAccount(
1094 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001095 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001096 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1097 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001098 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001099 + ", pid " + Binder.getCallingPid());
1100 }
1101 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001102 int userId = UserHandle.getCallingUserId();
1103 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001104 String msg = String.format(
1105 "uid %s cannot rename accounts of type: %s",
1106 callingUid,
1107 accountToRename.type);
1108 throw new SecurityException(msg);
1109 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001110 long identityToken = clearCallingIdentity();
1111 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001112 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001113 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001114 Bundle result = new Bundle();
1115 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1116 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
1117 try {
1118 response.onResult(result);
1119 } catch (RemoteException e) {
1120 Log.w(TAG, e.getMessage());
1121 }
1122 } finally {
1123 restoreCallingIdentity(identityToken);
1124 }
1125 }
1126
1127 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001128 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001129 Account resultAccount = null;
1130 /*
1131 * Cancel existing notifications. Let authenticators
1132 * re-post notifications as required. But we don't know if
1133 * the authenticators have bound their notifications to
1134 * now stale account name data.
1135 *
1136 * With a rename api, we might not need to do this anymore but it
1137 * shouldn't hurt.
1138 */
1139 cancelNotification(
1140 getSigninRequiredNotificationId(accounts, accountToRename),
1141 new UserHandle(accounts.userId));
1142 synchronized(accounts.credentialsPermissionNotificationIds) {
1143 for (Pair<Pair<Account, String>, Integer> pair:
1144 accounts.credentialsPermissionNotificationIds.keySet()) {
1145 if (accountToRename.equals(pair.first.first)) {
1146 int id = accounts.credentialsPermissionNotificationIds.get(pair);
1147 cancelNotification(id, new UserHandle(accounts.userId));
1148 }
1149 }
1150 }
1151 synchronized (accounts.cacheLock) {
1152 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
1153 db.beginTransaction();
1154 boolean isSuccessful = false;
1155 Account renamedAccount = new Account(newName, accountToRename.type);
1156 try {
1157 final ContentValues values = new ContentValues();
1158 values.put(ACCOUNTS_NAME, newName);
1159 values.put(ACCOUNTS_PREVIOUS_NAME, accountToRename.name);
1160 final long accountId = getAccountIdLocked(db, accountToRename);
1161 if (accountId >= 0) {
1162 final String[] argsAccountId = { String.valueOf(accountId) };
1163 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1164 db.setTransactionSuccessful();
1165 isSuccessful = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001166 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_ACCOUNTS, accountId,
1167 accounts);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001168 }
1169 } finally {
1170 db.endTransaction();
1171 if (isSuccessful) {
1172 /*
1173 * Database transaction was successful. Clean up cached
1174 * data associated with the account in the user profile.
1175 */
1176 insertAccountIntoCacheLocked(accounts, renamedAccount);
1177 /*
1178 * Extract the data and token caches before removing the
1179 * old account to preserve the user data associated with
1180 * the account.
1181 */
1182 HashMap<String, String> tmpData = accounts.userDataCache.get(accountToRename);
1183 HashMap<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
1184 removeAccountFromCacheLocked(accounts, accountToRename);
1185 /*
1186 * Update the cached data associated with the renamed
1187 * account.
1188 */
1189 accounts.userDataCache.put(renamedAccount, tmpData);
1190 accounts.authTokenCache.put(renamedAccount, tmpTokens);
1191 accounts.previousNameCache.put(
1192 renamedAccount,
1193 new AtomicReference<String>(accountToRename.name));
1194 resultAccount = renamedAccount;
1195
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001196 int parentUserId = accounts.userId;
1197 if (canHaveProfile(parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001198 /*
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001199 * Owner or system user account was renamed, rename the account for
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001200 * those users with which the account was shared.
1201 */
1202 List<UserInfo> users = mUserManager.getUsers(true);
1203 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001204 if (user.isRestricted()
1205 && (user.restrictedProfileParentId == parentUserId)) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001206 renameSharedAccountAsUser(accountToRename, newName, user.id);
1207 }
1208 }
1209 }
1210 sendAccountsChangedBroadcast(accounts.userId);
1211 }
1212 }
1213 }
1214 return resultAccount;
1215 }
1216
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001217 private boolean canHaveProfile(final int parentUserId) {
1218 final UserInfo userInfo = mUserManager.getUserInfo(parentUserId);
1219 return userInfo != null && userInfo.canHaveProfile();
1220 }
1221
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001222 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001223 public void removeAccount(IAccountManagerResponse response, Account account,
1224 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001225 removeAccountAsUser(
1226 response,
1227 account,
1228 expectActivityLaunch,
1229 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001230 }
1231
1232 @Override
1233 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001234 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001235 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001236 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1237 Log.v(TAG, "removeAccount: " + account
1238 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001239 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001240 + ", pid " + Binder.getCallingPid()
1241 + ", for user id " + userId);
1242 }
1243 if (response == null) throw new IllegalArgumentException("response is null");
1244 if (account == null) throw new IllegalArgumentException("account is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001245 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001246 if (isCrossUser(callingUid, userId)) {
1247 throw new SecurityException(
1248 String.format(
1249 "User %s tying remove account for %s" ,
1250 UserHandle.getCallingUserId(),
1251 userId));
1252 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001253 /*
1254 * Only the system or authenticator should be allowed to remove accounts for that
1255 * authenticator. This will let users remove accounts (via Settings in the system) but not
1256 * arbitrary applications (like competing authenticators).
1257 */
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001258 UserHandle user = new UserHandle(userId);
1259 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
1260 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001261 String msg = String.format(
1262 "uid %s cannot remove accounts of type: %s",
1263 callingUid,
1264 account.type);
1265 throw new SecurityException(msg);
1266 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001267 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001268 try {
1269 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
1270 "User cannot modify accounts");
1271 } catch (RemoteException re) {
1272 }
1273 return;
1274 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001275 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001276 try {
1277 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
1278 "User cannot modify accounts of this type (policy).");
1279 } catch (RemoteException re) {
1280 }
1281 return;
1282 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001283 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001284 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01001285 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001286 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001287 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08001288 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001289 if (account.equals(pair.first.first)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001290 int id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001291 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08001292 }
1293 }
1294 }
1295
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001296 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
1297
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001298 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001299 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
1300 } finally {
1301 restoreCallingIdentity(identityToken);
1302 }
1303 }
1304
1305 @Override
1306 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001307 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001308 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1309 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001310 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001311 + ", pid " + Binder.getCallingPid());
1312 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001313 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001314 if (account == null) {
1315 /*
1316 * Null accounts should result in returning false, as per
1317 * AccountManage.addAccountExplicitly(...) java doc.
1318 */
1319 Log.e(TAG, "account is null");
1320 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001321 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001322 String msg = String.format(
1323 "uid %s cannot explicitly add accounts of type: %s",
1324 callingUid,
1325 account.type);
1326 throw new SecurityException(msg);
1327 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001328 UserAccounts accounts = getUserAccountsForCaller();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001329 logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_REMOVE, TABLE_ACCOUNTS);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001330 long identityToken = clearCallingIdentity();
1331 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001332 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001333 } finally {
1334 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001335 }
Fred Quintana60307342009-03-24 22:48:12 -07001336 }
1337
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001338 private class RemoveAccountSession extends Session {
1339 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001340 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001341 Account account, boolean expectActivityLaunch) {
1342 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001343 true /* stripAuthTokenFromResult */, account.name,
1344 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001345 mAccount = account;
1346 }
1347
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001348 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001349 protected String toDebugString(long now) {
1350 return super.toDebugString(now) + ", removeAccount"
1351 + ", account " + mAccount;
1352 }
1353
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001354 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001355 public void run() throws RemoteException {
1356 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
1357 }
1358
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001359 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001360 public void onResult(Bundle result) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001361 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
1362 && !result.containsKey(AccountManager.KEY_INTENT)) {
1363 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001364 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001365 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001366 }
1367 IAccountManagerResponse response = getResponseAndClose();
1368 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08001369 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1370 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1371 + response);
1372 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001373 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001374 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001375 try {
1376 response.onResult(result2);
1377 } catch (RemoteException e) {
1378 // ignore
1379 }
1380 }
1381 }
1382 super.onResult(result);
1383 }
1384 }
1385
Amith Yamasani04e0d262012-02-14 11:50:53 -08001386 /* For testing */
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001387 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001388 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001389 }
1390
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001391 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001392 int deleted;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001393 synchronized (accounts.cacheLock) {
1394 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001395 final long accountId = getAccountIdLocked(db, account);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001396 deleted = db.delete(TABLE_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE
1397 + "=?",
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001398 new String[]{account.name, account.type});
Amith Yamasani04e0d262012-02-14 11:50:53 -08001399 removeAccountFromCacheLocked(accounts, account);
1400 sendAccountsChangedBroadcast(accounts.userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001401
1402 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_ACCOUNTS, accountId, accounts);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001403 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001404 long id = Binder.clearCallingIdentity();
1405 try {
1406 int parentUserId = accounts.userId;
1407 if (canHaveProfile(parentUserId)) {
1408 // Remove from any restricted profiles that are sharing this account.
Amith Yamasani67df64b2012-12-14 12:09:36 -08001409 List<UserInfo> users = mUserManager.getUsers(true);
1410 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001411 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001412 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001413 }
1414 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001415 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001416 } finally {
1417 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001418 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08001419 return (deleted > 0);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001420 }
1421
Maggie Benthalla12fccf2013-03-14 18:02:12 -04001422 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001423 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001424 int callerUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001425 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1426 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07001427 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08001428 + ", pid " + Binder.getCallingPid());
1429 }
Fred Quintana382601f2010-03-25 12:25:10 -07001430 if (accountType == null) throw new IllegalArgumentException("accountType is null");
1431 if (authToken == null) throw new IllegalArgumentException("authToken is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001432 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001433 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001434 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001435 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001436 synchronized (accounts.cacheLock) {
1437 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001438 db.beginTransaction();
1439 try {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001440 invalidateAuthTokenLocked(accounts, db, accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001441 invalidateCustomTokenLocked(accounts, accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001442 db.setTransactionSuccessful();
1443 } finally {
1444 db.endTransaction();
1445 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001446 }
Fred Quintana60307342009-03-24 22:48:12 -07001447 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001448 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001449 }
1450 }
1451
Carlos Valdivia91979be2015-05-22 14:11:35 -07001452 private void invalidateCustomTokenLocked(
1453 UserAccounts accounts,
1454 String accountType,
1455 String authToken) {
1456 if (authToken == null || accountType == null) {
1457 return;
1458 }
1459 // Also wipe out cached token in memory.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001460 accounts.accountTokenCaches.remove(accountType, authToken);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001461 }
1462
Amith Yamasani04e0d262012-02-14 11:50:53 -08001463 private void invalidateAuthTokenLocked(UserAccounts accounts, SQLiteDatabase db,
1464 String accountType, String authToken) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001465 if (authToken == null || accountType == null) {
1466 return;
1467 }
Fred Quintana33269202009-04-20 16:05:10 -07001468 Cursor cursor = db.rawQuery(
1469 "SELECT " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_ID
1470 + ", " + TABLE_ACCOUNTS + "." + ACCOUNTS_NAME
1471 + ", " + TABLE_AUTHTOKENS + "." + AUTHTOKENS_TYPE
1472 + " FROM " + TABLE_ACCOUNTS
1473 + " JOIN " + TABLE_AUTHTOKENS
1474 + " ON " + TABLE_ACCOUNTS + "." + ACCOUNTS_ID
1475 + " = " + AUTHTOKENS_ACCOUNTS_ID
1476 + " WHERE " + AUTHTOKENS_AUTHTOKEN + " = ? AND "
1477 + TABLE_ACCOUNTS + "." + ACCOUNTS_TYPE + " = ?",
1478 new String[]{authToken, accountType});
1479 try {
1480 while (cursor.moveToNext()) {
1481 long authTokenId = cursor.getLong(0);
1482 String accountName = cursor.getString(1);
1483 String authTokenType = cursor.getString(2);
1484 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ID + "=" + authTokenId, null);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001485 writeAuthTokenIntoCacheLocked(
1486 accounts,
1487 db,
1488 new Account(accountName, accountType),
1489 authTokenType,
1490 null);
Fred Quintana60307342009-03-24 22:48:12 -07001491 }
Fred Quintana33269202009-04-20 16:05:10 -07001492 } finally {
1493 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07001494 }
1495 }
1496
Carlos Valdivia91979be2015-05-22 14:11:35 -07001497 private void saveCachedToken(
1498 UserAccounts accounts,
1499 Account account,
1500 String callerPkg,
1501 byte[] callerSigDigest,
1502 String tokenType,
1503 String token,
1504 long expiryMillis) {
1505
1506 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
1507 return;
1508 }
1509 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1510 new UserHandle(accounts.userId));
1511 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001512 accounts.accountTokenCaches.put(
1513 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001514 }
1515 }
1516
Amith Yamasani04e0d262012-02-14 11:50:53 -08001517 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
1518 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07001519 if (account == null || type == null) {
1520 return false;
1521 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001522 cancelNotification(getSigninRequiredNotificationId(accounts, account),
1523 new UserHandle(accounts.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001524 synchronized (accounts.cacheLock) {
1525 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001526 db.beginTransaction();
1527 try {
1528 long accountId = getAccountIdLocked(db, account);
1529 if (accountId < 0) {
1530 return false;
1531 }
1532 db.delete(TABLE_AUTHTOKENS,
1533 AUTHTOKENS_ACCOUNTS_ID + "=" + accountId + " AND " + AUTHTOKENS_TYPE + "=?",
1534 new String[]{type});
1535 ContentValues values = new ContentValues();
1536 values.put(AUTHTOKENS_ACCOUNTS_ID, accountId);
1537 values.put(AUTHTOKENS_TYPE, type);
1538 values.put(AUTHTOKENS_AUTHTOKEN, authToken);
1539 if (db.insert(TABLE_AUTHTOKENS, AUTHTOKENS_AUTHTOKEN, values) >= 0) {
1540 db.setTransactionSuccessful();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001541 writeAuthTokenIntoCacheLocked(accounts, db, account, type, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001542 return true;
1543 }
Fred Quintana33269202009-04-20 16:05:10 -07001544 return false;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001545 } finally {
1546 db.endTransaction();
Fred Quintana33269202009-04-20 16:05:10 -07001547 }
Fred Quintana60307342009-03-24 22:48:12 -07001548 }
1549 }
1550
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001551 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001552 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001553 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001554 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1555 Log.v(TAG, "peekAuthToken: " + account
1556 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001557 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001558 + ", pid " + Binder.getCallingPid());
1559 }
Fred Quintana382601f2010-03-25 12:25:10 -07001560 if (account == null) throw new IllegalArgumentException("account is null");
1561 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001562 int userId = UserHandle.getCallingUserId();
1563 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001564 String msg = String.format(
1565 "uid %s cannot peek the authtokens associated with accounts of type: %s",
1566 callingUid,
1567 account.type);
1568 throw new SecurityException(msg);
1569 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001570 long identityToken = clearCallingIdentity();
1571 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001572 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001573 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001574 } finally {
1575 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001576 }
Fred Quintana60307342009-03-24 22:48:12 -07001577 }
1578
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001579 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001580 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001581 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001582 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1583 Log.v(TAG, "setAuthToken: " + account
1584 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001585 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001586 + ", pid " + Binder.getCallingPid());
1587 }
Fred Quintana382601f2010-03-25 12:25:10 -07001588 if (account == null) throw new IllegalArgumentException("account is null");
1589 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001590 int userId = UserHandle.getCallingUserId();
1591 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001592 String msg = String.format(
1593 "uid %s cannot set auth tokens associated with accounts of type: %s",
1594 callingUid,
1595 account.type);
1596 throw new SecurityException(msg);
1597 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001598 long identityToken = clearCallingIdentity();
1599 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001600 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001601 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001602 } finally {
1603 restoreCallingIdentity(identityToken);
1604 }
Fred Quintana60307342009-03-24 22:48:12 -07001605 }
1606
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001607 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001608 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001609 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001610 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1611 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001612 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001613 + ", pid " + Binder.getCallingPid());
1614 }
Fred Quintana382601f2010-03-25 12:25:10 -07001615 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001616 int userId = UserHandle.getCallingUserId();
1617 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001618 String msg = String.format(
1619 "uid %s cannot set secrets for accounts of type: %s",
1620 callingUid,
1621 account.type);
1622 throw new SecurityException(msg);
1623 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001624 long identityToken = clearCallingIdentity();
1625 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001626 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001627 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001628 } finally {
1629 restoreCallingIdentity(identityToken);
1630 }
Fred Quintana60307342009-03-24 22:48:12 -07001631 }
1632
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001633 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
1634 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07001635 if (account == null) {
1636 return;
1637 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001638 synchronized (accounts.cacheLock) {
1639 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001640 db.beginTransaction();
1641 try {
1642 final ContentValues values = new ContentValues();
1643 values.put(ACCOUNTS_PASSWORD, password);
1644 final long accountId = getAccountIdLocked(db, account);
1645 if (accountId >= 0) {
1646 final String[] argsAccountId = {String.valueOf(accountId)};
1647 db.update(TABLE_ACCOUNTS, values, ACCOUNTS_ID + "=?", argsAccountId);
1648 db.delete(TABLE_AUTHTOKENS, AUTHTOKENS_ACCOUNTS_ID + "=?", argsAccountId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001649 accounts.authTokenCache.remove(account);
Carlos Valdivia91979be2015-05-22 14:11:35 -07001650 accounts.accountTokenCaches.remove(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001651 db.setTransactionSuccessful();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001652
1653 String action = (password == null || password.length() == 0) ?
1654 DebugDbHelper.ACTION_CLEAR_PASSWORD
1655 : DebugDbHelper.ACTION_SET_PASSWORD;
1656 logRecord(db, action, TABLE_ACCOUNTS, accountId, accounts, callingUid);
Costin Manolachef5ffe892011-01-19 09:35:32 -08001657 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001658 } finally {
1659 db.endTransaction();
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001660 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001661 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08001662 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001663 }
1664
Amith Yamasani04e0d262012-02-14 11:50:53 -08001665 private void sendAccountsChangedBroadcast(int userId) {
Fred Quintana56285a62010-12-02 14:20:51 -08001666 Log.i(TAG, "the accounts changed, sending broadcast of "
1667 + ACCOUNTS_CHANGED_INTENT.getAction());
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001668 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Fred Quintana33269202009-04-20 16:05:10 -07001669 }
1670
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001671 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001672 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001673 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001674 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1675 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001676 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001677 + ", pid " + Binder.getCallingPid());
1678 }
Fred Quintana382601f2010-03-25 12:25:10 -07001679 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001680 int userId = UserHandle.getCallingUserId();
1681 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001682 String msg = String.format(
1683 "uid %s cannot clear passwords for accounts of type: %s",
1684 callingUid,
1685 account.type);
1686 throw new SecurityException(msg);
1687 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001688 long identityToken = clearCallingIdentity();
1689 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001690 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001691 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001692 } finally {
1693 restoreCallingIdentity(identityToken);
1694 }
Fred Quintana60307342009-03-24 22:48:12 -07001695 }
1696
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001697 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001698 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001699 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001700 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1701 Log.v(TAG, "setUserData: " + account
1702 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001703 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001704 + ", pid " + Binder.getCallingPid());
1705 }
Fred Quintana382601f2010-03-25 12:25:10 -07001706 if (key == null) throw new IllegalArgumentException("key is null");
1707 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001708 int userId = UserHandle.getCallingUserId();
1709 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001710 String msg = String.format(
1711 "uid %s cannot set user data for accounts of type: %s",
1712 callingUid,
1713 account.type);
1714 throw new SecurityException(msg);
1715 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001716 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001717 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001718 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001719 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07001720 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001721 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07001722 }
1723 }
1724
Amith Yamasani04e0d262012-02-14 11:50:53 -08001725 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
1726 String value) {
Fred Quintana31957f12009-10-21 13:43:10 -07001727 if (account == null || key == null) {
1728 return;
1729 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001730 synchronized (accounts.cacheLock) {
1731 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001732 db.beginTransaction();
1733 try {
1734 long accountId = getAccountIdLocked(db, account);
1735 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001736 return;
1737 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001738 long extrasId = getExtrasIdLocked(db, accountId, key);
1739 if (extrasId < 0 ) {
1740 extrasId = insertExtraLocked(db, accountId, key, value);
1741 if (extrasId < 0) {
1742 return;
1743 }
1744 } else {
1745 ContentValues values = new ContentValues();
1746 values.put(EXTRAS_VALUE, value);
1747 if (1 != db.update(TABLE_EXTRAS, values, EXTRAS_ID + "=" + extrasId, null)) {
1748 return;
1749 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001750
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001751 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001752 writeUserDataIntoCacheLocked(accounts, db, account, key, value);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001753 db.setTransactionSuccessful();
1754 } finally {
1755 db.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001756 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001757 }
1758 }
1759
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001760 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08001761 if (result == null) {
1762 Log.e(TAG, "the result is unexpectedly null", new Exception());
1763 }
1764 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1765 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1766 + response);
1767 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001768 try {
1769 response.onResult(result);
1770 } catch (RemoteException e) {
1771 // if the caller is dead then there is no one to care about remote
1772 // exceptions
1773 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1774 Log.v(TAG, "failure while notifying response", e);
1775 }
1776 }
1777 }
1778
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001779 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07001780 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
1781 final String authTokenType)
1782 throws RemoteException {
1783 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08001784 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
1785
Fred Quintanad9640ec2012-05-23 12:37:00 -07001786 final int callingUid = getCallingUid();
1787 clearCallingIdentity();
Amith Yamasani27db4682013-03-30 17:07:47 -07001788 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07001789 throw new SecurityException("can only call from system");
1790 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001791 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08001792 long identityToken = clearCallingIdentity();
1793 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001794 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001795 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
1796 false /* stripAuthTokenFromResult */, null /* accountName */,
1797 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001798 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001799 protected String toDebugString(long now) {
1800 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07001801 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08001802 + ", authTokenType " + authTokenType;
1803 }
1804
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001805 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001806 public void run() throws RemoteException {
1807 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1808 }
1809
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001810 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08001811 public void onResult(Bundle result) {
1812 if (result != null) {
1813 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
1814 Bundle bundle = new Bundle();
1815 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
1816 super.onResult(bundle);
1817 return;
1818 } else {
1819 super.onResult(result);
1820 }
1821 }
1822 }.bind();
1823 } finally {
1824 restoreCallingIdentity(identityToken);
1825 }
1826 }
1827
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001828 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07001829 public void getAuthToken(
1830 IAccountManagerResponse response,
1831 final Account account,
1832 final String authTokenType,
1833 final boolean notifyOnAuthFailure,
1834 final boolean expectActivityLaunch,
1835 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08001836 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1837 Log.v(TAG, "getAuthToken: " + account
1838 + ", response " + response
1839 + ", authTokenType " + authTokenType
1840 + ", notifyOnAuthFailure " + notifyOnAuthFailure
1841 + ", expectActivityLaunch " + expectActivityLaunch
1842 + ", caller's uid " + Binder.getCallingUid()
1843 + ", pid " + Binder.getCallingPid());
1844 }
Fred Quintana382601f2010-03-25 12:25:10 -07001845 if (response == null) throw new IllegalArgumentException("response is null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001846 try {
1847 if (account == null) {
1848 Slog.w(TAG, "getAuthToken called with null account");
1849 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
1850 return;
1851 }
1852 if (authTokenType == null) {
1853 Slog.w(TAG, "getAuthToken called with null authTokenType");
1854 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
1855 return;
1856 }
1857 } catch (RemoteException e) {
1858 Slog.w(TAG, "Failed to report error back to the client." + e);
1859 return;
1860 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001861 int userId = UserHandle.getCallingUserId();
1862 long ident = Binder.clearCallingIdentity();
1863 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001864 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001865 try {
1866 accounts = getUserAccounts(userId);
1867 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
1868 AuthenticatorDescription.newKey(account.type), accounts.userId);
1869 } finally {
1870 Binder.restoreCallingIdentity(ident);
1871 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001872
Costin Manolachea40c6302010-12-13 14:50:45 -08001873 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07001874 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08001875
1876 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001877 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001878 final boolean permissionGranted =
1879 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08001880
Carlos Valdivia91979be2015-05-22 14:11:35 -07001881 // Get the calling package. We will use it for the purpose of caching.
1882 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07001883 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001884 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07001885 try {
1886 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
1887 } finally {
1888 Binder.restoreCallingIdentity(ident);
1889 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001890 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
1891 String msg = String.format(
1892 "Uid %s is attempting to illegally masquerade as package %s!",
1893 callerUid,
1894 callerPkg);
1895 throw new SecurityException(msg);
1896 }
1897
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001898 // let authenticator know the identity of the caller
1899 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
1900 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07001901
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07001902 if (notifyOnAuthFailure) {
1903 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08001904 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001905
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001906 long identityToken = clearCallingIdentity();
1907 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07001908 // Distill the caller's package signatures into a single digest.
1909 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
1910
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001911 // if the caller has permission, do the peek. otherwise go the more expensive
1912 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08001913 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001914 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001915 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001916 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001917 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
1918 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1919 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001920 onResult(response, result);
1921 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07001922 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001923 }
1924
Carlos Valdivia91979be2015-05-22 14:11:35 -07001925 if (customTokens) {
1926 /*
1927 * Look up tokens in the new cache only if the loginOptions don't have parameters
1928 * outside of those expected to be injected by the AccountManager, e.g.
1929 * ANDORID_PACKAGE_NAME.
1930 */
1931 String token = readCachedTokenInternal(
1932 accounts,
1933 account,
1934 authTokenType,
1935 callerPkg,
1936 callerPkgSigDigest);
1937 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001938 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1939 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
1940 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001941 Bundle result = new Bundle();
1942 result.putString(AccountManager.KEY_AUTHTOKEN, token);
1943 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
1944 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
1945 onResult(response, result);
1946 return;
1947 }
1948 }
1949
Amith Yamasani04e0d262012-02-14 11:50:53 -08001950 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001951 false /* stripAuthTokenFromResult */, account.name,
1952 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001953 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001954 protected String toDebugString(long now) {
1955 if (loginOptions != null) loginOptions.keySet();
1956 return super.toDebugString(now) + ", getAuthToken"
1957 + ", " + account
1958 + ", authTokenType " + authTokenType
1959 + ", loginOptions " + loginOptions
1960 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
1961 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001962
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001963 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001964 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001965 // If the caller doesn't have permission then create and return the
1966 // "grant permission" intent instead of the "getAuthToken" intent.
1967 if (!permissionGranted) {
1968 mAuthenticator.getAuthTokenLabel(this, authTokenType);
1969 } else {
1970 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
1971 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001972 }
1973
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001974 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001975 public void onResult(Bundle result) {
1976 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001977 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001978 Intent intent = newGrantCredentialsPermissionIntent(
1979 account,
1980 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001981 new AccountAuthenticatorResponse(this),
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001982 authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001983 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001984 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07001985 onResult(bundle);
1986 return;
1987 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001988 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001989 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001990 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
1991 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001992 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07001993 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001994 "the type and name should not be empty");
1995 return;
1996 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07001997 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08001998 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07001999 saveAuthTokenToDatabase(
2000 mAccounts,
2001 resultAccount,
2002 authTokenType,
2003 authToken);
2004 }
2005 long expiryMillis = result.getLong(
2006 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2007 if (customTokens
2008 && expiryMillis > System.currentTimeMillis()) {
2009 saveCachedToken(
2010 mAccounts,
2011 account,
2012 callerPkg,
2013 callerPkgSigDigest,
2014 authTokenType,
2015 authToken,
2016 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002017 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002018 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002019
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002020 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002021 if (intent != null && notifyOnAuthFailure && !customTokens) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002022 doNotification(mAccounts,
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002023 account, result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Dianne Hackborn41203752012-08-31 14:05:51 -07002024 intent, accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002025 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002026 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002027 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002028 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002029 }.bind();
2030 } finally {
2031 restoreCallingIdentity(identityToken);
2032 }
Fred Quintana60307342009-03-24 22:48:12 -07002033 }
2034
Carlos Valdivia91979be2015-05-22 14:11:35 -07002035 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2036 MessageDigest digester;
2037 try {
2038 digester = MessageDigest.getInstance("SHA-256");
2039 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2040 callerPkg, PackageManager.GET_SIGNATURES);
2041 for (Signature sig : pkgInfo.signatures) {
2042 digester.update(sig.toByteArray());
2043 }
2044 } catch (NoSuchAlgorithmException x) {
2045 Log.wtf(TAG, "SHA-256 should be available", x);
2046 digester = null;
2047 } catch (NameNotFoundException e) {
2048 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
2049 digester = null;
2050 }
2051 return (digester == null) ? null : digester.digest();
2052 }
2053
Dianne Hackborn41203752012-08-31 14:05:51 -07002054 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
2055 int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002056 int uid = intent.getIntExtra(
2057 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
2058 String authTokenType = intent.getStringExtra(
2059 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07002060 final String titleAndSubtitle =
2061 mContext.getString(R.string.permission_request_notification_with_subtitle,
2062 account.name);
2063 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07002064 String title = titleAndSubtitle;
2065 String subtitle = "";
2066 if (index > 0) {
2067 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002068 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07002069 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002070 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01002071 Context contextForUser = getContextForUser(user);
Chris Wren1ce4b6d2015-06-11 10:19:43 -04002072 Notification n = new Notification.Builder(contextForUser)
2073 .setSmallIcon(android.R.drawable.stat_sys_warning)
2074 .setWhen(0)
2075 .setColor(contextForUser.getColor(
2076 com.android.internal.R.color.system_notification_accent_color))
2077 .setContentTitle(title)
2078 .setContentText(subtitle)
2079 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
2080 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
2081 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002082 installNotification(getCredentialPermissionNotificationId(
2083 account, authTokenType, uid), n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002084 }
2085
Costin Manolache5f383ad92010-12-02 16:44:46 -08002086 private Intent newGrantCredentialsPermissionIntent(Account account, int uid,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002087 AccountAuthenticatorResponse response, String authTokenType) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002088
2089 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Brian Carlstrom46703b02011-04-06 15:41:29 -07002090 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
Costin Manolache9ec17362011-01-17 12:12:37 -08002091 // Since it was set in Eclair+ we can't change it without breaking apps using
2092 // the intent from a non-Activity context.
2093 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002094 intent.addCategory(
2095 String.valueOf(getCredentialPermissionNotificationId(account, authTokenType, uid)));
Costin Manolache5f383ad92010-12-02 16:44:46 -08002096
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002097 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002098 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
2099 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002100 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002101
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002102 return intent;
2103 }
2104
2105 private Integer getCredentialPermissionNotificationId(Account account, String authTokenType,
2106 int uid) {
2107 Integer id;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002108 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002109 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002110 final Pair<Pair<Account, String>, Integer> key =
2111 new Pair<Pair<Account, String>, Integer>(
2112 new Pair<Account, String>(account, authTokenType), uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002113 id = accounts.credentialsPermissionNotificationIds.get(key);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002114 if (id == null) {
2115 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002116 accounts.credentialsPermissionNotificationIds.put(key, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002117 }
2118 }
2119 return id;
2120 }
2121
Amith Yamasani04e0d262012-02-14 11:50:53 -08002122 private Integer getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002123 Integer id;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002124 synchronized (accounts.signinRequiredNotificationIds) {
2125 id = accounts.signinRequiredNotificationIds.get(account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002126 if (id == null) {
2127 id = mNotificationIds.incrementAndGet();
Amith Yamasani04e0d262012-02-14 11:50:53 -08002128 accounts.signinRequiredNotificationIds.put(account, id);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002129 }
2130 }
2131 return id;
2132 }
2133
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002134 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07002135 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07002136 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002137 final boolean expectActivityLaunch, final Bundle optionsIn) {
Fred Quintana56285a62010-12-02 14:20:51 -08002138 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2139 Log.v(TAG, "addAccount: accountType " + accountType
2140 + ", response " + response
2141 + ", authTokenType " + authTokenType
2142 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2143 + ", expectActivityLaunch " + expectActivityLaunch
2144 + ", caller's uid " + Binder.getCallingUid()
2145 + ", pid " + Binder.getCallingPid());
2146 }
Fred Quintana382601f2010-03-25 12:25:10 -07002147 if (response == null) throw new IllegalArgumentException("response is null");
2148 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002149
Amith Yamasani71e6c692013-03-24 17:39:28 -07002150 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002151 final int uid = Binder.getCallingUid();
2152 final int userId = UserHandle.getUserId(uid);
2153 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002154 try {
2155 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2156 "User is not allowed to add an account!");
2157 } catch (RemoteException re) {
2158 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002159 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002160 return;
2161 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002162 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002163 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002164 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2165 "User cannot modify accounts of this type (policy).");
2166 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07002167 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002168 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2169 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002170 return;
2171 }
2172
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002173 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002174 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2175 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2176 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2177
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002178 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002179 long identityToken = clearCallingIdentity();
2180 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002181 UserAccounts accounts = getUserAccounts(usrId);
2182 logRecordWithUid(
2183 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002184 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002185 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002186 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002187 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002188 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07002189 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07002190 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002191 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002192
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002193 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002194 protected String toDebugString(long now) {
2195 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07002196 + ", accountType " + accountType
2197 + ", requiredFeatures "
2198 + (requiredFeatures != null
2199 ? TextUtils.join(",", requiredFeatures)
2200 : null);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002201 }
2202 }.bind();
2203 } finally {
2204 restoreCallingIdentity(identityToken);
2205 }
Fred Quintana60307342009-03-24 22:48:12 -07002206 }
2207
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002208 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002209 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
2210 final String authTokenType, final String[] requiredFeatures,
2211 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002212 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002213 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2214 Log.v(TAG, "addAccount: accountType " + accountType
2215 + ", response " + response
2216 + ", authTokenType " + authTokenType
2217 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2218 + ", expectActivityLaunch " + expectActivityLaunch
2219 + ", caller's uid " + Binder.getCallingUid()
2220 + ", pid " + Binder.getCallingPid()
2221 + ", for user id " + userId);
2222 }
2223 if (response == null) throw new IllegalArgumentException("response is null");
2224 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002225 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002226 if (isCrossUser(callingUid, userId)) {
2227 throw new SecurityException(
2228 String.format(
2229 "User %s trying to add account for %s" ,
2230 UserHandle.getCallingUserId(),
2231 userId));
2232 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002233
2234 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002235 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002236 try {
2237 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2238 "User is not allowed to add an account!");
2239 } catch (RemoteException re) {
2240 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002241 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002242 return;
2243 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002244 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002245 try {
2246 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2247 "User cannot modify accounts of this type (policy).");
2248 } catch (RemoteException re) {
2249 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002250 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2251 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002252 return;
2253 }
2254
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002255 final int pid = Binder.getCallingPid();
2256 final int uid = Binder.getCallingUid();
2257 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2258 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2259 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2260
2261 long identityToken = clearCallingIdentity();
2262 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002263 UserAccounts accounts = getUserAccounts(userId);
2264 logRecordWithUid(
2265 accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002266 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002267 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07002268 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002269 @Override
2270 public void run() throws RemoteException {
2271 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
2272 options);
2273 }
2274
2275 @Override
2276 protected String toDebugString(long now) {
2277 return super.toDebugString(now) + ", addAccount"
2278 + ", accountType " + accountType
2279 + ", requiredFeatures "
2280 + (requiredFeatures != null
2281 ? TextUtils.join(",", requiredFeatures)
2282 : null);
2283 }
2284 }.bind();
2285 } finally {
2286 restoreCallingIdentity(identityToken);
2287 }
2288 }
2289
Sandra Kwan78812282015-11-04 11:19:47 -08002290 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002291 public void startAddAccountSession(
2292 final IAccountManagerResponse response,
2293 final String accountType,
2294 final String authTokenType,
2295 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08002296 final boolean expectActivityLaunch,
2297 final Bundle optionsIn) {
2298 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2299 Log.v(TAG,
2300 "startAddAccountSession: accountType " + accountType
2301 + ", response " + response
2302 + ", authTokenType " + authTokenType
2303 + ", requiredFeatures " + stringArrayToString(requiredFeatures)
2304 + ", expectActivityLaunch " + expectActivityLaunch
2305 + ", caller's uid " + Binder.getCallingUid()
2306 + ", pid " + Binder.getCallingPid());
2307 }
2308 if (response == null) {
2309 throw new IllegalArgumentException("response is null");
2310 }
2311 if (accountType == null) {
2312 throw new IllegalArgumentException("accountType is null");
2313 }
2314
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002315 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002316 // Only allow system to start session
2317 if (!isSystemUid(uid)) {
2318 String msg = String.format(
2319 "uid %s cannot stat add account session.",
2320 uid);
2321 throw new SecurityException(msg);
2322 }
2323
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002324 final int userId = UserHandle.getUserId(uid);
2325 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002326 try {
2327 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2328 "User is not allowed to add an account!");
2329 } catch (RemoteException re) {
2330 }
2331 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2332 return;
2333 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002334 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002335 try {
2336 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2337 "User cannot modify accounts of this type (policy).");
2338 } catch (RemoteException re) {
2339 }
2340 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2341 userId);
2342 return;
2343 }
2344
2345 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08002346 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
2347 options.putInt(AccountManager.KEY_CALLER_UID, uid);
2348 options.putInt(AccountManager.KEY_CALLER_PID, pid);
2349
2350 int usrId = UserHandle.getCallingUserId();
2351 long identityToken = clearCallingIdentity();
2352 try {
2353 UserAccounts accounts = getUserAccounts(usrId);
2354 logRecordWithUid(accounts, DebugDbHelper.ACTION_CALLED_START_ACCOUNT_ADD,
2355 TABLE_ACCOUNTS, uid);
2356 new StartAccountSession(accounts, response, accountType, expectActivityLaunch,
2357 null /* accountName */, false /* authDetailsRequired */,
2358 true /* updateLastAuthenticationTime */) {
2359 @Override
2360 public void run() throws RemoteException {
2361 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
2362 requiredFeatures, options);
2363 }
2364
2365 @Override
2366 protected String toDebugString(long now) {
2367 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
2368 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
2369 + accountType + ", requiredFeatures "
2370 + (requiredFeatures != null ? requiredFeaturesStr : null);
2371 }
2372 }.bind();
2373 } finally {
2374 restoreCallingIdentity(identityToken);
2375 }
2376 }
2377
2378 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
2379 private abstract class StartAccountSession extends Session {
2380
2381 public StartAccountSession(UserAccounts accounts, IAccountManagerResponse response,
2382 String accountType, boolean expectActivityLaunch, String accountName,
2383 boolean authDetailsRequired, boolean updateLastAuthenticationTime) {
2384 super(accounts, response, accountType, expectActivityLaunch,
2385 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
2386 updateLastAuthenticationTime);
2387 }
2388
2389 @Override
2390 public void onResult(Bundle result) {
2391 mNumResults++;
2392 Intent intent = null;
2393
2394 if (result != null
2395 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
2396 /*
2397 * The Authenticator API allows third party authenticators to
2398 * supply arbitrary intents to other apps that they can run,
2399 * this can be very bad when those apps are in the system like
2400 * the System Settings.
2401 */
2402 int authenticatorUid = Binder.getCallingUid();
2403 long bid = Binder.clearCallingIdentity();
2404 try {
2405 PackageManager pm = mContext.getPackageManager();
2406 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
2407 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
2408 if (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authenticatorUid,
2409 targetUid)) {
2410 throw new SecurityException("Activity to be started with KEY_INTENT must "
2411 + "share Authenticator's signatures");
2412 }
2413 } finally {
2414 Binder.restoreCallingIdentity(bid);
2415 }
2416 }
2417
2418 IAccountManagerResponse response;
2419 if (mExpectActivityLaunch && result != null
2420 && result.containsKey(AccountManager.KEY_INTENT)) {
2421 response = mResponse;
2422 } else {
2423 response = getResponseAndClose();
2424 }
2425 if (response == null) {
2426 return;
2427 }
2428 if (result == null) {
2429 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2430 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
2431 + response);
2432 }
2433 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2434 "null bundle returned");
2435 return;
2436 }
2437
2438 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
2439 // All AccountManager error codes are greater
2440 // than 0
2441 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
2442 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2443 return;
2444 }
2445
2446 // Strip auth token from result.
2447 result.remove(AccountManager.KEY_AUTHTOKEN);
2448
2449 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2450 Log.v(TAG,
2451 getClass().getSimpleName() + " calling onResult() on response " + response);
2452 }
2453
2454 // Get the session bundle created by authenticator. The
2455 // bundle contains data necessary for finishing the session
2456 // later. The session bundle will be encrypted here and
2457 // decrypted later when trying to finish the session.
2458 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
2459 if (sessionBundle != null) {
2460 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2461 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08002462 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08002463 Log.w(TAG, "Account type in session bundle doesn't match request.");
2464 }
2465 // Add accountType info to session bundle. This will
2466 // override any value set by authenticator.
2467 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
2468
2469 // Encrypt session bundle before returning to caller.
2470 try {
2471 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2472 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
2473 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
2474 } catch (GeneralSecurityException e) {
2475 if (Log.isLoggable(TAG, Log.DEBUG)) {
2476 Log.v(TAG, "Failed to encrypt session bundle!", e);
2477 }
2478 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
2479 "failed to encrypt session bundle");
2480 return;
2481 }
2482 }
2483
2484 sendResponse(response, result);
2485 }
2486 }
2487
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002488 @Override
2489 public void finishSession(IAccountManagerResponse response,
2490 @NonNull Bundle sessionBundle,
2491 boolean expectActivityLaunch,
2492 Bundle appInfo) {
2493 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2494 Log.v(TAG,
Sandra Kwan390c9d22016-01-12 14:13:37 -08002495 "finishSession: response " + response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002496 + ", expectActivityLaunch " + expectActivityLaunch
2497 + ", caller's uid " + Binder.getCallingUid()
2498 + ", pid " + Binder.getCallingPid());
2499 }
2500 if (response == null) {
2501 throw new IllegalArgumentException("response is null");
2502 }
2503
2504 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
2505 // Account type is added to it before encryption.
2506 if (sessionBundle == null || sessionBundle.size() == 0) {
2507 throw new IllegalArgumentException("sessionBundle is empty");
2508 }
2509
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002510 final int uid = Binder.getCallingUid();
Sandra Kwana578d112015-12-16 16:01:43 -08002511 // Only allow system to finish session
2512 if (!isSystemUid(uid)) {
2513 String msg = String.format(
2514 "uid %s cannot finish session.",
2515 uid);
2516 throw new SecurityException(msg);
2517 }
2518
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002519 final int userId = UserHandle.getUserId(uid);
2520 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002521 sendErrorResponse(response,
2522 AccountManager.ERROR_CODE_USER_RESTRICTED,
2523 "User is not allowed to add an account!");
2524 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
2525 return;
2526 }
2527
2528 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002529 final Bundle decryptedBundle;
2530 final String accountType;
2531 // First decrypt session bundle to get account type for checking permission.
2532 try {
2533 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
2534 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
2535 if (decryptedBundle == null) {
2536 sendErrorResponse(
2537 response,
2538 AccountManager.ERROR_CODE_BAD_REQUEST,
2539 "failed to decrypt session bundle");
2540 return;
2541 }
2542 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
2543 // Account type cannot be null. This should not happen if session bundle was created
2544 // properly by #StartAccountSession.
2545 if (TextUtils.isEmpty(accountType)) {
2546 sendErrorResponse(
2547 response,
2548 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
2549 "accountType is empty");
2550 return;
2551 }
2552
2553 // If by any chances, decryptedBundle contains colliding keys with
2554 // system info
2555 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
2556 // update credentials flow, we should replace with the new values of the current call.
2557 if (appInfo != null) {
2558 decryptedBundle.putAll(appInfo);
2559 }
2560
2561 // Add info that may be used by add account or update credentials flow.
2562 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, uid);
2563 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
2564 } catch (GeneralSecurityException e) {
2565 if (Log.isLoggable(TAG, Log.DEBUG)) {
2566 Log.v(TAG, "Failed to decrypt session bundle!", e);
2567 }
2568 sendErrorResponse(
2569 response,
2570 AccountManager.ERROR_CODE_BAD_REQUEST,
2571 "failed to decrypt session bundle");
2572 return;
2573 }
2574
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002575 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08002576 sendErrorResponse(
2577 response,
2578 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2579 "User cannot modify accounts of this type (policy).");
2580 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2581 userId);
2582 return;
2583 }
2584
2585 long identityToken = clearCallingIdentity();
2586 try {
2587 UserAccounts accounts = getUserAccounts(userId);
2588 logRecordWithUid(
2589 accounts,
2590 DebugDbHelper.ACTION_CALLED_ACCOUNT_SESSION_FINISH,
2591 TABLE_ACCOUNTS,
2592 uid);
2593 new Session(
2594 accounts,
2595 response,
2596 accountType,
2597 expectActivityLaunch,
2598 true /* stripAuthTokenFromResult */,
2599 null /* accountName */,
2600 false /* authDetailsRequired */,
2601 true /* updateLastAuthenticationTime */) {
2602 @Override
2603 public void run() throws RemoteException {
2604 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
2605 }
2606
2607 @Override
2608 protected String toDebugString(long now) {
2609 return super.toDebugString(now)
2610 + ", finishSession"
2611 + ", accountType " + accountType;
2612 }
2613 }.bind();
2614 } finally {
2615 restoreCallingIdentity(identityToken);
2616 }
2617 }
2618
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002619 private void showCantAddAccount(int errorCode, int userId) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002620 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
2621 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
2622 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2623 long identityToken = clearCallingIdentity();
2624 try {
Amith Yamasaniae7034a2014-09-22 12:42:12 -07002625 mContext.startActivityAsUser(cantAddAccount, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002626 } finally {
2627 restoreCallingIdentity(identityToken);
2628 }
2629 }
2630
2631 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002632 public void confirmCredentialsAsUser(
2633 IAccountManagerResponse response,
2634 final Account account,
2635 final Bundle options,
2636 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08002637 int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002638 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002639 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2640 Log.v(TAG, "confirmCredentials: " + account
2641 + ", response " + response
2642 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002643 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002644 + ", pid " + Binder.getCallingPid());
2645 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002646 // Only allow the system process to read accounts of other users
2647 if (isCrossUser(callingUid, userId)) {
2648 throw new SecurityException(
2649 String.format(
2650 "User %s trying to confirm account credentials for %s" ,
2651 UserHandle.getCallingUserId(),
2652 userId));
2653 }
Fred Quintana382601f2010-03-25 12:25:10 -07002654 if (response == null) throw new IllegalArgumentException("response is null");
2655 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002656 long identityToken = clearCallingIdentity();
2657 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002658 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002659 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002660 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002661 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002662 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002663 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002664 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002665 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002666 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002667 protected String toDebugString(long now) {
2668 return super.toDebugString(now) + ", confirmCredentials"
2669 + ", " + account;
2670 }
2671 }.bind();
2672 } finally {
2673 restoreCallingIdentity(identityToken);
2674 }
Fred Quintana60307342009-03-24 22:48:12 -07002675 }
2676
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002677 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002678 public void updateCredentials(IAccountManagerResponse response, final Account account,
2679 final String authTokenType, final boolean expectActivityLaunch,
2680 final Bundle loginOptions) {
Fred Quintana56285a62010-12-02 14:20:51 -08002681 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2682 Log.v(TAG, "updateCredentials: " + account
2683 + ", response " + response
2684 + ", authTokenType " + authTokenType
2685 + ", expectActivityLaunch " + expectActivityLaunch
2686 + ", caller's uid " + Binder.getCallingUid()
2687 + ", pid " + Binder.getCallingPid());
2688 }
Fred Quintana382601f2010-03-25 12:25:10 -07002689 if (response == null) throw new IllegalArgumentException("response is null");
2690 if (account == null) throw new IllegalArgumentException("account is null");
2691 if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002692 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002693 long identityToken = clearCallingIdentity();
2694 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002695 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002696 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002697 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07002698 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002699 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002700 public void run() throws RemoteException {
2701 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
2702 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002703 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002704 protected String toDebugString(long now) {
2705 if (loginOptions != null) loginOptions.keySet();
2706 return super.toDebugString(now) + ", updateCredentials"
2707 + ", " + account
2708 + ", authTokenType " + authTokenType
2709 + ", loginOptions " + loginOptions;
2710 }
2711 }.bind();
2712 } finally {
2713 restoreCallingIdentity(identityToken);
2714 }
Fred Quintana60307342009-03-24 22:48:12 -07002715 }
2716
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002717 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08002718 public void startUpdateCredentialsSession(
2719 IAccountManagerResponse response,
2720 final Account account,
2721 final String authTokenType,
2722 final boolean expectActivityLaunch,
2723 final Bundle loginOptions) {
2724 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2725 Log.v(TAG,
2726 "startUpdateCredentialsSession: " + account + ", response " + response
2727 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
2728 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
2729 + ", pid " + Binder.getCallingPid());
2730 }
2731 if (response == null) {
2732 throw new IllegalArgumentException("response is null");
2733 }
2734 if (account == null) {
2735 throw new IllegalArgumentException("account is null");
2736 }
Sandra Kwana578d112015-12-16 16:01:43 -08002737
2738 final int uid = Binder.getCallingUid();
2739 // Only allow system to start session
2740 if (!isSystemUid(uid)) {
2741 String msg = String.format(
2742 "uid %s cannot start update credentials session.",
2743 uid);
2744 throw new SecurityException(msg);
2745 }
2746
Sandra Kwane68c37e2015-11-12 17:11:49 -08002747 int userId = UserHandle.getCallingUserId();
2748 long identityToken = clearCallingIdentity();
2749 try {
2750 UserAccounts accounts = getUserAccounts(userId);
2751 new StartAccountSession(
2752 accounts,
2753 response,
2754 account.type,
2755 expectActivityLaunch,
2756 account.name,
2757 false /* authDetailsRequired */,
2758 true /* updateLastCredentialTime */) {
2759 @Override
2760 public void run() throws RemoteException {
2761 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
2762 loginOptions);
2763 }
2764
2765 @Override
2766 protected String toDebugString(long now) {
2767 if (loginOptions != null)
2768 loginOptions.keySet();
2769 return super.toDebugString(now)
2770 + ", startUpdateCredentialsSession"
2771 + ", " + account
2772 + ", authTokenType " + authTokenType
2773 + ", loginOptions " + loginOptions;
2774 }
2775 }.bind();
2776 } finally {
2777 restoreCallingIdentity(identityToken);
2778 }
2779 }
2780
2781 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08002782 public void isCredentialsUpdateSuggested(
2783 IAccountManagerResponse response,
2784 final Account account,
2785 final String statusToken) {
2786 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2787 Log.v(TAG,
2788 "isCredentialsUpdateSuggested: " + account + ", response " + response
2789 + ", caller's uid " + Binder.getCallingUid()
2790 + ", pid " + Binder.getCallingPid());
2791 }
2792 if (response == null) {
2793 throw new IllegalArgumentException("response is null");
2794 }
2795 if (account == null) {
2796 throw new IllegalArgumentException("account is null");
2797 }
2798 if (TextUtils.isEmpty(statusToken)) {
2799 throw new IllegalArgumentException("status token is empty");
2800 }
2801
2802 int uid = Binder.getCallingUid();
2803 // Only allow system to start session
2804 if (!isSystemUid(uid)) {
2805 String msg = String.format(
2806 "uid %s cannot stat add account session.",
2807 uid);
2808 throw new SecurityException(msg);
2809 }
2810
2811 int usrId = UserHandle.getCallingUserId();
2812 long identityToken = clearCallingIdentity();
2813 try {
2814 UserAccounts accounts = getUserAccounts(usrId);
2815 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
2816 false /* stripAuthTokenFromResult */, account.name,
2817 false /* authDetailsRequired */) {
2818 @Override
2819 protected String toDebugString(long now) {
2820 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
2821 + ", " + account;
2822 }
2823
2824 @Override
2825 public void run() throws RemoteException {
2826 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
2827 }
2828
2829 @Override
2830 public void onResult(Bundle result) {
2831 IAccountManagerResponse response = getResponseAndClose();
2832 if (response == null) {
2833 return;
2834 }
2835
2836 if (result == null) {
2837 sendErrorResponse(
2838 response,
2839 AccountManager.ERROR_CODE_INVALID_RESPONSE,
2840 "null bundle");
2841 return;
2842 }
2843
2844 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2845 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2846 + response);
2847 }
2848 // Check to see if an error occurred. We know if an error occurred because all
2849 // error codes are greater than 0.
2850 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
2851 sendErrorResponse(response,
2852 result.getInt(AccountManager.KEY_ERROR_CODE),
2853 result.getString(AccountManager.KEY_ERROR_MESSAGE));
2854 return;
2855 }
2856 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
2857 sendErrorResponse(
2858 response,
2859 AccountManager.ERROR_CODE_INVALID_RESPONSE,
2860 "no result in response");
2861 return;
2862 }
2863 final Bundle newResult = new Bundle();
2864 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
2865 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
2866 sendResponse(response, newResult);
2867 }
2868 }.bind();
2869 } finally {
2870 restoreCallingIdentity(identityToken);
2871 }
2872 }
2873
2874 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002875 public void editProperties(IAccountManagerResponse response, final String accountType,
2876 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002877 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002878 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2879 Log.v(TAG, "editProperties: accountType " + accountType
2880 + ", response " + response
2881 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002882 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002883 + ", pid " + Binder.getCallingPid());
2884 }
Fred Quintana382601f2010-03-25 12:25:10 -07002885 if (response == null) throw new IllegalArgumentException("response is null");
2886 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002887 int userId = UserHandle.getCallingUserId();
2888 if (!isAccountManagedByCaller(accountType, callingUid, userId) && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002889 String msg = String.format(
2890 "uid %s cannot edit authenticator properites for account type: %s",
2891 callingUid,
2892 accountType);
2893 throw new SecurityException(msg);
2894 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002895 long identityToken = clearCallingIdentity();
2896 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002897 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002898 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002899 true /* stripAuthTokenFromResult */, null /* accountName */,
2900 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002901 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002902 public void run() throws RemoteException {
2903 mAuthenticator.editProperties(this, mAccountType);
2904 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002905 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002906 protected String toDebugString(long now) {
2907 return super.toDebugString(now) + ", editProperties"
2908 + ", accountType " + accountType;
2909 }
2910 }.bind();
2911 } finally {
2912 restoreCallingIdentity(identityToken);
2913 }
Fred Quintana60307342009-03-24 22:48:12 -07002914 }
2915
Amith Yamasani12747872015-12-07 14:19:49 -08002916 @Override
2917 public boolean someUserHasAccount(@NonNull final Account account) {
2918 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
2919 throw new SecurityException("Only system can check for accounts across users");
2920 }
2921 final long token = Binder.clearCallingIdentity();
2922 try {
2923 AccountAndUser[] allAccounts = getAllAccounts();
2924 for (int i = allAccounts.length - 1; i >= 0; i--) {
2925 if (allAccounts[i].account.equals(account)) {
2926 return true;
2927 }
2928 }
2929 return false;
2930 } finally {
2931 Binder.restoreCallingIdentity(token);
2932 }
2933 }
2934
Fred Quintana33269202009-04-20 16:05:10 -07002935 private class GetAccountsByTypeAndFeatureSession extends Session {
2936 private final String[] mFeatures;
2937 private volatile Account[] mAccountsOfType = null;
2938 private volatile ArrayList<Account> mAccountsWithFeatures = null;
2939 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002940 private final int mCallingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002941
Amith Yamasani04e0d262012-02-14 11:50:53 -08002942 public GetAccountsByTypeAndFeatureSession(UserAccounts accounts,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002943 IAccountManagerResponse response, String type, String[] features, int callingUid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002944 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002945 true /* stripAuthTokenFromResult */, null /* accountName */,
2946 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08002947 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07002948 mFeatures = features;
2949 }
2950
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002951 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002952 public void run() throws RemoteException {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002953 synchronized (mAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07002954 mAccountsOfType = getAccountsFromCacheLocked(mAccounts, mAccountType, mCallingUid,
2955 null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002956 }
Fred Quintana33269202009-04-20 16:05:10 -07002957 // check whether each account matches the requested features
2958 mAccountsWithFeatures = new ArrayList<Account>(mAccountsOfType.length);
2959 mCurrentAccount = 0;
2960
2961 checkAccount();
2962 }
2963
2964 public void checkAccount() {
2965 if (mCurrentAccount >= mAccountsOfType.length) {
2966 sendResult();
2967 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002968 }
Fred Quintana33269202009-04-20 16:05:10 -07002969
Fred Quintana29e94b82010-03-10 12:11:51 -08002970 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
2971 if (accountAuthenticator == null) {
2972 // It is possible that the authenticator has died, which is indicated by
2973 // mAuthenticator being set to null. If this happens then just abort.
2974 // There is no need to send back a result or error in this case since
2975 // that already happened when mAuthenticator was cleared.
2976 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2977 Log.v(TAG, "checkAccount: aborting session since we are no longer"
2978 + " connected to the authenticator, " + toDebugString());
2979 }
2980 return;
2981 }
Fred Quintana33269202009-04-20 16:05:10 -07002982 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08002983 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07002984 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002985 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07002986 }
2987 }
2988
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002989 @Override
Fred Quintana33269202009-04-20 16:05:10 -07002990 public void onResult(Bundle result) {
2991 mNumResults++;
2992 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002993 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07002994 return;
2995 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002996 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07002997 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
2998 }
2999 mCurrentAccount++;
3000 checkAccount();
3001 }
3002
3003 public void sendResult() {
3004 IAccountManagerResponse response = getResponseAndClose();
3005 if (response != null) {
3006 try {
3007 Account[] accounts = new Account[mAccountsWithFeatures.size()];
3008 for (int i = 0; i < accounts.length; i++) {
3009 accounts[i] = mAccountsWithFeatures.get(i);
3010 }
Fred Quintana56285a62010-12-02 14:20:51 -08003011 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3012 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3013 + response);
3014 }
Fred Quintana33269202009-04-20 16:05:10 -07003015 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003016 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07003017 response.onResult(result);
3018 } catch (RemoteException e) {
3019 // if the caller is dead then there is no one to care about remote exceptions
3020 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3021 Log.v(TAG, "failure while notifying response", e);
3022 }
3023 }
3024 }
3025 }
3026
3027
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003028 @Override
Fred Quintana33269202009-04-20 16:05:10 -07003029 protected String toDebugString(long now) {
3030 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
3031 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
3032 }
3033 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003034
Amith Yamasani04e0d262012-02-14 11:50:53 -08003035 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003036 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08003037 * @hide
3038 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003039 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003040 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003041 int callingUid = Binder.getCallingUid();
Svetoslavf3f02ac2015-09-08 14:36:35 -07003042 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3043 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003044 if (visibleAccountTypes.isEmpty()) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003045 return new Account[0];
3046 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003047 long identityToken = clearCallingIdentity();
3048 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003049 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003050 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003051 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003052 callingUid,
3053 null, // packageName
3054 visibleAccountTypes);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003055 } finally {
3056 restoreCallingIdentity(identityToken);
3057 }
3058 }
3059
Amith Yamasanif29f2362012-04-05 18:29:52 -07003060 /**
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003061 * Returns accounts for all running users.
3062 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07003063 * @hide
3064 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003065 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003066 public AccountAndUser[] getRunningAccounts() {
3067 final int[] runningUserIds;
3068 try {
3069 runningUserIds = ActivityManagerNative.getDefault().getRunningUserIds();
3070 } catch (RemoteException e) {
3071 // Running in system_server; should never happen
3072 throw new RuntimeException(e);
3073 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003074 return getAccounts(runningUserIds);
3075 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07003076
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003077 /** {@hide} */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003078 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003079 public AccountAndUser[] getAllAccounts() {
3080 final List<UserInfo> users = getUserManager().getUsers();
3081 final int[] userIds = new int[users.size()];
3082 for (int i = 0; i < userIds.length; i++) {
3083 userIds[i] = users.get(i).id;
3084 }
3085 return getAccounts(userIds);
3086 }
3087
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003088 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07003089 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003090 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07003091 for (int userId : userIds) {
3092 UserAccounts userAccounts = getUserAccounts(userId);
3093 if (userAccounts == null) continue;
3094 synchronized (userAccounts.cacheLock) {
3095 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
3096 Binder.getCallingUid(), null);
3097 for (int a = 0; a < accounts.length; a++) {
3098 runningAccounts.add(new AccountAndUser(accounts[a], userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07003099 }
3100 }
3101 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003102
3103 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
3104 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07003105 }
3106
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003107 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003108 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003109 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
3110 return getAccountsAsUser(type, userId, null, -1, opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003111 }
3112
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003113 @NonNull
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003114 private Account[] getAccountsAsUser(
3115 String type,
3116 int userId,
3117 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003118 int packageUid,
3119 String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003120 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003121 // Only allow the system process to read accounts of other users
3122 if (userId != UserHandle.getCallingUserId()
Amith Yamasanibb49e852013-03-30 19:20:18 -07003123 && callingUid != Process.myUid()
Jim Miller464f5302013-02-27 18:33:25 -08003124 && mContext.checkCallingOrSelfPermission(
3125 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
3126 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003127 throw new SecurityException("User " + UserHandle.getCallingUserId()
3128 + " trying to get account for " + userId);
3129 }
3130
Fred Quintana56285a62010-12-02 14:20:51 -08003131 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3132 Log.v(TAG, "getAccounts: accountType " + type
3133 + ", caller's uid " + Binder.getCallingUid()
3134 + ", pid " + Binder.getCallingPid());
3135 }
Amith Yamasani27db4682013-03-30 17:07:47 -07003136 // If the original calling app was using the framework account chooser activity, we'll
3137 // be passed in the original caller's uid here, which is what should be used for filtering.
3138 if (packageUid != -1 && UserHandle.isSameApp(callingUid, Process.myUid())) {
3139 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07003140 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07003141 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003142
Svetoslavf3f02ac2015-09-08 14:36:35 -07003143 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3144 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003145 if (visibleAccountTypes.isEmpty()
3146 || (type != null && !visibleAccountTypes.contains(type))) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003147 return new Account[0];
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003148 } else if (visibleAccountTypes.contains(type)) {
3149 // Prune the list down to just the requested type.
3150 visibleAccountTypes = new ArrayList<>();
3151 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07003152 } // else aggregate all the visible accounts (it won't matter if the
3153 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003154
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003155 long identityToken = clearCallingIdentity();
3156 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003157 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003158 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003159 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003160 callingUid,
3161 callingPackage,
3162 visibleAccountTypes);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003163 } finally {
3164 restoreCallingIdentity(identityToken);
3165 }
3166 }
3167
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003168 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003169 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003170 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003171 int callingUid,
3172 String callingPackage,
3173 List<String> visibleAccountTypes) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07003174 synchronized (userAccounts.cacheLock) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003175 ArrayList<Account> visibleAccounts = new ArrayList<>();
3176 for (String visibleType : visibleAccountTypes) {
3177 Account[] accountsForType = getAccountsFromCacheLocked(
3178 userAccounts, visibleType, callingUid, callingPackage);
3179 if (accountsForType != null) {
3180 visibleAccounts.addAll(Arrays.asList(accountsForType));
3181 }
3182 }
3183 Account[] result = new Account[visibleAccounts.size()];
3184 for (int i = 0; i < visibleAccounts.size(); i++) {
3185 result[i] = visibleAccounts.get(i);
3186 }
3187 return result;
3188 }
3189 }
3190
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003191 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003192 public void addSharedAccountsFromParentUser(int parentUserId, int userId) {
3193 checkManageUsersPermission("addSharedAccountsFromParentUser");
3194 Account[] accounts = getAccountsAsUser(null, parentUserId, mContext.getOpPackageName());
3195 for (Account account : accounts) {
3196 addSharedAccountAsUser(account, userId);
3197 }
3198 }
3199
3200 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003201 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003202 UserAccounts accounts = getUserAccounts(userId);
3203 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003204 ContentValues values = new ContentValues();
3205 values.put(ACCOUNTS_NAME, account.name);
3206 values.put(ACCOUNTS_TYPE, account.type);
3207 db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3208 new String[] {account.name, account.type});
3209 long accountId = db.insert(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME, values);
3210 if (accountId < 0) {
3211 Log.w(TAG, "insertAccountIntoDatabase: " + account
3212 + ", skipping the DB insert failed");
3213 return false;
3214 }
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003215 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_ADD, TABLE_SHARED_ACCOUNTS, accountId, accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003216 return true;
3217 }
3218
3219 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003220 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
3221 userId = handleIncomingUser(userId);
3222 UserAccounts accounts = getUserAccounts(userId);
3223 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003224 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003225 final ContentValues values = new ContentValues();
3226 values.put(ACCOUNTS_NAME, newName);
3227 values.put(ACCOUNTS_PREVIOUS_NAME, account.name);
3228 int r = db.update(
3229 TABLE_SHARED_ACCOUNTS,
3230 values,
3231 ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3232 new String[] { account.name, account.type });
3233 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003234 int callingUid = getCallingUid();
3235 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_RENAME, TABLE_SHARED_ACCOUNTS,
3236 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003237 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003238 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003239 }
3240 return r > 0;
3241 }
3242
3243 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08003244 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003245 return removeSharedAccountAsUser(account, userId, getCallingUid());
3246 }
3247
3248 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08003249 userId = handleIncomingUser(userId);
3250 UserAccounts accounts = getUserAccounts(userId);
3251 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003252 long sharedTableAccountId = getAccountIdFromSharedTable(db, account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003253 int r = db.delete(TABLE_SHARED_ACCOUNTS, ACCOUNTS_NAME + "=? AND " + ACCOUNTS_TYPE+ "=?",
3254 new String[] {account.name, account.type});
3255 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003256 logRecord(db, DebugDbHelper.ACTION_ACCOUNT_REMOVE, TABLE_SHARED_ACCOUNTS,
3257 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07003258 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08003259 }
3260 return r > 0;
3261 }
3262
3263 @Override
3264 public Account[] getSharedAccountsAsUser(int userId) {
3265 userId = handleIncomingUser(userId);
3266 UserAccounts accounts = getUserAccounts(userId);
3267 ArrayList<Account> accountList = new ArrayList<Account>();
3268 Cursor cursor = null;
3269 try {
3270 cursor = accounts.openHelper.getReadableDatabase()
3271 .query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_NAME, ACCOUNTS_TYPE},
3272 null, null, null, null, null);
3273 if (cursor != null && cursor.moveToFirst()) {
3274 int nameIndex = cursor.getColumnIndex(ACCOUNTS_NAME);
3275 int typeIndex = cursor.getColumnIndex(ACCOUNTS_TYPE);
3276 do {
3277 accountList.add(new Account(cursor.getString(nameIndex),
3278 cursor.getString(typeIndex)));
3279 } while (cursor.moveToNext());
3280 }
3281 } finally {
3282 if (cursor != null) {
3283 cursor.close();
3284 }
3285 }
3286 Account[] accountArray = new Account[accountList.size()];
3287 accountList.toArray(accountArray);
3288 return accountArray;
3289 }
3290
3291 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003292 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003293 public Account[] getAccounts(String type, String opPackageName) {
3294 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003295 }
3296
Amith Yamasani27db4682013-03-30 17:07:47 -07003297 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003298 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003299 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003300 int callingUid = Binder.getCallingUid();
3301 if (!UserHandle.isSameApp(callingUid, Process.myUid())) {
3302 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
3303 + callingUid + " with uid=" + uid);
3304 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003305 return getAccountsAsUser(null, UserHandle.getCallingUserId(), packageName, uid,
3306 opPackageName);
Amith Yamasani27db4682013-03-30 17:07:47 -07003307 }
3308
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003309 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07003310 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07003311 public Account[] getAccountsByTypeForPackage(String type, String packageName,
3312 String opPackageName) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003313 int packageUid = -1;
3314 try {
3315 packageUid = AppGlobals.getPackageManager().getPackageUid(
Jeff Sharkeycd654482016-01-08 17:42:11 -07003316 packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES,
3317 UserHandle.getCallingUserId());
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003318 } catch (RemoteException re) {
3319 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
3320 return new Account[0];
3321 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07003322 return getAccountsAsUser(type, UserHandle.getCallingUserId(), packageName,
3323 packageUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07003324 }
3325
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003326 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003327 public void getAccountsByFeatures(
3328 IAccountManagerResponse response,
3329 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07003330 String[] features,
3331 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003332 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003333 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3334 Log.v(TAG, "getAccounts: accountType " + type
3335 + ", response " + response
3336 + ", features " + stringArrayToString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003337 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003338 + ", pid " + Binder.getCallingPid());
3339 }
Fred Quintana382601f2010-03-25 12:25:10 -07003340 if (response == null) throw new IllegalArgumentException("response is null");
3341 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003342 int userId = UserHandle.getCallingUserId();
3343
Svetoslavf3f02ac2015-09-08 14:36:35 -07003344 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
3345 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003346 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003347 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003348 // Need to return just the accounts that are from matching signatures.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003349 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, new Account[0]);
3350 try {
3351 response.onResult(result);
3352 } catch (RemoteException e) {
3353 Log.e(TAG, "Cannot respond to caller do to exception." , e);
3354 }
3355 return;
3356 }
Fred Quintana33269202009-04-20 16:05:10 -07003357 long identityToken = clearCallingIdentity();
3358 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003359 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003360 if (features == null || features.length == 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003361 Account[] accounts;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003362 synchronized (userAccounts.cacheLock) {
Amith Yamasani27db4682013-03-30 17:07:47 -07003363 accounts = getAccountsFromCacheLocked(userAccounts, type, callingUid, null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003364 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08003365 Bundle result = new Bundle();
3366 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
3367 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003368 return;
3369 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003370 new GetAccountsByTypeAndFeatureSession(
3371 userAccounts,
3372 response,
3373 type,
3374 features,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003375 callingUid).bind();
Fred Quintana33269202009-04-20 16:05:10 -07003376 } finally {
3377 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07003378 }
3379 }
3380
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003381 private long getAccountIdFromSharedTable(SQLiteDatabase db, Account account) {
3382 Cursor cursor = db.query(TABLE_SHARED_ACCOUNTS, new String[]{ACCOUNTS_ID},
3383 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
3384 try {
3385 if (cursor.moveToNext()) {
3386 return cursor.getLong(0);
3387 }
3388 return -1;
3389 } finally {
3390 cursor.close();
3391 }
3392 }
3393
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003394 private long getAccountIdLocked(SQLiteDatabase db, Account account) {
Fred Quintana60307342009-03-24 22:48:12 -07003395 Cursor cursor = db.query(TABLE_ACCOUNTS, new String[]{ACCOUNTS_ID},
Fred Quintanaffd0cb042009-08-15 21:45:26 -07003396 "name=? AND type=?", new String[]{account.name, account.type}, null, null, null);
Fred Quintana60307342009-03-24 22:48:12 -07003397 try {
3398 if (cursor.moveToNext()) {
3399 return cursor.getLong(0);
3400 }
3401 return -1;
3402 } finally {
3403 cursor.close();
3404 }
3405 }
3406
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003407 private long getExtrasIdLocked(SQLiteDatabase db, long accountId, String key) {
Fred Quintana60307342009-03-24 22:48:12 -07003408 Cursor cursor = db.query(TABLE_EXTRAS, new String[]{EXTRAS_ID},
3409 EXTRAS_ACCOUNTS_ID + "=" + accountId + " AND " + EXTRAS_KEY + "=?",
3410 new String[]{key}, null, null, null);
3411 try {
3412 if (cursor.moveToNext()) {
3413 return cursor.getLong(0);
3414 }
3415 return -1;
3416 } finally {
3417 cursor.close();
3418 }
3419 }
3420
Fred Quintanaa698f422009-04-08 19:14:54 -07003421 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07003422 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07003423 IAccountManagerResponse mResponse;
3424 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003425 final boolean mExpectActivityLaunch;
3426 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003427 final String mAccountName;
3428 // Indicates if we need to add auth details(like last credential time)
3429 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003430 // If set, we need to update the last authenticated time. This is
3431 // currently
3432 // used on
3433 // successful confirming credentials.
3434 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07003435
Fred Quintana33269202009-04-20 16:05:10 -07003436 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07003437 private int mNumRequestContinued = 0;
3438 private int mNumErrors = 0;
3439
Fred Quintana60307342009-03-24 22:48:12 -07003440 IAccountAuthenticator mAuthenticator = null;
3441
Fred Quintana8570f742010-02-18 10:32:54 -08003442 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003443 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003444
Amith Yamasani04e0d262012-02-14 11:50:53 -08003445 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003446 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3447 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003448 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
3449 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
3450 }
3451
3452 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
3453 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
3454 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07003455 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08003456 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07003457 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08003458 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08003459 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07003460 mResponse = response;
3461 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07003462 mExpectActivityLaunch = expectActivityLaunch;
3463 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003464 mAccountName = accountName;
3465 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003466 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003467
Fred Quintanaa698f422009-04-08 19:14:54 -07003468 synchronized (mSessions) {
3469 mSessions.put(toString(), this);
3470 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08003471 if (response != null) {
3472 try {
3473 response.asBinder().linkToDeath(this, 0 /* flags */);
3474 } catch (RemoteException e) {
3475 mResponse = null;
3476 binderDied();
3477 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003478 }
Fred Quintana60307342009-03-24 22:48:12 -07003479 }
3480
Fred Quintanaa698f422009-04-08 19:14:54 -07003481 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07003482 if (mResponse == null) {
3483 // this session has already been closed
3484 return null;
3485 }
Fred Quintana60307342009-03-24 22:48:12 -07003486 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07003487 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07003488 return response;
3489 }
3490
Fred Quintanaa698f422009-04-08 19:14:54 -07003491 private void close() {
3492 synchronized (mSessions) {
3493 if (mSessions.remove(toString()) == null) {
3494 // the session was already closed, so bail out now
3495 return;
3496 }
3497 }
3498 if (mResponse != null) {
3499 // stop listening for response deaths
3500 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
3501
3502 // clear this so that we don't accidentally send any further results
3503 mResponse = null;
3504 }
3505 cancelTimeout();
3506 unbind();
3507 }
3508
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003509 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003510 public void binderDied() {
3511 mResponse = null;
3512 close();
3513 }
3514
3515 protected String toDebugString() {
3516 return toDebugString(SystemClock.elapsedRealtime());
3517 }
3518
3519 protected String toDebugString(long now) {
3520 return "Session: expectLaunch " + mExpectActivityLaunch
3521 + ", connected " + (mAuthenticator != null)
3522 + ", stats (" + mNumResults + "/" + mNumRequestContinued
3523 + "/" + mNumErrors + ")"
3524 + ", lifetime " + ((now - mCreationTime) / 1000.0);
3525 }
3526
Fred Quintana60307342009-03-24 22:48:12 -07003527 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003528 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3529 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
3530 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003531 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003532 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003533 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07003534 }
3535 }
3536
3537 private void unbind() {
3538 if (mAuthenticator != null) {
3539 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07003540 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07003541 }
3542 }
3543
Fred Quintana60307342009-03-24 22:48:12 -07003544 public void cancelTimeout() {
3545 mMessageHandler.removeMessages(MESSAGE_TIMED_OUT, this);
3546 }
3547
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003548 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003549 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07003550 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07003551 try {
3552 run();
3553 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003554 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07003555 "remote exception");
3556 }
Fred Quintana60307342009-03-24 22:48:12 -07003557 }
3558
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003559 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07003560 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003561 mAuthenticator = null;
3562 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003563 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003564 try {
3565 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3566 "disconnected");
3567 } catch (RemoteException e) {
3568 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3569 Log.v(TAG, "Session.onServiceDisconnected: "
3570 + "caught RemoteException while responding", e);
3571 }
3572 }
Fred Quintana60307342009-03-24 22:48:12 -07003573 }
3574 }
3575
Fred Quintanab839afc2009-10-14 15:57:28 -07003576 public abstract void run() throws RemoteException;
3577
Fred Quintana60307342009-03-24 22:48:12 -07003578 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07003579 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003580 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07003581 try {
3582 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
3583 "timeout");
3584 } catch (RemoteException e) {
3585 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3586 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
3587 e);
3588 }
3589 }
Fred Quintana60307342009-03-24 22:48:12 -07003590 }
3591 }
3592
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003593 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003594 public void onResult(Bundle result) {
3595 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003596 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003597 if (result != null) {
3598 boolean isSuccessfulConfirmCreds = result.getBoolean(
3599 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003600 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003601 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
3602 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07003603 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003604 // mUpdateLastAuthenticatedTime is true and the confirmRequest
3605 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07003606 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003607 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003608 if (needUpdate || mAuthDetailsRequired) {
3609 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
3610 if (needUpdate && accountPresent) {
3611 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
3612 }
3613 if (mAuthDetailsRequired) {
3614 long lastAuthenticatedTime = -1;
3615 if (accountPresent) {
3616 lastAuthenticatedTime = DatabaseUtils.longForQuery(
3617 mAccounts.openHelper.getReadableDatabase(),
3618 "select " + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
3619 + " from " +
3620 TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
3621 + ACCOUNTS_TYPE + "=?",
3622 new String[] {
3623 mAccountName, mAccountType
3624 });
3625 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07003626 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003627 lastAuthenticatedTime);
3628 }
3629 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003630 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003631 if (result != null
3632 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
3633 /*
3634 * The Authenticator API allows third party authenticators to
3635 * supply arbitrary intents to other apps that they can run,
3636 * this can be very bad when those apps are in the system like
3637 * the System Settings.
3638 */
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003639 int authenticatorUid = Binder.getCallingUid();
Carlos Valdivia416747a2013-10-14 17:22:42 -07003640 long bid = Binder.clearCallingIdentity();
3641 try {
3642 PackageManager pm = mContext.getPackageManager();
3643 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
3644 int targetUid = resolveInfo.activityInfo.applicationInfo.uid;
3645 if (PackageManager.SIGNATURE_MATCH !=
3646 pm.checkSignatures(authenticatorUid, targetUid)) {
3647 throw new SecurityException(
3648 "Activity to be started with KEY_INTENT must " +
3649 "share Authenticator's signatures");
3650 }
3651 } finally {
3652 Binder.restoreCallingIdentity(bid);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003653 }
3654 }
3655 if (result != null
3656 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003657 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
3658 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003659 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
3660 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003661 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
3662 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003663 }
Fred Quintana60307342009-03-24 22:48:12 -07003664 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003665 IAccountManagerResponse response;
3666 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003667 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003668 response = mResponse;
3669 } else {
3670 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07003671 }
Fred Quintana60307342009-03-24 22:48:12 -07003672 if (response != null) {
3673 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07003674 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08003675 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3676 Log.v(TAG, getClass().getSimpleName()
3677 + " calling onError() on response " + response);
3678 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003679 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07003680 "null bundle returned");
3681 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08003682 if (mStripAuthTokenFromResult) {
3683 result.remove(AccountManager.KEY_AUTHTOKEN);
3684 }
Fred Quintana56285a62010-12-02 14:20:51 -08003685 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3686 Log.v(TAG, getClass().getSimpleName()
3687 + " calling onResult() on response " + response);
3688 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003689 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
3690 (intent == null)) {
3691 // All AccountManager error codes are greater than 0
3692 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
3693 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3694 } else {
3695 response.onResult(result);
3696 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003697 }
Fred Quintana60307342009-03-24 22:48:12 -07003698 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003699 // if the caller is dead then there is no one to care about remote exceptions
3700 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3701 Log.v(TAG, "failure while notifying response", e);
3702 }
Fred Quintana60307342009-03-24 22:48:12 -07003703 }
3704 }
3705 }
Fred Quintana60307342009-03-24 22:48:12 -07003706
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003707 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003708 public void onRequestContinued() {
3709 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07003710 }
3711
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003712 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003713 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07003714 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07003715 IAccountManagerResponse response = getResponseAndClose();
3716 if (response != null) {
3717 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08003718 Log.v(TAG, getClass().getSimpleName()
3719 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07003720 }
3721 try {
3722 response.onError(errorCode, errorMessage);
3723 } catch (RemoteException e) {
3724 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3725 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
3726 }
3727 }
3728 } else {
3729 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3730 Log.v(TAG, "Session.onError: already closed");
3731 }
Fred Quintana60307342009-03-24 22:48:12 -07003732 }
3733 }
Fred Quintanab839afc2009-10-14 15:57:28 -07003734
3735 /**
3736 * find the component name for the authenticator and initiate a bind
3737 * if no authenticator or the bind fails then return false, otherwise return true
3738 */
3739 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07003740 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
3741 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
3742 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07003743 if (authenticatorInfo == null) {
3744 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3745 Log.v(TAG, "there is no authenticator for " + authenticatorType
3746 + ", bailing out");
3747 }
3748 return false;
3749 }
3750
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07003751 final ActivityManager am = mContext.getSystemService(ActivityManager.class);
3752 if (am.isUserRunningAndLocked(mAccounts.userId)
3753 && !authenticatorInfo.componentInfo.encryptionAware) {
3754 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
3755 + " which isn't encryption aware");
3756 return false;
3757 }
3758
Fred Quintanab839afc2009-10-14 15:57:28 -07003759 Intent intent = new Intent();
3760 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
3761 intent.setComponent(authenticatorInfo.componentName);
3762 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3763 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
3764 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08003765 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
3766 new UserHandle(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07003767 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3768 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
3769 }
3770 return false;
3771 }
3772
Fred Quintanab839afc2009-10-14 15:57:28 -07003773 return true;
3774 }
Fred Quintana60307342009-03-24 22:48:12 -07003775 }
3776
3777 private class MessageHandler extends Handler {
3778 MessageHandler(Looper looper) {
3779 super(looper);
3780 }
Costin Manolache3348f142009-09-29 18:58:36 -07003781
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003782 @Override
Fred Quintana60307342009-03-24 22:48:12 -07003783 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07003784 switch (msg.what) {
3785 case MESSAGE_TIMED_OUT:
3786 Session session = (Session)msg.obj;
3787 session.onTimedOut();
3788 break;
3789
Amith Yamasani5be347b2013-03-31 17:44:31 -07003790 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00003791 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07003792 break;
3793
Fred Quintana60307342009-03-24 22:48:12 -07003794 default:
3795 throw new IllegalStateException("unhandled message: " + msg.what);
3796 }
3797 }
3798 }
3799
Amith Yamasani04e0d262012-02-14 11:50:53 -08003800 private static String getDatabaseName(int userId) {
3801 File systemDir = Environment.getSystemSecureDirectory();
Amith Yamasani61f57372012-08-31 12:12:28 -07003802 File databaseFile = new File(Environment.getUserSystemDirectory(userId), DATABASE_NAME);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003803 if (userId == 0) {
Amith Yamasania23bb382012-04-11 15:32:07 -07003804 // Migrate old file, if it exists, to the new location.
3805 // Make sure the new file doesn't already exist. A dummy file could have been
3806 // accidentally created in the old location, causing the new one to become corrupted
3807 // as well.
Amith Yamasani04e0d262012-02-14 11:50:53 -08003808 File oldFile = new File(systemDir, DATABASE_NAME);
Amith Yamasania23bb382012-04-11 15:32:07 -07003809 if (oldFile.exists() && !databaseFile.exists()) {
Marc Blankc6b0f992012-03-18 19:16:41 -07003810 // Check for use directory; create if it doesn't exist, else renameTo will fail
Amith Yamasani61f57372012-08-31 12:12:28 -07003811 File userDir = Environment.getUserSystemDirectory(userId);
Marc Blankc6b0f992012-03-18 19:16:41 -07003812 if (!userDir.exists()) {
3813 if (!userDir.mkdirs()) {
3814 throw new IllegalStateException("User dir cannot be created: " + userDir);
3815 }
3816 }
3817 if (!oldFile.renameTo(databaseFile)) {
3818 throw new IllegalStateException("User dir cannot be migrated: " + databaseFile);
3819 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003820 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08003821 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08003822 return databaseFile.getPath();
Oscar Montemayora8529f62009-11-18 10:14:20 -08003823 }
3824
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003825 private static class DebugDbHelper{
3826 private DebugDbHelper() {
3827 }
3828
3829 private static String TABLE_DEBUG = "debug_table";
3830
3831 // Columns for the table
3832 private static String ACTION_TYPE = "action_type";
3833 private static String TIMESTAMP = "time";
3834 private static String CALLER_UID = "caller_uid";
3835 private static String TABLE_NAME = "table_name";
3836 private static String KEY = "primary_key";
3837
3838 // These actions correspond to the occurrence of real actions. Since
3839 // these are called by the authenticators, the uid associated will be
3840 // of the authenticator.
3841 private static String ACTION_SET_PASSWORD = "action_set_password";
3842 private static String ACTION_CLEAR_PASSWORD = "action_clear_password";
3843 private static String ACTION_ACCOUNT_ADD = "action_account_add";
3844 private static String ACTION_ACCOUNT_REMOVE = "action_account_remove";
3845 private static String ACTION_AUTHENTICATOR_REMOVE = "action_authenticator_remove";
3846 private static String ACTION_ACCOUNT_RENAME = "action_account_rename";
3847
3848 // These actions don't necessarily correspond to any action on
3849 // accountDb taking place. As an example, there might be a request for
3850 // addingAccount, which might not lead to addition of account on grounds
3851 // of bad authentication. We will still be logging it to keep track of
3852 // who called.
3853 private static String ACTION_CALLED_ACCOUNT_ADD = "action_called_account_add";
3854 private static String ACTION_CALLED_ACCOUNT_REMOVE = "action_called_account_remove";
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003855
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003856 //This action doesn't add account to accountdb. Account is only
3857 // added in finishSession which may be in a different user profile.
Sandra Kwan78812282015-11-04 11:19:47 -08003858 private static String ACTION_CALLED_START_ACCOUNT_ADD = "action_called_start_account_add";
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003859 private static String ACTION_CALLED_ACCOUNT_SESSION_FINISH =
3860 "action_called_account_session_finish";
Sandra Kwan78812282015-11-04 11:19:47 -08003861
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003862 private static SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3863
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003864 private static void createDebugTable(SQLiteDatabase db) {
3865 db.execSQL("CREATE TABLE " + TABLE_DEBUG + " ( "
3866 + ACCOUNTS_ID + " INTEGER,"
3867 + ACTION_TYPE + " TEXT NOT NULL, "
3868 + TIMESTAMP + " DATETIME,"
3869 + CALLER_UID + " INTEGER NOT NULL,"
3870 + TABLE_NAME + " TEXT NOT NULL,"
3871 + KEY + " INTEGER PRIMARY KEY)");
3872 db.execSQL("CREATE INDEX timestamp_index ON " + TABLE_DEBUG + " (" + TIMESTAMP + ")");
3873 }
3874 }
3875
3876 private void logRecord(UserAccounts accounts, String action, String tableName) {
3877 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3878 logRecord(db, action, tableName, -1, accounts);
3879 }
3880
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003881 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
3882 SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
3883 logRecord(db, action, tableName, -1, accounts, uid);
3884 }
3885
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07003886 /*
3887 * This function receives an opened writable database.
3888 */
3889 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3890 UserAccounts userAccount) {
3891 logRecord(db, action, tableName, accountId, userAccount, getCallingUid());
3892 }
3893
3894 /*
3895 * This function receives an opened writable database.
3896 */
3897 private void logRecord(SQLiteDatabase db, String action, String tableName, long accountId,
3898 UserAccounts userAccount, int callingUid) {
3899 SQLiteStatement logStatement = userAccount.statementForLogging;
3900 logStatement.bindLong(1, accountId);
3901 logStatement.bindString(2, action);
3902 logStatement.bindString(3, DebugDbHelper.dateFromat.format(new Date()));
3903 logStatement.bindLong(4, callingUid);
3904 logStatement.bindString(5, tableName);
3905 logStatement.bindLong(6, userAccount.debugDbInsertionPoint);
3906 logStatement.execute();
3907 logStatement.clearBindings();
3908 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
3909 % MAX_DEBUG_DB_SIZE;
3910 }
3911
3912 /*
3913 * This should only be called once to compile the sql statement for logging
3914 * and to find the insertion point.
3915 */
3916 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(SQLiteDatabase db,
3917 UserAccounts userAccount) {
3918 // Initialize the count if not done earlier.
3919 int size = (int) getDebugTableRowCount(db);
3920 if (size >= MAX_DEBUG_DB_SIZE) {
3921 // Table is full, and we need to find the point where to insert.
3922 userAccount.debugDbInsertionPoint = (int) getDebugTableInsertionPoint(db);
3923 } else {
3924 userAccount.debugDbInsertionPoint = size;
3925 }
3926 compileSqlStatementForLogging(db, userAccount);
3927 }
3928
3929 private void compileSqlStatementForLogging(SQLiteDatabase db, UserAccounts userAccount) {
3930 String sql = "INSERT OR REPLACE INTO " + DebugDbHelper.TABLE_DEBUG
3931 + " VALUES (?,?,?,?,?,?)";
3932 userAccount.statementForLogging = db.compileStatement(sql);
3933 }
3934
3935 private long getDebugTableRowCount(SQLiteDatabase db) {
3936 String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + DebugDbHelper.TABLE_DEBUG;
3937 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3938 }
3939
3940 /*
3941 * Finds the row key where the next insertion should take place. This should
3942 * be invoked only if the table has reached its full capacity.
3943 */
3944 private long getDebugTableInsertionPoint(SQLiteDatabase db) {
3945 // This query finds the smallest timestamp value (and if 2 records have
3946 // same timestamp, the choose the lower id).
3947 String queryCountDebugDbRows = new StringBuilder()
3948 .append("SELECT ").append(DebugDbHelper.KEY)
3949 .append(" FROM ").append(DebugDbHelper.TABLE_DEBUG)
3950 .append(" ORDER BY ")
3951 .append(DebugDbHelper.TIMESTAMP).append(",").append(DebugDbHelper.KEY)
3952 .append(" LIMIT 1")
3953 .toString();
3954 return DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
3955 }
3956
Amith Yamasani04e0d262012-02-14 11:50:53 -08003957 static class DatabaseHelper extends SQLiteOpenHelper {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003958
Amith Yamasani04e0d262012-02-14 11:50:53 -08003959 public DatabaseHelper(Context context, int userId) {
3960 super(context, AccountManagerService.getDatabaseName(userId), null, DATABASE_VERSION);
Fred Quintana60307342009-03-24 22:48:12 -07003961 }
3962
Fred Quintanaf9f240e2011-02-24 18:27:50 -08003963 /**
3964 * This call needs to be made while the mCacheLock is held. The way to
3965 * ensure this is to get the lock any time a method is called ont the DatabaseHelper
3966 * @param db The database.
3967 */
Fred Quintana60307342009-03-24 22:48:12 -07003968 @Override
3969 public void onCreate(SQLiteDatabase db) {
3970 db.execSQL("CREATE TABLE " + TABLE_ACCOUNTS + " ( "
3971 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3972 + ACCOUNTS_NAME + " TEXT NOT NULL, "
3973 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
3974 + ACCOUNTS_PASSWORD + " TEXT, "
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07003975 + ACCOUNTS_PREVIOUS_NAME + " TEXT, "
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003976 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " INTEGER DEFAULT 0, "
Fred Quintana60307342009-03-24 22:48:12 -07003977 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
3978
3979 db.execSQL("CREATE TABLE " + TABLE_AUTHTOKENS + " ( "
3980 + AUTHTOKENS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3981 + AUTHTOKENS_ACCOUNTS_ID + " INTEGER NOT NULL, "
3982 + AUTHTOKENS_TYPE + " TEXT NOT NULL, "
3983 + AUTHTOKENS_AUTHTOKEN + " TEXT, "
3984 + "UNIQUE (" + AUTHTOKENS_ACCOUNTS_ID + "," + AUTHTOKENS_TYPE + "))");
3985
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003986 createGrantsTable(db);
3987
Fred Quintana60307342009-03-24 22:48:12 -07003988 db.execSQL("CREATE TABLE " + TABLE_EXTRAS + " ( "
3989 + EXTRAS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
3990 + EXTRAS_ACCOUNTS_ID + " INTEGER, "
3991 + EXTRAS_KEY + " TEXT NOT NULL, "
3992 + EXTRAS_VALUE + " TEXT, "
3993 + "UNIQUE(" + EXTRAS_ACCOUNTS_ID + "," + EXTRAS_KEY + "))");
3994
3995 db.execSQL("CREATE TABLE " + TABLE_META + " ( "
3996 + META_KEY + " TEXT PRIMARY KEY NOT NULL, "
3997 + META_VALUE + " TEXT)");
Fred Quintanaa698f422009-04-08 19:14:54 -07003998
Amith Yamasani67df64b2012-12-14 12:09:36 -08003999 createSharedAccountsTable(db);
4000
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004001 createAccountsDeletionTrigger(db);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004002
4003 DebugDbHelper.createDebugTable(db);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004004 }
4005
Amith Yamasani67df64b2012-12-14 12:09:36 -08004006 private void createSharedAccountsTable(SQLiteDatabase db) {
4007 db.execSQL("CREATE TABLE " + TABLE_SHARED_ACCOUNTS + " ( "
4008 + ACCOUNTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
4009 + ACCOUNTS_NAME + " TEXT NOT NULL, "
4010 + ACCOUNTS_TYPE + " TEXT NOT NULL, "
4011 + "UNIQUE(" + ACCOUNTS_NAME + "," + ACCOUNTS_TYPE + "))");
4012 }
4013
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004014 private void addLastSuccessfullAuthenticatedTimeColumn(SQLiteDatabase db) {
4015 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN "
4016 + ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS + " DEFAULT 0");
4017 }
4018
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004019 private void addOldAccountNameColumn(SQLiteDatabase db) {
4020 db.execSQL("ALTER TABLE " + TABLE_ACCOUNTS + " ADD COLUMN " + ACCOUNTS_PREVIOUS_NAME);
4021 }
4022
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004023 private void addDebugTable(SQLiteDatabase db) {
4024 DebugDbHelper.createDebugTable(db);
4025 }
4026
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004027 private void createAccountsDeletionTrigger(SQLiteDatabase db) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004028 db.execSQL(""
4029 + " CREATE TRIGGER " + TABLE_ACCOUNTS + "Delete DELETE ON " + TABLE_ACCOUNTS
4030 + " BEGIN"
4031 + " DELETE FROM " + TABLE_AUTHTOKENS
4032 + " WHERE " + AUTHTOKENS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
4033 + " DELETE FROM " + TABLE_EXTRAS
4034 + " WHERE " + EXTRAS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004035 + " DELETE FROM " + TABLE_GRANTS
4036 + " WHERE " + GRANTS_ACCOUNTS_ID + "=OLD." + ACCOUNTS_ID + " ;"
Fred Quintanaa698f422009-04-08 19:14:54 -07004037 + " END");
Fred Quintana60307342009-03-24 22:48:12 -07004038 }
4039
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004040 private void createGrantsTable(SQLiteDatabase db) {
4041 db.execSQL("CREATE TABLE " + TABLE_GRANTS + " ( "
4042 + GRANTS_ACCOUNTS_ID + " INTEGER NOT NULL, "
4043 + GRANTS_AUTH_TOKEN_TYPE + " STRING NOT NULL, "
4044 + GRANTS_GRANTEE_UID + " INTEGER NOT NULL, "
4045 + "UNIQUE (" + GRANTS_ACCOUNTS_ID + "," + GRANTS_AUTH_TOKEN_TYPE
4046 + "," + GRANTS_GRANTEE_UID + "))");
4047 }
4048
Fred Quintana60307342009-03-24 22:48:12 -07004049 @Override
4050 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004051 Log.e(TAG, "upgrade from version " + oldVersion + " to version " + newVersion);
Fred Quintana60307342009-03-24 22:48:12 -07004052
Fred Quintanaa698f422009-04-08 19:14:54 -07004053 if (oldVersion == 1) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004054 // no longer need to do anything since the work is done
4055 // when upgrading from version 2
4056 oldVersion++;
4057 }
4058
4059 if (oldVersion == 2) {
4060 createGrantsTable(db);
4061 db.execSQL("DROP TRIGGER " + TABLE_ACCOUNTS + "Delete");
4062 createAccountsDeletionTrigger(db);
Fred Quintanaa698f422009-04-08 19:14:54 -07004063 oldVersion++;
4064 }
Costin Manolache3348f142009-09-29 18:58:36 -07004065
4066 if (oldVersion == 3) {
4067 db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_TYPE +
4068 " = 'com.google' WHERE " + ACCOUNTS_TYPE + " == 'com.google.GAIA'");
4069 oldVersion++;
4070 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004071
4072 if (oldVersion == 4) {
4073 createSharedAccountsTable(db);
4074 oldVersion++;
4075 }
4076
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004077 if (oldVersion == 5) {
4078 addOldAccountNameColumn(db);
4079 oldVersion++;
4080 }
4081
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004082 if (oldVersion == 6) {
4083 addLastSuccessfullAuthenticatedTimeColumn(db);
4084 oldVersion++;
4085 }
4086
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004087 if (oldVersion == 7) {
4088 addDebugTable(db);
4089 oldVersion++;
4090 }
4091
Amith Yamasani67df64b2012-12-14 12:09:36 -08004092 if (oldVersion != newVersion) {
4093 Log.e(TAG, "failed to upgrade version " + oldVersion + " to version " + newVersion);
4094 }
Fred Quintana60307342009-03-24 22:48:12 -07004095 }
4096
4097 @Override
4098 public void onOpen(SQLiteDatabase db) {
4099 if (Log.isLoggable(TAG, Log.VERBOSE)) Log.v(TAG, "opened database " + DATABASE_NAME);
4100 }
4101 }
4102
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004103 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07004104 return asBinder();
4105 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004106
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004107 /**
4108 * Searches array of arguments for the specified string
4109 * @param args array of argument strings
4110 * @param value value to search for
4111 * @return true if the value is contained in the array
4112 */
4113 private static boolean scanArgs(String[] args, String value) {
4114 if (args != null) {
4115 for (String arg : args) {
4116 if (value.equals(arg)) {
4117 return true;
4118 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004119 }
4120 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004121 return false;
4122 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004123
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004124 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004125 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07004126 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
4127 != PackageManager.PERMISSION_GRANTED) {
4128 fout.println("Permission Denial: can't dump AccountsManager from from pid="
4129 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
4130 + " without permission " + android.Manifest.permission.DUMP);
4131 return;
4132 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004133 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004134 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07004135
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004136 final List<UserInfo> users = getUserManager().getUsers();
4137 for (UserInfo user : users) {
4138 ipw.println("User " + user + ":");
4139 ipw.increaseIndent();
4140 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
4141 ipw.println();
4142 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08004143 }
4144 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004145
Amith Yamasani04e0d262012-02-14 11:50:53 -08004146 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
4147 String[] args, boolean isCheckinRequest) {
4148 synchronized (userAccounts.cacheLock) {
4149 final SQLiteDatabase db = userAccounts.openHelper.getReadableDatabase();
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004150
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004151 if (isCheckinRequest) {
4152 // This is a checkin request. *Only* upload the account types and the count of each.
4153 Cursor cursor = db.query(TABLE_ACCOUNTS, ACCOUNT_TYPE_COUNT_PROJECTION,
4154 null, null, ACCOUNTS_TYPE, null, null);
4155 try {
4156 while (cursor.moveToNext()) {
4157 // print type,count
4158 fout.println(cursor.getString(0) + "," + cursor.getString(1));
4159 }
4160 } finally {
4161 if (cursor != null) {
4162 cursor.close();
4163 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004164 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004165 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004166 Account[] accounts = getAccountsFromCacheLocked(userAccounts, null /* type */,
Amith Yamasani27db4682013-03-30 17:07:47 -07004167 Process.myUid(), null);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004168 fout.println("Accounts: " + accounts.length);
4169 for (Account account : accounts) {
4170 fout.println(" " + account);
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004171 }
Fred Quintana307da1a2010-01-21 14:24:20 -08004172
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004173 // Add debug information.
4174 fout.println();
4175 Cursor cursor = db.query(DebugDbHelper.TABLE_DEBUG, null,
4176 null, null, null, null, DebugDbHelper.TIMESTAMP);
4177 fout.println("AccountId, Action_Type, timestamp, UID, TableName, Key");
4178 fout.println("Accounts History");
4179 try {
4180 while (cursor.moveToNext()) {
4181 // print type,count
4182 fout.println(cursor.getString(0) + "," + cursor.getString(1) + "," +
4183 cursor.getString(2) + "," + cursor.getString(3) + ","
4184 + cursor.getString(4) + "," + cursor.getString(5));
4185 }
4186 } finally {
4187 cursor.close();
4188 }
4189
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004190 fout.println();
4191 synchronized (mSessions) {
4192 final long now = SystemClock.elapsedRealtime();
4193 fout.println("Active Sessions: " + mSessions.size());
4194 for (Session session : mSessions.values()) {
4195 fout.println(" " + session.toDebugString(now));
4196 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004197 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004198
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004199 fout.println();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004200 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004201 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07004202 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004203 }
4204
Amith Yamasani04e0d262012-02-14 11:50:53 -08004205 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Dianne Hackborn41203752012-08-31 14:05:51 -07004206 Intent intent, int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004207 long identityToken = clearCallingIdentity();
4208 try {
4209 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4210 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
4211 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004212
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004213 if (intent.getComponent() != null &&
4214 GrantCredentialsPermissionActivity.class.getName().equals(
4215 intent.getComponent().getClassName())) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004216 createNoCredentialsPermissionNotification(account, intent, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004217 } else {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004218 final Integer notificationId = getSigninRequiredNotificationId(accounts, account);
Fred Quintana33f889a2009-09-14 17:31:26 -07004219 intent.addCategory(String.valueOf(notificationId));
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004220 UserHandle user = new UserHandle(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004221 Context contextForUser = getContextForUser(user);
Fred Quintana33f889a2009-09-14 17:31:26 -07004222 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004223 contextForUser.getText(R.string.notification_title).toString();
Chris Wren1ce4b6d2015-06-11 10:19:43 -04004224 Notification n = new Notification.Builder(contextForUser)
4225 .setWhen(0)
4226 .setSmallIcon(android.R.drawable.stat_sys_warning)
4227 .setColor(contextForUser.getColor(
4228 com.android.internal.R.color.system_notification_accent_color))
4229 .setContentTitle(String.format(notificationTitleFormat, account.name))
4230 .setContentText(message)
4231 .setContentIntent(PendingIntent.getActivityAsUser(
4232 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
4233 null, user))
4234 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004235 installNotification(notificationId, n, user);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004236 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004237 } finally {
4238 restoreCallingIdentity(identityToken);
4239 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004240 }
4241
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004242 protected void installNotification(final int notificationId, final Notification n,
4243 UserHandle user) {
Fred Quintana56285a62010-12-02 14:20:51 -08004244 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004245 .notifyAsUser(null, notificationId, n, user);
Fred Quintana56285a62010-12-02 14:20:51 -08004246 }
4247
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004248 protected void cancelNotification(int id, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004249 long identityToken = clearCallingIdentity();
4250 try {
4251 ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004252 .cancelAsUser(null, id, user);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07004253 } finally {
4254 restoreCallingIdentity(identityToken);
4255 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004256 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004257
Svetoslavf3f02ac2015-09-08 14:36:35 -07004258 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
Fred Quintanab38eb142010-02-24 13:40:54 -08004259 for (String perm : permissions) {
4260 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
4261 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004262 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
Fred Quintanab38eb142010-02-24 13:40:54 -08004263 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004264 final int opCode = AppOpsManager.permissionToOpCode(perm);
4265 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
4266 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
4267 return true;
4268 }
Fred Quintanab38eb142010-02-24 13:40:54 -08004269 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004270 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004271 return false;
4272 }
4273
Amith Yamasani67df64b2012-12-14 12:09:36 -08004274 private int handleIncomingUser(int userId) {
4275 try {
4276 return ActivityManagerNative.getDefault().handleIncomingUser(
4277 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
4278 } catch (RemoteException re) {
4279 // Shouldn't happen, local.
4280 }
4281 return userId;
4282 }
4283
Christopher Tateccbf84f2013-05-08 15:25:41 -07004284 private boolean isPrivileged(int callingUid) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004285 final int callingUserId = UserHandle.getUserId(callingUid);
4286
4287 final PackageManager userPackageManager;
4288 try {
4289 userPackageManager = mContext.createPackageContextAsUser(
4290 "android", 0, new UserHandle(callingUserId)).getPackageManager();
4291 } catch (NameNotFoundException e) {
4292 return false;
4293 }
4294
4295 String[] packages = userPackageManager.getPackagesForUid(callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07004296 for (String name : packages) {
4297 try {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004298 PackageInfo packageInfo = userPackageManager.getPackageInfo(name, 0 /* flags */);
Fred Quintana56285a62010-12-02 14:20:51 -08004299 if (packageInfo != null
Alex Klyubinb9f8a522015-02-03 11:12:59 -08004300 && (packageInfo.applicationInfo.privateFlags
4301 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
Fred Quintana7be59642009-08-24 18:29:25 -07004302 return true;
4303 }
4304 } catch (PackageManager.NameNotFoundException e) {
4305 return false;
4306 }
4307 }
4308 return false;
4309 }
4310
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004311 private boolean permissionIsGranted(
4312 Account account, String authTokenType, int callerUid, int userId) {
Christopher Tateccbf84f2013-05-08 15:25:41 -07004313 final boolean isPrivileged = isPrivileged(callerUid);
Fred Quintana31957f12009-10-21 13:43:10 -07004314 final boolean fromAuthenticator = account != null
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004315 && isAccountManagedByCaller(account.type, callerUid, userId);
Fred Quintana31957f12009-10-21 13:43:10 -07004316 final boolean hasExplicitGrants = account != null
Amith Yamasani04e0d262012-02-14 11:50:53 -08004317 && hasExplicitlyGrantedPermission(account, authTokenType, callerUid);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004318 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4319 Log.v(TAG, "checkGrantsOrCallingUidAgainstAuthenticator: caller uid "
Fred Quintana56285a62010-12-02 14:20:51 -08004320 + callerUid + ", " + account
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004321 + ": is authenticator? " + fromAuthenticator
4322 + ", has explicit permission? " + hasExplicitGrants);
4323 }
Christopher Tateccbf84f2013-05-08 15:25:41 -07004324 return fromAuthenticator || hasExplicitGrants || isPrivileged;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004325 }
4326
Svetoslavf3f02ac2015-09-08 14:36:35 -07004327 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
4328 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004329 if (accountType == null) {
4330 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004331 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07004332 return getTypesVisibleToCaller(callingUid, userId,
4333 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004334 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004335 }
4336
4337 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
4338 if (accountType == null) {
4339 return false;
4340 } else {
4341 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
4342 }
4343 }
4344
Svetoslavf3f02ac2015-09-08 14:36:35 -07004345 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
4346 String opPackageName) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004347 boolean isPermitted =
Svetoslavf3f02ac2015-09-08 14:36:35 -07004348 isPermitted(opPackageName, callingUid, Manifest.permission.GET_ACCOUNTS,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004349 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004350 return getTypesForCaller(callingUid, userId, isPermitted);
4351 }
4352
4353 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
4354 return getTypesForCaller(callingUid, userId, false);
4355 }
4356
4357 private List<String> getTypesForCaller(
4358 int callingUid, int userId, boolean isOtherwisePermitted) {
4359 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004360 long identityToken = Binder.clearCallingIdentity();
4361 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
4362 try {
4363 serviceInfos = mAuthenticatorCache.getAllServices(userId);
4364 } finally {
4365 Binder.restoreCallingIdentity(identityToken);
4366 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004367 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004368 serviceInfos) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004369 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
4370 if (isOtherwisePermitted || sigChk == PackageManager.SIGNATURE_MATCH) {
4371 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004372 }
4373 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004374 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004375 }
4376
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004377 private boolean isAccountPresentForCaller(String accountName, String accountType) {
4378 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
4379 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
4380 if (account.name.equals(accountName)) {
4381 return true;
4382 }
4383 }
4384 }
4385 return false;
4386 }
4387
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004388 private static void checkManageUsersPermission(String message) {
4389 if (ActivityManager.checkComponentPermission(
4390 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
4391 != PackageManager.PERMISSION_GRANTED) {
4392 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
4393 }
4394 }
4395
Amith Yamasani04e0d262012-02-14 11:50:53 -08004396 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
4397 int callerUid) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004398 if (callerUid == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004399 return true;
4400 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004401 UserAccounts accounts = getUserAccountsForCaller();
4402 synchronized (accounts.cacheLock) {
4403 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
4404 String[] args = { String.valueOf(callerUid), authTokenType,
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004405 account.name, account.type};
4406 final boolean permissionGranted =
4407 DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
4408 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
4409 // TODO: Skip this check when running automated tests. Replace this
4410 // with a more general solution.
4411 Log.d(TAG, "no credentials permission for usage of " + account + ", "
Amith Yamasani04e0d262012-02-14 11:50:53 -08004412 + authTokenType + " by uid " + callerUid
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004413 + " but ignoring since device is in test harness.");
4414 return true;
4415 }
4416 return permissionGranted;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004417 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004418 }
4419
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004420 private boolean isSystemUid(int callingUid) {
4421 String[] packages = null;
4422 long ident = Binder.clearCallingIdentity();
4423 try {
4424 packages = mPackageManager.getPackagesForUid(callingUid);
4425 } finally {
4426 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004427 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004428 if (packages != null) {
4429 for (String name : packages) {
4430 try {
4431 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
4432 if (packageInfo != null
4433 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
4434 != 0) {
4435 return true;
4436 }
4437 } catch (PackageManager.NameNotFoundException e) {
4438 Log.w(TAG, String.format("Could not find package [%s]", name), e);
4439 }
4440 }
4441 } else {
4442 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07004443 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07004444 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00004445 }
4446
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004447 /** Succeeds if any of the specified permissions are granted. */
4448 private void checkReadAccountsPermitted(
4449 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004450 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004451 int userId,
4452 String opPackageName) {
4453 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004454 String msg = String.format(
4455 "caller uid %s cannot access %s accounts",
4456 callingUid,
4457 accountType);
4458 Log.w(TAG, " " + msg);
4459 throw new SecurityException(msg);
4460 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004461 }
4462
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004463 private boolean canUserModifyAccounts(int userId, int callingUid) {
4464 // the managing app can always modify accounts
4465 if (isProfileOwner(callingUid)) {
4466 return true;
4467 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004468 if (getUserManager().getUserRestrictions(new UserHandle(userId))
4469 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
4470 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08004471 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004472 return true;
4473 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004474
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004475 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
4476 // the managing app can always modify accounts
4477 if (isProfileOwner(callingUid)) {
4478 return true;
4479 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004480 DevicePolicyManager dpm = (DevicePolicyManager) mContext
4481 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01004482 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02004483 if (typesArray == null) {
4484 return true;
4485 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01004486 for (String forbiddenType : typesArray) {
4487 if (forbiddenType.equals(accountType)) {
4488 return false;
4489 }
4490 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08004491 return true;
4492 }
4493
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00004494 private boolean isProfileOwner(int uid) {
4495 final DevicePolicyManagerInternal dpmi =
4496 LocalServices.getService(DevicePolicyManagerInternal.class);
4497 return (dpmi != null)
4498 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4499 }
4500
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004501 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07004502 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
4503 throws RemoteException {
4504 final int callingUid = getCallingUid();
4505
Amith Yamasani27db4682013-03-30 17:07:47 -07004506 if (callingUid != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07004507 throw new SecurityException();
4508 }
4509
4510 if (value) {
4511 grantAppPermission(account, authTokenType, uid);
4512 } else {
4513 revokeAppPermission(account, authTokenType, uid);
4514 }
4515 }
4516
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004517 /**
4518 * Allow callers with the given uid permission to get credentials for account/authTokenType.
4519 * <p>
4520 * Although this is public it can only be accessed via the AccountManagerService object
4521 * which is in the system. This means we don't need to protect it with permissions.
4522 * @hide
4523 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07004524 private void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07004525 if (account == null || authTokenType == null) {
4526 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07004527 return;
4528 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004529 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08004530 synchronized (accounts.cacheLock) {
4531 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004532 db.beginTransaction();
4533 try {
4534 long accountId = getAccountIdLocked(db, account);
4535 if (accountId >= 0) {
4536 ContentValues values = new ContentValues();
4537 values.put(GRANTS_ACCOUNTS_ID, accountId);
4538 values.put(GRANTS_AUTH_TOKEN_TYPE, authTokenType);
4539 values.put(GRANTS_GRANTEE_UID, uid);
4540 db.insert(TABLE_GRANTS, GRANTS_ACCOUNTS_ID, values);
4541 db.setTransactionSuccessful();
4542 }
4543 } finally {
4544 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004545 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004546 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
4547 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004548 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004549 }
4550
4551 /**
4552 * Don't allow callers with the given uid permission to get credentials for
4553 * account/authTokenType.
4554 * <p>
4555 * Although this is public it can only be accessed via the AccountManagerService object
4556 * which is in the system. This means we don't need to protect it with permissions.
4557 * @hide
4558 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07004559 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07004560 if (account == null || authTokenType == null) {
4561 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07004562 return;
4563 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004564 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08004565 synchronized (accounts.cacheLock) {
4566 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004567 db.beginTransaction();
4568 try {
4569 long accountId = getAccountIdLocked(db, account);
4570 if (accountId >= 0) {
4571 db.delete(TABLE_GRANTS,
4572 GRANTS_ACCOUNTS_ID + "=? AND " + GRANTS_AUTH_TOKEN_TYPE + "=? AND "
4573 + GRANTS_GRANTEE_UID + "=?",
4574 new String[]{String.valueOf(accountId), authTokenType,
4575 String.valueOf(uid)});
4576 db.setTransactionSuccessful();
4577 }
4578 } finally {
4579 db.endTransaction();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004580 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004581 cancelNotification(getCredentialPermissionNotificationId(account, authTokenType, uid),
4582 new UserHandle(accounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004583 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004584 }
Fred Quintana56285a62010-12-02 14:20:51 -08004585
4586 static final private String stringArrayToString(String[] value) {
4587 return value != null ? ("[" + TextUtils.join(",", value) + "]") : null;
4588 }
4589
Amith Yamasani04e0d262012-02-14 11:50:53 -08004590 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
4591 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004592 if (oldAccountsForType != null) {
4593 ArrayList<Account> newAccountsList = new ArrayList<Account>();
4594 for (Account curAccount : oldAccountsForType) {
4595 if (!curAccount.equals(account)) {
4596 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004597 }
4598 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004599 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004600 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004601 } else {
4602 Account[] newAccountsForType = new Account[newAccountsList.size()];
4603 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004604 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004605 }
Fred Quintana56285a62010-12-02 14:20:51 -08004606 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004607 accounts.userDataCache.remove(account);
4608 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004609 accounts.previousNameCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004610 }
4611
4612 /**
4613 * This assumes that the caller has already checked that the account is not already present.
4614 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08004615 private void insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
4616 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004617 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
4618 Account[] newAccountsForType = new Account[oldLength + 1];
4619 if (accountsForType != null) {
4620 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08004621 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004622 newAccountsForType[oldLength] = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004623 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08004624 }
4625
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004626 private Account[] filterSharedAccounts(UserAccounts userAccounts, Account[] unfiltered,
Amith Yamasani27db4682013-03-30 17:07:47 -07004627 int callingUid, String callingPackage) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004628 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Amith Yamasani27db4682013-03-30 17:07:47 -07004629 || callingUid == Process.myUid()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004630 return unfiltered;
4631 }
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004632 UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
4633 if (user != null && user.isRestricted()) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004634 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004635 // If any of the packages is a white listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004636 // otherwise return non-shared accounts only.
4637 // This might be a temporary way to specify a whitelist
4638 String whiteList = mContext.getResources().getString(
4639 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
4640 for (String packageName : packages) {
4641 if (whiteList.contains(";" + packageName + ";")) {
4642 return unfiltered;
4643 }
4644 }
4645 ArrayList<Account> allowed = new ArrayList<Account>();
4646 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
4647 if (sharedAccounts == null || sharedAccounts.length == 0) return unfiltered;
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004648 String requiredAccountType = "";
4649 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07004650 // If there's an explicit callingPackage specified, check if that package
4651 // opted in to see restricted accounts.
4652 if (callingPackage != null) {
4653 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004654 if (pi != null && pi.restrictedAccountType != null) {
4655 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07004656 }
4657 } else {
4658 // Otherwise check if the callingUid has a package that has opted in
4659 for (String packageName : packages) {
4660 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
4661 if (pi != null && pi.restrictedAccountType != null) {
4662 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07004663 break;
4664 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004665 }
4666 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004667 } catch (NameNotFoundException nnfe) {
4668 }
4669 for (Account account : unfiltered) {
4670 if (account.type.equals(requiredAccountType)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004671 allowed.add(account);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07004672 } else {
4673 boolean found = false;
4674 for (Account shared : sharedAccounts) {
4675 if (shared.equals(account)) {
4676 found = true;
4677 break;
4678 }
4679 }
4680 if (!found) {
4681 allowed.add(account);
4682 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004683 }
4684 }
4685 Account[] filtered = new Account[allowed.size()];
4686 allowed.toArray(filtered);
4687 return filtered;
4688 } else {
4689 return unfiltered;
4690 }
4691 }
4692
Amith Yamasani27db4682013-03-30 17:07:47 -07004693 /*
4694 * packageName can be null. If not null, it should be used to filter out restricted accounts
4695 * that the package is not allowed to access.
4696 */
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004697 protected Account[] getAccountsFromCacheLocked(UserAccounts userAccounts, String accountType,
Amith Yamasani27db4682013-03-30 17:07:47 -07004698 int callingUid, String callingPackage) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004699 if (accountType != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004700 final Account[] accounts = userAccounts.accountCache.get(accountType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004701 if (accounts == null) {
4702 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08004703 } else {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004704 return filterSharedAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
Amith Yamasani27db4682013-03-30 17:07:47 -07004705 callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004706 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004707 } else {
4708 int totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004709 for (Account[] accounts : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004710 totalLength += accounts.length;
4711 }
4712 if (totalLength == 0) {
4713 return EMPTY_ACCOUNT_ARRAY;
4714 }
4715 Account[] accounts = new Account[totalLength];
4716 totalLength = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004717 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004718 System.arraycopy(accountsOfType, 0, accounts, totalLength,
4719 accountsOfType.length);
4720 totalLength += accountsOfType.length;
4721 }
Amith Yamasani27db4682013-03-30 17:07:47 -07004722 return filterSharedAccounts(userAccounts, accounts, callingUid, callingPackage);
Fred Quintana56285a62010-12-02 14:20:51 -08004723 }
4724 }
4725
Amith Yamasani04e0d262012-02-14 11:50:53 -08004726 protected void writeUserDataIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4727 Account account, String key, String value) {
4728 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004729 if (userDataForAccount == null) {
4730 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004731 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004732 }
4733 if (value == null) {
4734 userDataForAccount.remove(key);
4735 } else {
4736 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004737 }
4738 }
4739
Carlos Valdivia91979be2015-05-22 14:11:35 -07004740 protected String readCachedTokenInternal(
4741 UserAccounts accounts,
4742 Account account,
4743 String tokenType,
4744 String callingPackage,
4745 byte[] pkgSigDigest) {
4746 synchronized (accounts.cacheLock) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004747 return accounts.accountTokenCaches.get(
4748 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004749 }
4750 }
4751
Amith Yamasani04e0d262012-02-14 11:50:53 -08004752 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts, final SQLiteDatabase db,
4753 Account account, String key, String value) {
4754 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004755 if (authTokensForAccount == null) {
4756 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004757 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004758 }
4759 if (value == null) {
4760 authTokensForAccount.remove(key);
4761 } else {
4762 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08004763 }
4764 }
4765
Amith Yamasani04e0d262012-02-14 11:50:53 -08004766 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
4767 String authTokenType) {
4768 synchronized (accounts.cacheLock) {
4769 HashMap<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004770 if (authTokensForAccount == null) {
4771 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004772 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004773 authTokensForAccount = readAuthTokensForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004774 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004775 }
4776 return authTokensForAccount.get(authTokenType);
4777 }
4778 }
4779
Amith Yamasani04e0d262012-02-14 11:50:53 -08004780 protected String readUserDataInternal(UserAccounts accounts, Account account, String key) {
4781 synchronized (accounts.cacheLock) {
4782 HashMap<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintana56285a62010-12-02 14:20:51 -08004783 if (userDataForAccount == null) {
4784 // need to populate the cache for this account
Amith Yamasani04e0d262012-02-14 11:50:53 -08004785 final SQLiteDatabase db = accounts.openHelper.getReadableDatabase();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004786 userDataForAccount = readUserDataForAccountFromDatabaseLocked(db, account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004787 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08004788 }
4789 return userDataForAccount.get(key);
4790 }
4791 }
4792
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004793 protected HashMap<String, String> readUserDataForAccountFromDatabaseLocked(
4794 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004795 HashMap<String, String> userDataForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004796 Cursor cursor = db.query(TABLE_EXTRAS,
4797 COLUMNS_EXTRAS_KEY_AND_VALUE,
4798 SELECTION_USERDATA_BY_ACCOUNT,
4799 new String[]{account.name, account.type},
4800 null, null, null);
4801 try {
4802 while (cursor.moveToNext()) {
4803 final String tmpkey = cursor.getString(0);
4804 final String value = cursor.getString(1);
4805 userDataForAccount.put(tmpkey, value);
4806 }
4807 } finally {
4808 cursor.close();
4809 }
4810 return userDataForAccount;
4811 }
4812
Fred Quintanaf9f240e2011-02-24 18:27:50 -08004813 protected HashMap<String, String> readAuthTokensForAccountFromDatabaseLocked(
4814 final SQLiteDatabase db, Account account) {
Fred Quintana56285a62010-12-02 14:20:51 -08004815 HashMap<String, String> authTokensForAccount = new HashMap<String, String>();
Fred Quintana56285a62010-12-02 14:20:51 -08004816 Cursor cursor = db.query(TABLE_AUTHTOKENS,
4817 COLUMNS_AUTHTOKENS_TYPE_AND_AUTHTOKEN,
4818 SELECTION_AUTHTOKENS_BY_ACCOUNT,
4819 new String[]{account.name, account.type},
4820 null, null, null);
4821 try {
4822 while (cursor.moveToNext()) {
4823 final String type = cursor.getString(0);
4824 final String authToken = cursor.getString(1);
4825 authTokensForAccount.put(type, authToken);
4826 }
4827 } finally {
4828 cursor.close();
4829 }
4830 return authTokensForAccount;
4831 }
Kenny Guy07ad8dc2014-09-01 20:56:12 +01004832
4833 private Context getContextForUser(UserHandle user) {
4834 try {
4835 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
4836 } catch (NameNotFoundException e) {
4837 // Default to mContext, not finding the package system is running as is unlikely.
4838 return mContext;
4839 }
4840 }
Sandra Kwan78812282015-11-04 11:19:47 -08004841
4842 private void sendResponse(IAccountManagerResponse response, Bundle result) {
4843 try {
4844 response.onResult(result);
4845 } catch (RemoteException e) {
4846 // if the caller is dead then there is no one to care about remote
4847 // exceptions
4848 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4849 Log.v(TAG, "failure while notifying response", e);
4850 }
4851 }
4852 }
4853
4854 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
4855 String errorMessage) {
4856 try {
4857 response.onError(errorCode, errorMessage);
4858 } catch (RemoteException e) {
4859 // if the caller is dead then there is no one to care about remote
4860 // exceptions
4861 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4862 Log.v(TAG, "failure while notifying response", e);
4863 }
4864 }
4865 }
Fred Quintana60307342009-03-24 22:48:12 -07004866}