blob: 8ae592f7978afa9162df752c89e09e8436543167 [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;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070025import android.accounts.AccountManagerInternal;
sunjianf29d5492017-05-11 15:42:31 -070026import android.accounts.AccountManagerResponse;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.accounts.AuthenticatorDescription;
Amith Yamasani23c8b962013-04-10 13:37:18 -070028import android.accounts.CantAddAccountActivity;
sunjianf29d5492017-05-11 15:42:31 -070029import android.accounts.ChooseAccountActivity;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080030import android.accounts.GrantCredentialsPermissionActivity;
31import android.accounts.IAccountAuthenticator;
32import android.accounts.IAccountAuthenticatorResponse;
33import android.accounts.IAccountManager;
34import android.accounts.IAccountManagerResponse;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070035import android.annotation.IntRange;
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -070036import android.annotation.NonNull;
Svet Ganovf6d424f12016-09-20 20:18:53 -070037import android.annotation.Nullable;
Brett Chabot3b4fcbc2011-01-09 13:41:02 -080038import android.app.ActivityManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070039import android.app.ActivityThread;
Svetoslavf3f02ac2015-09-08 14:36:35 -070040import android.app.AppOpsManager;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070041import android.app.INotificationManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070042import android.app.Notification;
43import android.app.NotificationManager;
44import android.app.PendingIntent;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000045import android.app.admin.DeviceAdminInfo;
Sander Alewijnseda1350f2014-05-08 16:59:42 +010046import android.app.admin.DevicePolicyManager;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +000047import android.app.admin.DevicePolicyManagerInternal;
Fred Quintanaa698f422009-04-08 19:14:54 -070048import android.content.BroadcastReceiver;
Doug Zongker885cfc232009-10-21 16:52:44 -070049import android.content.ComponentName;
Fred Quintanaa698f422009-04-08 19:14:54 -070050import android.content.Context;
51import android.content.Intent;
52import android.content.IntentFilter;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070053import android.content.IntentSender;
Fred Quintanab839afc2009-10-14 15:57:28 -070054import android.content.ServiceConnection;
Carlos Valdivia6ede9c32016-03-10 20:12:32 -080055import android.content.pm.ActivityInfo;
Doug Zongker885cfc232009-10-21 16:52:44 -070056import android.content.pm.ApplicationInfo;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070057import android.content.pm.IPackageManager;
Doug Zongker885cfc232009-10-21 16:52:44 -070058import android.content.pm.PackageInfo;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070059import android.content.pm.PackageManager;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -070060import android.content.pm.PackageManager.NameNotFoundException;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070061import android.content.pm.RegisteredServicesCache;
Fred Quintana3ecd5f42009-09-17 12:42:35 -070062import android.content.pm.RegisteredServicesCacheListener;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -070063import android.content.pm.ResolveInfo;
Carlos Valdivia91979be2015-05-22 14:11:35 -070064import android.content.pm.Signature;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070065import android.content.pm.UserInfo;
Fred Quintana60307342009-03-24 22:48:12 -070066import android.database.Cursor;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -070067import android.database.sqlite.SQLiteStatement;
Doug Zongker885cfc232009-10-21 16:52:44 -070068import android.os.Binder;
Fred Quintanaa698f422009-04-08 19:14:54 -070069import android.os.Bundle;
Oscar Montemayora8529f62009-11-18 10:14:20 -080070import android.os.Environment;
Fred Quintanaa698f422009-04-08 19:14:54 -070071import android.os.Handler;
Fred Quintanaa698f422009-04-08 19:14:54 -070072import android.os.IBinder;
73import android.os.Looper;
74import android.os.Message;
Dianne Hackborn164371f2013-10-01 19:10:13 -070075import android.os.Parcel;
sunjianf29d5492017-05-11 15:42:31 -070076import android.os.Parcelable;
Amith Yamasani27db4682013-03-30 17:07:47 -070077import android.os.Process;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070078import android.os.RemoteCallback;
Fred Quintanaa698f422009-04-08 19:14:54 -070079import android.os.RemoteException;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -080080import android.os.StrictMode;
Fred Quintanaa698f422009-04-08 19:14:54 -070081import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070082import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -070083import android.os.UserManager;
Fred Quintanaa698f422009-04-08 19:14:54 -070084import android.text.TextUtils;
85import android.util.Log;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -070086import android.util.Pair;
Jeff Sharkey6eb96202012-10-10 13:13:54 -070087import android.util.Slog;
Amith Yamasani04e0d262012-02-14 11:50:53 -080088import android.util.SparseArray;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -070089import android.util.SparseBooleanArray;
Fred Quintana60307342009-03-24 22:48:12 -070090
Costin Manolacheb61e8fb2011-09-08 11:26:09 -070091import com.android.internal.R;
Svet Ganov5d09c992016-09-07 09:57:41 -070092import com.android.internal.annotations.GuardedBy;
Fyodor Kupoloveeca6582016-04-08 12:14:04 -070093import com.android.internal.annotations.VisibleForTesting;
Svetoslav Ganov5cb29732016-07-11 19:32:30 -070094import com.android.internal.content.PackageMonitor;
Chris Wren282cfef2017-03-27 15:01:44 -040095import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050096import com.android.internal.notification.SystemNotificationChannels;
Amith Yamasani67df64b2012-12-14 12:09:36 -080097import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060098import com.android.internal.util.DumpUtils;
Amith Yamasani04e0d262012-02-14 11:50:53 -080099import com.android.internal.util.IndentingPrintWriter;
Fyodor Kupolov35f68082016-04-06 12:14:17 -0700100import com.android.internal.util.Preconditions;
Benjamin Franzb6c0ce42015-11-05 10:06:51 +0000101import com.android.server.LocalServices;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700102import com.android.server.ServiceThread;
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600103import com.android.server.SystemService;
104
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700105import com.google.android.collect.Lists;
106import com.google.android.collect.Sets;
Costin Manolacheb61e8fb2011-09-08 11:26:09 -0700107
Oscar Montemayora8529f62009-11-18 10:14:20 -0800108import java.io.File;
Fred Quintanaa698f422009-04-08 19:14:54 -0700109import java.io.FileDescriptor;
110import java.io.PrintWriter;
Sandra Kwan78812282015-11-04 11:19:47 -0800111import java.security.GeneralSecurityException;
Carlos Valdivia91979be2015-05-22 14:11:35 -0700112import java.security.MessageDigest;
113import java.security.NoSuchAlgorithmException;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700114import java.text.SimpleDateFormat;
Fred Quintanaa698f422009-04-08 19:14:54 -0700115import java.util.ArrayList;
Fred Quintana56285a62010-12-02 14:20:51 -0800116import java.util.Arrays;
Fred Quintanaa698f422009-04-08 19:14:54 -0700117import java.util.Collection;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700118import java.util.Collections;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700119import java.util.Date;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700120import java.util.HashMap;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -0700121import java.util.HashSet;
Fred Quintana56285a62010-12-02 14:20:51 -0800122import java.util.LinkedHashMap;
Jeff Sharkey6eb96202012-10-10 13:13:54 -0700123import java.util.List;
Andy McFadden2f362292012-01-20 14:43:38 -0800124import java.util.Map;
Sandra Kwan1c9026d2016-02-23 10:22:15 -0800125import java.util.Map.Entry;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700126import java.util.Objects;
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700127import java.util.Set;
Svet Ganovc1c0d1c2016-09-23 19:15:47 -0700128import java.util.UUID;
Svet Ganovf6d424f12016-09-20 20:18:53 -0700129import java.util.concurrent.CopyOnWriteArrayList;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700130import java.util.concurrent.atomic.AtomicReference;
Fred Quintana60307342009-03-24 22:48:12 -0700131
Fred Quintana60307342009-03-24 22:48:12 -0700132/**
133 * A system service that provides account, password, and authtoken management for all
134 * accounts on the device. Some of these calls are implemented with the help of the corresponding
135 * {@link IAccountAuthenticator} services. This service is not accessed by users directly,
136 * instead one uses an instance of {@link AccountManager}, which can be accessed as follows:
Brian Carlstrom46703b02011-04-06 15:41:29 -0700137 * AccountManager accountManager = AccountManager.get(context);
Fred Quintana33269202009-04-20 16:05:10 -0700138 * @hide
Fred Quintana60307342009-03-24 22:48:12 -0700139 */
Fred Quintana3ecd5f42009-09-17 12:42:35 -0700140public class AccountManagerService
141 extends IAccountManager.Stub
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800142 implements RegisteredServicesCacheListener<AuthenticatorDescription> {
Fred Quintana60307342009-03-24 22:48:12 -0700143 private static final String TAG = "AccountManagerService";
144
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600145 public static class Lifecycle extends SystemService {
146 private AccountManagerService mService;
147
148 public Lifecycle(Context context) {
149 super(context);
150 }
151
152 @Override
153 public void onStart() {
Fyodor Kupolovda993802016-09-21 14:47:10 -0700154 mService = new AccountManagerService(new Injector(getContext()));
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600155 publishBinderService(Context.ACCOUNT_SERVICE, mService);
156 }
157
158 @Override
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600159 public void onUnlockUser(int userHandle) {
160 mService.onUnlockUser(userHandle);
161 }
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -0700162
163 @Override
Fyodor Kupolovce25ed22017-05-04 11:44:31 -0700164 public void onStopUser(int userHandle) {
Fyodor Kupolov945c97e2017-06-21 17:45:19 -0700165 Slog.i(TAG, "onStopUser " + userHandle);
166 mService.purgeUserData(userHandle);
Fyodor Kupolovb9da4e42017-03-16 13:01:12 -0700167 }
Jeff Sharkey1cab76a2016-04-12 18:23:31 -0600168 }
169
Svet Ganov5d09c992016-09-07 09:57:41 -0700170 final Context mContext;
Fred Quintana60307342009-03-24 22:48:12 -0700171
Fred Quintana56285a62010-12-02 14:20:51 -0800172 private final PackageManager mPackageManager;
Svetoslavf3f02ac2015-09-08 14:36:35 -0700173 private final AppOpsManager mAppOpsManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700174 private UserManager mUserManager;
Fyodor Kupolovda993802016-09-21 14:47:10 -0700175 private final Injector mInjector;
Fred Quintana56285a62010-12-02 14:20:51 -0800176
Svet Ganov5d09c992016-09-07 09:57:41 -0700177 final MessageHandler mHandler;
Tejas Khorana7b88f0e2016-06-13 13:06:35 -0700178
Fred Quintana60307342009-03-24 22:48:12 -0700179 // Messages that can be sent on mHandler
180 private static final int MESSAGE_TIMED_OUT = 3;
Amith Yamasani5be347b2013-03-31 17:44:31 -0700181 private static final int MESSAGE_COPY_SHARED_ACCOUNT = 4;
Fred Quintana60307342009-03-24 22:48:12 -0700182
Fred Quintana56285a62010-12-02 14:20:51 -0800183 private final IAccountAuthenticatorCache mAuthenticatorCache;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700184 private static final String PRE_N_DATABASE_NAME = "accounts.db";
Fred Quintana7be59642009-08-24 18:29:25 -0700185 private static final Intent ACCOUNTS_CHANGED_INTENT;
Sandra Kwan390c9d22016-01-12 14:13:37 -0800186
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800187 private static final int SIGNATURE_CHECK_MISMATCH = 0;
188 private static final int SIGNATURE_CHECK_MATCH = 1;
189 private static final int SIGNATURE_CHECK_UID_MATCH = 2;
190
Carlos Valdivia91979be2015-05-22 14:11:35 -0700191 static {
192 ACCOUNTS_CHANGED_INTENT = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
Christopher Tatebded68f2017-02-21 11:41:55 -0800193 ACCOUNTS_CHANGED_INTENT.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
194 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Carlos Valdivia91979be2015-05-22 14:11:35 -0700195 }
Fred Quintanaa698f422009-04-08 19:14:54 -0700196
197 private final LinkedHashMap<String, Session> mSessions = new LinkedHashMap<String, Session>();
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700198
Amith Yamasani04e0d262012-02-14 11:50:53 -0800199 static class UserAccounts {
200 private final int userId;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700201 final AccountsDb accountsDb;
Chris Wren717a8812017-03-31 15:34:39 -0400202 private final HashMap<Pair<Pair<Account, String>, Integer>, NotificationId>
203 credentialsPermissionNotificationIds = new HashMap<>();
204 private final HashMap<Account, NotificationId> signinRequiredNotificationIds
205 = new HashMap<>();
Svet Ganov5d09c992016-09-07 09:57:41 -0700206 final Object cacheLock = new Object();
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700207 final Object dbLock = new Object(); // if needed, dbLock must be obtained before cacheLock
Amith Yamasani04e0d262012-02-14 11:50:53 -0800208 /** protected by the {@link #cacheLock} */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700209 final HashMap<String, Account[]> accountCache = new LinkedHashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800210 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700211 private final Map<Account, Map<String, String>> userDataCache = new HashMap<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800212 /** protected by the {@link #cacheLock} */
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -0700213 private final Map<Account, Map<String, String>> authTokenCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700214 /** protected by the {@link #cacheLock} */
Carlos Valdiviac37ee222015-06-17 20:17:37 -0700215 private final TokenCache accountTokenCaches = new TokenCache();
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700216 /** protected by the {@link #cacheLock} */
217 private final Map<Account, Map<String, Integer>> visibilityCache = new HashMap<>();
Carlos Valdivia91979be2015-05-22 14:11:35 -0700218
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700219 /** protected by the {@link #mReceiversForType},
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700220 * type -> (packageName -> number of active receivers)
221 * type == null is used to get notifications about all account types
222 */
223 private final Map<String, Map<String, Integer>> mReceiversForType = new HashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800224
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -0700225 /**
226 * protected by the {@link #cacheLock}
227 *
228 * Caches the previous names associated with an account. Previous names
229 * should be cached because we expect that when an Account is renamed,
230 * many clients will receive a LOGIN_ACCOUNTS_CHANGED broadcast and
231 * want to know if the accounts they care about have been renamed.
232 *
233 * The previous names are wrapped in an {@link AtomicReference} so that
234 * we can distinguish between those accounts with no previous names and
235 * those whose previous names haven't been cached (yet).
236 */
237 private final HashMap<Account, AtomicReference<String>> previousNameCache =
238 new HashMap<Account, AtomicReference<String>>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800239
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700240 private int debugDbInsertionPoint = -1;
Fyodor Kupolov00de49e2016-09-23 13:10:27 -0700241 private SQLiteStatement statementForLogging; // TODO Move to AccountsDb
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -0700242
Fyodor Kupoloveeca6582016-04-08 12:14:04 -0700243 UserAccounts(Context context, int userId, File preNDbFile, File deDbFile) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800244 this.userId = userId;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700245 synchronized (dbLock) {
246 synchronized (cacheLock) {
247 accountsDb = AccountsDb.create(context, userId, preNDbFile, deDbFile);
248 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800249 }
250 }
251 }
252
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700253 private final SparseArray<UserAccounts> mUsers = new SparseArray<>();
Jeff Sharkeyce18c812016-04-27 16:00:41 -0600254 private final SparseBooleanArray mLocalUnlockedUsers = new SparseBooleanArray();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -0700255 // Not thread-safe. Only use in synchronized context
256 private final SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Svet Ganovf6d424f12016-09-20 20:18:53 -0700257 private CopyOnWriteArrayList<AccountManagerInternal.OnAppPermissionChangeListener>
258 mAppPermissionChangeListeners = new CopyOnWriteArrayList<>();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800259
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -0700260 private static AtomicReference<AccountManagerService> sThis = new AtomicReference<>();
Fred Quintana31957f12009-10-21 13:43:10 -0700261 private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
Fred Quintana7be59642009-08-24 18:29:25 -0700262
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700263 /**
264 * This should only be called by system code. One should only call this after the service
265 * has started.
266 * @return a reference to the AccountManagerService instance
267 * @hide
268 */
269 public static AccountManagerService getSingleton() {
270 return sThis.get();
271 }
Fred Quintana60307342009-03-24 22:48:12 -0700272
Fyodor Kupolovda993802016-09-21 14:47:10 -0700273 public AccountManagerService(Injector injector) {
274 mInjector = injector;
275 mContext = injector.getContext();
276 mPackageManager = mContext.getPackageManager();
Svetoslavf3f02ac2015-09-08 14:36:35 -0700277 mAppOpsManager = mContext.getSystemService(AppOpsManager.class);
Fyodor Kupolovda993802016-09-21 14:47:10 -0700278 mHandler = new MessageHandler(injector.getMessageHandlerLooper());
279 mAuthenticatorCache = mInjector.getAccountAuthenticatorCache();
Fred Quintana5ebbb4a2009-11-09 15:42:20 -0800280 mAuthenticatorCache.setListener(this, null /* Handler */);
Fred Quintana60307342009-03-24 22:48:12 -0700281
Fred Quintanad4a1d2e2009-07-16 16:36:38 -0700282 sThis.set(this);
Fred Quintanaafa92b82009-12-01 16:27:03 -0800283
Fred Quintanac1a4e5d2011-02-25 10:44:38 -0800284 IntentFilter intentFilter = new IntentFilter();
285 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
286 intentFilter.addDataScheme("package");
287 mContext.registerReceiver(new BroadcastReceiver() {
288 @Override
289 public void onReceive(Context context1, Intent intent) {
Carlos Valdivia23f58262014-09-05 10:52:41 -0700290 // Don't delete accounts when updating a authenticator's
291 // package.
292 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700293 /* Purging data requires file io, don't block the main thread. This is probably
294 * less than ideal because we are introducing a race condition where old grants
295 * could be exercised until they are purged. But that race condition existed
296 * anyway with the broadcast receiver.
297 *
298 * Ideally, we would completely clear the cache, purge data from the database,
299 * and then rebuild the cache. All under the cache lock. But that change is too
300 * large at this point.
301 */
Dmitry Dementyev0b676422017-03-09 11:51:26 -0800302 final String removedPackageName = intent.getData().getSchemeSpecificPart();
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700303 Runnable purgingRunnable = new Runnable() {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700304 @Override
305 public void run() {
306 purgeOldGrantsAll();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800307 // Notify authenticator about removed app?
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800308 removeVisibilityValuesForPackage(removedPackageName);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -0700309 }
310 };
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700311 mHandler.post(purgingRunnable);
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
Fyodor Kupolovda993802016-09-21 14:47:10 -0700316 injector.addLocalService(new AccountManagerInternalImpl());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700317
Fyodor Kupolov945c97e2017-06-21 17:45:19 -0700318 IntentFilter userFilter = new IntentFilter();
319 userFilter.addAction(Intent.ACTION_USER_REMOVED);
320 mContext.registerReceiverAsUser(new BroadcastReceiver() {
321 @Override
322 public void onReceive(Context context, Intent intent) {
323 String action = intent.getAction();
324 if (Intent.ACTION_USER_REMOVED.equals(action)) {
325 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
326 if (userId < 1) return;
327 Slog.i(TAG, "User " + userId + " removed");
328 purgeUserData(userId);
329 }
330 }
331 }, UserHandle.ALL, userFilter, null, null);
332
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700333 // Need to cancel account request notifications if the update/install can access the account
334 new PackageMonitor() {
335 @Override
336 public void onPackageAdded(String packageName, int uid) {
337 // Called on a handler, and running as the system
338 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
339 }
340
341 @Override
342 public void onPackageUpdateFinished(String packageName, int uid) {
343 // Called on a handler, and running as the system
344 cancelAccountAccessRequestNotificationIfNeeded(uid, true);
345 }
Fyodor Kupolov8873aa32016-08-25 15:25:40 -0700346 }.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700347
348 // Cancel account request notification if an app op was preventing the account access
349 mAppOpsManager.startWatchingMode(AppOpsManager.OP_GET_ACCOUNTS, null,
350 new AppOpsManager.OnOpChangedInternalListener() {
351 @Override
352 public void onOpChanged(int op, String packageName) {
353 try {
354 final int userId = ActivityManager.getCurrentUser();
355 final int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
356 final int mode = mAppOpsManager.checkOpNoThrow(
357 AppOpsManager.OP_GET_ACCOUNTS, uid, packageName);
358 if (mode == AppOpsManager.MODE_ALLOWED) {
359 final long identity = Binder.clearCallingIdentity();
360 try {
361 cancelAccountAccessRequestNotificationIfNeeded(packageName, uid, true);
362 } finally {
363 Binder.restoreCallingIdentity(identity);
364 }
365 }
366 } catch (NameNotFoundException e) {
367 /* ignore */
368 }
369 }
370 });
371
372 // Cancel account request notification if a permission was preventing the account access
373 mPackageManager.addOnPermissionsChangeListener(
374 (int uid) -> {
375 Account[] accounts = null;
376 String[] packageNames = mPackageManager.getPackagesForUid(uid);
377 if (packageNames != null) {
378 final int userId = UserHandle.getUserId(uid);
379 final long identity = Binder.clearCallingIdentity();
380 try {
381 for (String packageName : packageNames) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800382 // if app asked for permission we need to cancel notification even
383 // for O+ applications.
384 if (mPackageManager.checkPermission(
385 Manifest.permission.GET_ACCOUNTS,
386 packageName) != PackageManager.PERMISSION_GRANTED) {
387 continue;
388 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700389
390 if (accounts == null) {
391 accounts = getAccountsAsUser(null, userId, "android");
392 if (ArrayUtils.isEmpty(accounts)) {
393 return;
394 }
395 }
396
397 for (Account account : accounts) {
398 cancelAccountAccessRequestNotificationIfNeeded(
399 account, uid, packageName, true);
400 }
401 }
402 } finally {
403 Binder.restoreCallingIdentity(identity);
404 }
405 }
406 });
407 }
408
409 private void cancelAccountAccessRequestNotificationIfNeeded(int uid,
410 boolean checkAccess) {
411 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
412 for (Account account : accounts) {
413 cancelAccountAccessRequestNotificationIfNeeded(account, uid, checkAccess);
414 }
415 }
416
417 private void cancelAccountAccessRequestNotificationIfNeeded(String packageName, int uid,
418 boolean checkAccess) {
419 Account[] accounts = getAccountsAsUser(null, UserHandle.getUserId(uid), "android");
420 for (Account account : accounts) {
421 cancelAccountAccessRequestNotificationIfNeeded(account, uid, packageName, checkAccess);
422 }
423 }
424
425 private void cancelAccountAccessRequestNotificationIfNeeded(Account account, int uid,
426 boolean checkAccess) {
427 String[] packageNames = mPackageManager.getPackagesForUid(uid);
428 if (packageNames != null) {
429 for (String packageName : packageNames) {
430 cancelAccountAccessRequestNotificationIfNeeded(account, uid,
431 packageName, checkAccess);
432 }
433 }
434 }
435
436 private void cancelAccountAccessRequestNotificationIfNeeded(Account account,
437 int uid, String packageName, boolean checkAccess) {
438 if (!checkAccess || hasAccountAccess(account, packageName,
439 UserHandle.getUserHandleForUid(uid))) {
440 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -0700441 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700442 UserHandle.getUserHandleForUid(uid));
443 }
Fred Quintanaafa92b82009-12-01 16:27:03 -0800444 }
445
Dianne Hackborn164371f2013-10-01 19:10:13 -0700446 @Override
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800447 public boolean addAccountExplicitlyWithVisibility(Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800448 Bundle extras, Map packageToVisibility) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800449 Bundle.setDefusable(extras, true);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700450 int callingUid = Binder.getCallingUid();
451 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800452 if (Log.isLoggable(TAG, Log.VERBOSE)) {
453 Log.v(TAG, "addAccountExplicitly: " + account + ", caller's uid " + callingUid
454 + ", pid " + Binder.getCallingPid());
455 }
456 Preconditions.checkNotNull(account, "account cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800457 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
458 String msg = String.format("uid %s cannot explicitly add accounts of type: %s",
459 callingUid, account.type);
460 throw new SecurityException(msg);
461 }
462 /*
463 * Child users are not allowed to add accounts. Only the accounts that are shared by the
464 * parent profile can be added to child profile.
465 *
466 * TODO: Only allow accounts that were shared to be added by a limited user.
467 */
468 // fails if the account already exists
469 long identityToken = clearCallingIdentity();
470 try {
471 UserAccounts accounts = getUserAccounts(userId);
472 return addAccountInternal(accounts, account, password, extras, callingUid,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800473 (Map<String, Integer>) packageToVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800474 } finally {
475 restoreCallingIdentity(identityToken);
476 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700477 }
478
479 @Override
Dmitry Dementyev52745472016-12-02 10:27:45 -0800480 public Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
481 String accountType) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800482 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700483 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800484 boolean isSystemUid = UserHandle.isSameApp(callingUid, Process.SYSTEM_UID);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700485 List<String> managedTypes = getTypesForCaller(callingUid, userId, isSystemUid);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800486
487 if ((accountType != null && !managedTypes.contains(accountType))
488 || (accountType == null && !isSystemUid)) {
489 throw new SecurityException(
490 "getAccountsAndVisibilityForPackage() called from unauthorized uid "
491 + callingUid + " with packageName=" + packageName);
492 }
493 if (accountType != null) {
494 managedTypes = new ArrayList<String>();
495 managedTypes.add(accountType);
496 }
497
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800498 long identityToken = clearCallingIdentity();
499 try {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700500 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800501 return getAccountsAndVisibilityForPackage(packageName, managedTypes, callingUid,
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700502 accounts);
Dmitry Dementyev06f32e02017-02-16 17:47:48 -0800503 } finally {
504 restoreCallingIdentity(identityToken);
505 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800506 }
507
508 /*
509 * accountTypes may not be null
510 */
511 private Map<Account, Integer> getAccountsAndVisibilityForPackage(String packageName,
512 List<String> accountTypes, Integer callingUid, UserAccounts accounts) {
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700513 if (!packageExistsForUser(packageName, accounts.userId)) {
514 Log.d(TAG, "Package not found " + packageName);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800515 return new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800516 }
517
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -0800518 Map<Account, Integer> result = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800519 for (String accountType : accountTypes) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700520 synchronized (accounts.dbLock) {
521 synchronized (accounts.cacheLock) {
522 final Account[] accountsOfType = accounts.accountCache.get(accountType);
523 if (accountsOfType != null) {
524 for (Account account : accountsOfType) {
525 result.put(account,
526 resolveAccountVisibility(account, packageName, accounts));
527 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800528 }
529 }
530 }
531 }
532 return filterSharedAccounts(accounts, result, callingUid, packageName);
Dmitry Dementyev52745472016-12-02 10:27:45 -0800533 }
534
535 @Override
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800536 public Map<String, Integer> getPackagesAndVisibilityForAccount(Account account) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700537 Preconditions.checkNotNull(account, "account cannot be null");
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700538 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700539 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800540 if (!isAccountManagedByCaller(account.type, callingUid, userId)
541 && !isSystemUid(callingUid)) {
542 String msg =
543 String.format("uid %s cannot get secrets for account %s", callingUid, account);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700544 throw new SecurityException(msg);
545 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700546
547 long identityToken = clearCallingIdentity();
548 try {
549 UserAccounts accounts = getUserAccounts(userId);
550 synchronized (accounts.dbLock) {
551 synchronized (accounts.cacheLock) {
552 return getPackagesAndVisibilityForAccountLocked(account, accounts);
553 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700554 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700555 } finally {
556 restoreCallingIdentity(identityToken);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700557 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700558
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800559 }
560
561 /**
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700562 * Returns Map with all package names and visibility values for given account.
563 * The method and returned map must be guarded by accounts.cacheLock
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800564 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800565 * @param account Account to get visibility values.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800566 * @param accounts UserAccount that currently hosts the account and application
567 *
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700568 * @return Map with cache for package names to visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800569 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700570 private @NonNull Map<String, Integer> getPackagesAndVisibilityForAccountLocked(Account account,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800571 UserAccounts accounts) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700572 Map<String, Integer> accountVisibility = accounts.visibilityCache.get(account);
573 if (accountVisibility == null) {
574 Log.d(TAG, "Visibility was not initialized");
575 accountVisibility = new HashMap<>();
576 accounts.visibilityCache.put(account, accountVisibility);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800577 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700578 return accountVisibility;
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700579 }
580
581 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700582 public int getAccountVisibility(Account account, String packageName) {
583 Preconditions.checkNotNull(account, "account cannot be null");
584 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800585 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700586 int userId = UserHandle.getCallingUserId();
587 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800588 && !isSystemUid(callingUid)) {
589 String msg = String.format(
590 "uid %s cannot get secrets for accounts of type: %s",
591 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700592 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800593 throw new SecurityException(msg);
594 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700595 long identityToken = clearCallingIdentity();
596 try {
597 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyevcbe1bd12017-04-25 17:02:47 -0700598 if (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)) {
599 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
600 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
601 return visibility;
602 } else {
603 return AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
604 }
605 }
606 if (AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName)) {
607 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
608 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
609 return visibility;
610 } else {
611 return AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
612 }
613 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700614 return resolveAccountVisibility(account, packageName, accounts);
615 } finally {
616 restoreCallingIdentity(identityToken);
617 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800618 }
619
620 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800621 * Method returns visibility for given account and package name.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800622 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800623 * @param account The account to check visibility.
624 * @param packageName Package name to check visibility.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800625 * @param accounts UserAccount that currently hosts the account and application
626 *
627 * @return Visibility value, AccountManager.VISIBILITY_UNDEFINED if no value was stored.
628 *
629 */
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700630 private int getAccountVisibilityFromCache(Account account, String packageName,
631 UserAccounts accounts) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -0700632 synchronized (accounts.cacheLock) {
633 Map<String, Integer> accountVisibility =
634 getPackagesAndVisibilityForAccountLocked(account, accounts);
635 Integer visibility = accountVisibility.get(packageName);
636 return visibility != null ? visibility : AccountManager.VISIBILITY_UNDEFINED;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800637 }
638 }
639
640 /**
641 * Method which handles default values for Account visibility.
642 *
643 * @param account The account to check visibility.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800644 * @param packageName Package name to check visibility
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800645 * @param accounts UserAccount that currently hosts the account and application
646 *
647 * @return Visibility value, the method never returns AccountManager.VISIBILITY_UNDEFINED
648 *
649 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800650 private Integer resolveAccountVisibility(Account account, @NonNull String packageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800651 UserAccounts accounts) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800652 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800653 int uid = -1;
654 try {
655 long identityToken = clearCallingIdentity();
656 try {
657 uid = mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
658 } finally {
659 restoreCallingIdentity(identityToken);
660 }
661 } catch (NameNotFoundException e) {
662 Log.d(TAG, "Package not found " + e.getMessage());
663 return AccountManager.VISIBILITY_NOT_VISIBLE;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800664 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800665
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800666 // System visibility can not be restricted.
667 if (UserHandle.isSameApp(uid, Process.SYSTEM_UID)) {
668 return AccountManager.VISIBILITY_VISIBLE;
669 }
670
671 int signatureCheckResult =
672 checkPackageSignature(account.type, uid, accounts.userId);
673
674 // Authenticator can not restrict visibility to itself.
675 if (signatureCheckResult == SIGNATURE_CHECK_UID_MATCH) {
676 return AccountManager.VISIBILITY_VISIBLE; // Authenticator can always see the account
677 }
678
679 // Return stored value if it was set.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700680 int visibility = getAccountVisibilityFromCache(account, packageName, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800681
682 if (AccountManager.VISIBILITY_UNDEFINED != visibility) {
683 return visibility;
684 }
685
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700686 boolean isPrivileged = isPermittedForPackage(packageName, uid, accounts.userId,
Dmitry Dementyevf794c8d2017-02-03 18:17:59 -0800687 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
688
689 // Device/Profile owner gets visibility by default.
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800690 if (isProfileOwner(uid)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800691 return AccountManager.VISIBILITY_VISIBLE;
692 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800693
694 boolean preO = isPreOApplication(packageName);
695 if ((signatureCheckResult != SIGNATURE_CHECK_MISMATCH)
Dmitry Dementyevd6f06722017-04-05 12:43:26 -0700696 || (preO && checkGetAccountsPermission(packageName, uid, accounts.userId))
697 || (checkReadContactsPermission(packageName, uid, accounts.userId)
698 && accountTypeManagesContacts(account.type, accounts.userId))
699 || isPrivileged) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800700 // Use legacy for preO apps with GET_ACCOUNTS permission or pre/postO with signature
701 // match.
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700702 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800703 AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800704 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
705 visibility = AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
706 }
707 } else {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700708 visibility = getAccountVisibilityFromCache(account,
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800709 AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800710 if (AccountManager.VISIBILITY_UNDEFINED == visibility) {
711 visibility = AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE;
712 }
713 }
714 return visibility;
715 }
716
717 /**
718 * Checks targetSdk for a package;
719 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800720 * @param packageName Package name
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800721 *
722 * @return True if package's target SDK is below {@link android.os.Build.VERSION_CODES#O}, or
723 * undefined
724 */
725 private boolean isPreOApplication(String packageName) {
726 try {
727 long identityToken = clearCallingIdentity();
728 ApplicationInfo applicationInfo;
729 try {
730 applicationInfo = mPackageManager.getApplicationInfo(packageName, 0);
731 } finally {
732 restoreCallingIdentity(identityToken);
733 }
734
735 if (applicationInfo != null) {
736 int version = applicationInfo.targetSdkVersion;
737 return version < android.os.Build.VERSION_CODES.O;
738 }
739 return true;
740 } catch (NameNotFoundException e) {
741 Log.d(TAG, "Package not found " + e.getMessage());
742 return true;
743 }
Dmitry Dementyev58fa83622016-12-20 18:08:51 -0800744 }
745
746 @Override
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700747 public boolean setAccountVisibility(Account account, String packageName, int newVisibility) {
748 Preconditions.checkNotNull(account, "account cannot be null");
749 Preconditions.checkNotNull(packageName, "packageName cannot be null");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800750 int callingUid = Binder.getCallingUid();
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700751 int userId = UserHandle.getCallingUserId();
752 if (!isAccountManagedByCaller(account.type, callingUid, userId)
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800753 && !isSystemUid(callingUid)) {
754 String msg = String.format(
755 "uid %s cannot get secrets for accounts of type: %s",
756 callingUid,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700757 account.type);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800758 throw new SecurityException(msg);
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700759 }
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700760 long identityToken = clearCallingIdentity();
761 try {
762 UserAccounts accounts = getUserAccounts(userId);
763 return setAccountVisibility(account, packageName, newVisibility, true /* notify */,
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700764 accounts);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700765 } finally {
766 restoreCallingIdentity(identityToken);
767 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700768 }
769
sunjian066aa5e2017-06-05 12:16:59 -0700770 private boolean isVisible(int visibility) {
771 return visibility == AccountManager.VISIBILITY_VISIBLE ||
772 visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE;
773 }
774
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700775 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800776 * Updates visibility for given account name and package.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700777 *
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800778 * @param account Account to update visibility.
779 * @param packageName Package name for which visibility is updated.
780 * @param newVisibility New visibility calue
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800781 * @param notify if the flag is set applications will get notification about visibility change
782 * @param accounts UserAccount that currently hosts the account and application
783 *
784 * @return True if account visibility was changed.
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700785 */
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800786 private boolean setAccountVisibility(Account account, String packageName, int newVisibility,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800787 boolean notify, UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700788 synchronized (accounts.dbLock) {
789 synchronized (accounts.cacheLock) {
790 Map<String, Integer> packagesToVisibility;
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700791 List<String> accountRemovedReceivers;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700792 if (notify) {
793 if (isSpecialPackageKey(packageName)) {
794 packagesToVisibility =
795 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700796 accountRemovedReceivers = getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700797 } else {
798 if (!packageExistsForUser(packageName, accounts.userId)) {
799 return false; // package is not installed.
800 }
801 packagesToVisibility = new HashMap<>();
802 packagesToVisibility.put(packageName,
803 resolveAccountVisibility(account, packageName, accounts));
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700804 accountRemovedReceivers = new ArrayList<>();
805 if (shouldNotifyPackageOnAccountRemoval(account, packageName, accounts)) {
806 accountRemovedReceivers.add(packageName);
807 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700808 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800809 } else {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700810 // Notifications will not be send - only used during add account.
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700811 if (!isSpecialPackageKey(packageName) &&
812 !packageExistsForUser(packageName, accounts.userId)) {
813 // package is not installed and not meta value.
814 return false;
Nicolas Prevotf7d8df12016-09-16 17:45:34 +0100815 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700816 packagesToVisibility = Collections.emptyMap();
817 accountRemovedReceivers = Collections.emptyList();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800818 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700819
820 if (!updateAccountVisibilityLocked(account, packageName, newVisibility, accounts)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -0800821 return false;
822 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800823
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700824 if (notify) {
825 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
826 .entrySet()) {
sunjian066aa5e2017-06-05 12:16:59 -0700827 int oldVisibility = packageToVisibility.getValue();
828 int currentVisibility =
829 resolveAccountVisibility(account, packageName, accounts);
830 if (isVisible(oldVisibility) != isVisible(currentVisibility)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700831 notifyPackage(packageToVisibility.getKey(), accounts);
832 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700833 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700834 for (String packageNameToNotify : accountRemovedReceivers) {
835 sendAccountRemovedBroadcast(account, packageNameToNotify, accounts.userId);
836 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700837 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700838 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -0700839 return true;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800840 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700841 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -0700842 }
843
Dmitry Dementyev71fa5262017-03-23 12:29:17 -0700844 // Update account visibility in cache and database.
845 private boolean updateAccountVisibilityLocked(Account account, String packageName,
846 int newVisibility, UserAccounts accounts) {
847 final long accountId = accounts.accountsDb.findDeAccountId(account);
848 if (accountId < 0) {
849 return false;
850 }
851
852 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
853 try {
854 if (!accounts.accountsDb.setAccountVisibility(accountId, packageName,
855 newVisibility)) {
856 return false;
857 }
858 } finally {
859 StrictMode.setThreadPolicy(oldPolicy);
860 }
861 Map<String, Integer> accountVisibility =
862 getPackagesAndVisibilityForAccountLocked(account, accounts);
863 accountVisibility.put(packageName, newVisibility);
864 return true;
865 }
866
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700867 @Override
868 public void registerAccountListener(String[] accountTypes, String opPackageName) {
869 int callingUid = Binder.getCallingUid();
870 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700871
872 int userId = UserHandle.getCallingUserId();
873 long identityToken = clearCallingIdentity();
874 try {
875 UserAccounts accounts = getUserAccounts(userId);
876 registerAccountListener(accountTypes, opPackageName, accounts);
877 } finally {
878 restoreCallingIdentity(identityToken);
879 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800880 }
881
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700882 private void registerAccountListener(String[] accountTypes, String opPackageName,
883 UserAccounts accounts) {
884 synchronized (accounts.mReceiversForType) {
885 if (accountTypes == null) {
886 // null for any type
887 accountTypes = new String[] {null};
888 }
889 for (String type : accountTypes) {
890 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
891 if (receivers == null) {
892 receivers = new HashMap<>();
893 accounts.mReceiversForType.put(type, receivers);
894 }
895 Integer cnt = receivers.get(opPackageName);
896 receivers.put(opPackageName, cnt != null ? cnt + 1 : 1);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800897 }
898 }
899 }
900
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700901 @Override
902 public void unregisterAccountListener(String[] accountTypes, String opPackageName) {
903 int callingUid = Binder.getCallingUid();
904 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -0700905 int userId = UserHandle.getCallingUserId();
906 long identityToken = clearCallingIdentity();
907 try {
908 UserAccounts accounts = getUserAccounts(userId);
909 unregisterAccountListener(accountTypes, opPackageName, accounts);
910 } finally {
911 restoreCallingIdentity(identityToken);
912 }
913 }
914
915 private void unregisterAccountListener(String[] accountTypes, String opPackageName,
916 UserAccounts accounts) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700917 synchronized (accounts.mReceiversForType) {
918 if (accountTypes == null) {
919 // null for any type
920 accountTypes = new String[] {null};
921 }
922 for (String type : accountTypes) {
923 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
924 if (receivers == null || receivers.get(opPackageName) == null) {
925 throw new IllegalArgumentException("attempt to unregister wrong receiver");
926 }
927 Integer cnt = receivers.get(opPackageName);
928 if (cnt == 1) {
929 receivers.remove(opPackageName);
930 } else {
931 receivers.put(opPackageName, cnt - 1);
932 }
933 }
934 }
935 }
936
937 // Send notification to all packages which can potentially see the account
938 private void sendNotificationAccountUpdated(Account account, UserAccounts accounts) {
939 Map<String, Integer> packagesToVisibility = getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700940
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700941 for (Entry<String, Integer> packageToVisibility : packagesToVisibility.entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700942 if ((packageToVisibility.getValue() != AccountManager.VISIBILITY_NOT_VISIBLE)
943 && (packageToVisibility.getValue()
944 != AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE)) {
Dmitry Dementyev8882d882017-03-14 17:25:46 -0700945 notifyPackage(packageToVisibility.getKey(), accounts);
946 }
947 }
948 }
949
950 /**
951 * Sends a direct intent to a package, notifying it of account visibility change.
952 *
953 * @param packageName to send Account to
954 * @param accounts UserAccount that currently hosts the account
955 */
956 private void notifyPackage(String packageName, UserAccounts accounts) {
957 Intent intent = new Intent(AccountManager.ACTION_VISIBLE_ACCOUNTS_CHANGED);
958 intent.setPackage(packageName);
959 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
960 mContext.sendBroadcastAsUser(intent, new UserHandle(accounts.userId));
961 }
962
963 // Returns a map from package name to visibility, for packages subscribed
964 // to notifications about any account type, or type of provided account
965 // account type or all types.
966 private Map<String, Integer> getRequestingPackages(Account account, UserAccounts accounts) {
967 Set<String> packages = new HashSet<>();
968 synchronized (accounts.mReceiversForType) {
969 for (String type : new String[] {account.type, null}) {
970 Map<String, Integer> receivers = accounts.mReceiversForType.get(type);
971 if (receivers != null) {
972 packages.addAll(receivers.keySet());
973 }
974 }
975 }
976 Map<String, Integer> result = new HashMap<>();
977 for (String packageName : packages) {
978 result.put(packageName, resolveAccountVisibility(account, packageName, accounts));
979 }
980 return result;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -0800981 }
982
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -0700983 // Returns a list of packages listening to ACTION_ACCOUNT_REMOVED able to see the account.
984 private List<String> getAccountRemovedReceivers(Account account, UserAccounts accounts) {
985 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
986 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
987 List<ResolveInfo> receivers =
988 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
989 List<String> result = new ArrayList<>();
990 if (receivers == null) {
991 return result;
992 }
993 for (ResolveInfo resolveInfo: receivers) {
994 String packageName = resolveInfo.activityInfo.applicationInfo.packageName;
995 int visibility = resolveAccountVisibility(account, packageName, accounts);
996 if (visibility == AccountManager.VISIBILITY_VISIBLE
997 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
998 result.add(packageName);
999 }
1000 }
1001 return result;
1002 }
1003
1004 // Returns true if given package is listening to ACTION_ACCOUNT_REMOVED and can see the account.
1005 private boolean shouldNotifyPackageOnAccountRemoval(Account account,
1006 String packageName, UserAccounts accounts) {
1007 int visibility = resolveAccountVisibility(account, packageName, accounts);
1008 if (visibility != AccountManager.VISIBILITY_VISIBLE
1009 && visibility != AccountManager.VISIBILITY_USER_MANAGED_VISIBLE) {
1010 return false;
1011 }
1012
1013 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
1014 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
1015 intent.setPackage(packageName);
1016 List<ResolveInfo> receivers =
1017 mPackageManager.queryBroadcastReceiversAsUser(intent, 0, accounts.userId);
1018 return (receivers != null && receivers.size() > 0);
1019 }
1020
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001021 private boolean packageExistsForUser(String packageName, int userId) {
1022 try {
1023 long identityToken = clearCallingIdentity();
1024 try {
1025 mPackageManager.getPackageUidAsUser(packageName, userId);
Dmitry Dementyev5c80deb2017-04-04 11:12:42 -07001026 return true;
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001027 } finally {
1028 restoreCallingIdentity(identityToken);
1029 }
1030 } catch (NameNotFoundException e) {
1031 return false;
1032 }
1033 }
1034
1035 /**
1036 * Returns true if packageName is one of special values.
1037 */
1038 private boolean isSpecialPackageKey(String packageName) {
1039 return (AccountManager.PACKAGE_NAME_KEY_LEGACY_VISIBLE.equals(packageName)
1040 || AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE.equals(packageName));
1041 }
1042
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001043 private void sendAccountsChangedBroadcast(int userId) {
1044 Log.i(TAG, "the accounts changed, sending broadcast of "
1045 + ACCOUNTS_CHANGED_INTENT.getAction());
1046 mContext.sendBroadcastAsUser(ACCOUNTS_CHANGED_INTENT, new UserHandle(userId));
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001047 }
1048
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001049 private void sendAccountRemovedBroadcast(Account account, String packageName, int userId) {
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001050 Intent intent = new Intent(AccountManager.ACTION_ACCOUNT_REMOVED);
1051 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001052 intent.setPackage(packageName);
1053 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
1054 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Dmitry Dementyeva461e302017-04-12 11:00:48 -07001055 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
1056 }
1057
Tejas Khorana5edff3b2016-06-28 20:59:52 -07001058 @Override
Dianne Hackborn164371f2013-10-01 19:10:13 -07001059 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1060 throws RemoteException {
1061 try {
1062 return super.onTransact(code, data, reply, flags);
1063 } catch (RuntimeException e) {
1064 // The account manager only throws security exceptions, so let's
1065 // log all others.
1066 if (!(e instanceof SecurityException)) {
1067 Slog.wtf(TAG, "Account Manager Crash", e);
1068 }
1069 throw e;
1070 }
1071 }
1072
Amith Yamasani258848d2012-08-10 17:06:33 -07001073 private UserManager getUserManager() {
1074 if (mUserManager == null) {
Amith Yamasani27db4682013-03-30 17:07:47 -07001075 mUserManager = UserManager.get(mContext);
Amith Yamasani258848d2012-08-10 17:06:33 -07001076 }
1077 return mUserManager;
1078 }
1079
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001080 /**
1081 * Validate internal set of accounts against installed authenticators for
1082 * given user. Clears cached authenticators before validating.
1083 */
1084 public void validateAccounts(int userId) {
1085 final UserAccounts accounts = getUserAccounts(userId);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001086 // Invalidate user-specific cache to make sure we catch any
1087 // removed authenticators.
1088 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
1089 }
1090
1091 /**
1092 * Validate internal set of accounts against installed authenticators for
1093 * given user. Clear cached authenticators before validating when requested.
1094 */
1095 private void validateAccountsInternal(
1096 UserAccounts accounts, boolean invalidateAuthenticatorCache) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001097 if (Log.isLoggable(TAG, Log.DEBUG)) {
1098 Log.d(TAG, "validateAccountsInternal " + accounts.userId
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001099 + " isCeDatabaseAttached=" + accounts.accountsDb.isCeDatabaseAttached()
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001100 + " userLocked=" + mLocalUnlockedUsers.get(accounts.userId));
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001101 }
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001102
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001103 if (invalidateAuthenticatorCache) {
1104 mAuthenticatorCache.invalidateCache(accounts.userId);
1105 }
1106
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001107 final HashMap<String, Integer> knownAuth = getAuthenticatorTypeAndUIDForUser(
1108 mAuthenticatorCache, accounts.userId);
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001109 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001110
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001111 synchronized (accounts.dbLock) {
1112 synchronized (accounts.cacheLock) {
1113 boolean accountDeleted = false;
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001114
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001115 // Get a map of stored authenticator types to UID
1116 final AccountsDb accountsDb = accounts.accountsDb;
1117 Map<String, Integer> metaAuthUid = accountsDb.findMetaAuthUid();
1118 // Create a list of authenticator type whose previous uid no longer exists
1119 HashSet<String> obsoleteAuthType = Sets.newHashSet();
1120 SparseBooleanArray knownUids = null;
1121 for (Entry<String, Integer> authToUidEntry : metaAuthUid.entrySet()) {
1122 String type = authToUidEntry.getKey();
1123 int uid = authToUidEntry.getValue();
1124 Integer knownUid = knownAuth.get(type);
1125 if (knownUid != null && uid == knownUid) {
1126 // Remove it from the knownAuth list if it's unchanged.
1127 knownAuth.remove(type);
1128 } else {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07001129 /*
1130 * The authenticator is presently not cached and should only be triggered
1131 * when we think an authenticator has been removed (or is being updated).
1132 * But we still want to check if any data with the associated uid is
1133 * around. This is an (imperfect) signal that the package may be updating.
1134 *
1135 * A side effect of this is that an authenticator sharing a uid with
1136 * multiple apps won't get its credentials wiped as long as some app with
1137 * that uid is still on the device. But I suspect that this is a rare case.
1138 * And it isn't clear to me how an attacker could really exploit that
1139 * feature.
1140 *
1141 * The upshot is that we don't have to worry about accounts getting
1142 * uninstalled while the authenticator's package is being updated.
1143 *
1144 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001145 if (knownUids == null) {
1146 knownUids = getUidsOfInstalledOrUpdatedPackagesAsUser(accounts.userId);
1147 }
1148 if (!knownUids.get(uid)) {
1149 // The authenticator is not presently available to the cache. And the
1150 // package no longer has a data directory (so we surmise it isn't
1151 // updating). So purge its data from the account databases.
1152 obsoleteAuthType.add(type);
1153 // And delete it from the TABLE_META
1154 accountsDb.deleteMetaByAuthTypeAndUid(type, uid);
1155 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001156 }
1157 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001158
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001159 // Add the newly registered authenticator to TABLE_META. If old authenticators have
1160 // been re-enabled (after being updated for example), then we just overwrite the old
1161 // values.
1162 for (Entry<String, Integer> entry : knownAuth.entrySet()) {
1163 accountsDb.insertOrReplaceMetaAuthTypeAndUid(entry.getKey(), entry.getValue());
1164 }
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001165
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001166 final Map<Long, Account> accountsMap = accountsDb.findAllDeAccounts();
1167 try {
1168 accounts.accountCache.clear();
1169 final HashMap<String, ArrayList<String>> accountNamesByType
1170 = new LinkedHashMap<>();
1171 for (Entry<Long, Account> accountEntry : accountsMap.entrySet()) {
1172 final long accountId = accountEntry.getKey();
1173 final Account account = accountEntry.getValue();
1174 if (obsoleteAuthType.contains(account.type)) {
1175 Slog.w(TAG, "deleting account " + account.name + " because type "
1176 + account.type
1177 + "'s registered authenticator no longer exist.");
1178 Map<String, Integer> packagesToVisibility =
1179 getRequestingPackages(account, accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001180 List<String> accountRemovedReceivers =
1181 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001182 accountsDb.beginTransaction();
1183 try {
1184 accountsDb.deleteDeAccount(accountId);
1185 // Also delete from CE table if user is unlocked; if user is
1186 // currently locked the account will be removed later by
1187 // syncDeCeAccountsLocked
1188 if (userUnlocked) {
1189 accountsDb.deleteCeAccount(accountId);
1190 }
1191 accountsDb.setTransactionSuccessful();
1192 } finally {
1193 accountsDb.endTransaction();
Fyodor Kupolov627fc202016-06-03 11:03:03 -07001194 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001195 accountDeleted = true;
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001196
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001197 logRecord(AccountsDb.DEBUG_ACTION_AUTHENTICATOR_REMOVE,
1198 AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07001199
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001200 accounts.userDataCache.remove(account);
1201 accounts.authTokenCache.remove(account);
1202 accounts.accountTokenCaches.remove(account);
1203 accounts.visibilityCache.remove(account);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001204
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001205 for (Entry<String, Integer> packageToVisibility :
1206 packagesToVisibility.entrySet()) {
sunjian066aa5e2017-06-05 12:16:59 -07001207 if (isVisible(packageToVisibility.getValue())) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001208 notifyPackage(packageToVisibility.getKey(), accounts);
1209 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001210 }
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07001211 for (String packageName : accountRemovedReceivers) {
1212 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
1213 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001214 } else {
1215 ArrayList<String> accountNames = accountNamesByType.get(account.type);
1216 if (accountNames == null) {
1217 accountNames = new ArrayList<>();
1218 accountNamesByType.put(account.type, accountNames);
1219 }
1220 accountNames.add(account.name);
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001221 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001222 }
1223 for (Map.Entry<String, ArrayList<String>> cur : accountNamesByType.entrySet()) {
1224 final String accountType = cur.getKey();
1225 final ArrayList<String> accountNames = cur.getValue();
1226 final Account[] accountsForType = new Account[accountNames.size()];
1227 for (int i = 0; i < accountsForType.length; i++) {
1228 accountsForType[i] = new Account(accountNames.get(i), accountType,
1229 UUID.randomUUID().toString());
Fred Quintana56285a62010-12-02 14:20:51 -08001230 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001231 accounts.accountCache.put(accountType, accountsForType);
Fred Quintana56285a62010-12-02 14:20:51 -08001232 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001233 accounts.visibilityCache.putAll(accountsDb.findAllVisibilityValues());
1234 } finally {
1235 if (accountDeleted) {
1236 sendAccountsChangedBroadcast(accounts.userId);
Fred Quintana56285a62010-12-02 14:20:51 -08001237 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001238 }
Fred Quintanaafa92b82009-12-01 16:27:03 -08001239 }
1240 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07001241 }
1242
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001243 private SparseBooleanArray getUidsOfInstalledOrUpdatedPackagesAsUser(int userId) {
1244 // Get the UIDs of all apps that might have data on the device. We want
1245 // to preserve user data if the app might otherwise be storing data.
1246 List<PackageInfo> pkgsWithData =
1247 mPackageManager.getInstalledPackagesAsUser(
1248 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
1249 SparseBooleanArray knownUids = new SparseBooleanArray(pkgsWithData.size());
1250 for (PackageInfo pkgInfo : pkgsWithData) {
1251 if (pkgInfo.applicationInfo != null
1252 && (pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) != 0) {
1253 knownUids.put(pkgInfo.applicationInfo.uid, true);
1254 }
1255 }
1256 return knownUids;
1257 }
1258
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001259 static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001260 Context context,
1261 int userId) {
1262 AccountAuthenticatorCache authCache = new AccountAuthenticatorCache(context);
Carlos Valdiviaa46b1122016-04-26 19:36:50 -07001263 return getAuthenticatorTypeAndUIDForUser(authCache, userId);
1264 }
1265
1266 private static HashMap<String, Integer> getAuthenticatorTypeAndUIDForUser(
1267 IAccountAuthenticatorCache authCache,
1268 int userId) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08001269 HashMap<String, Integer> knownAuth = new LinkedHashMap<>();
Sandra Kwan1c9026d2016-02-23 10:22:15 -08001270 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> service : authCache
1271 .getAllServices(userId)) {
1272 knownAuth.put(service.type.type, service.uid);
1273 }
1274 return knownAuth;
1275 }
1276
Amith Yamasani04e0d262012-02-14 11:50:53 -08001277 private UserAccounts getUserAccountsForCaller() {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001278 return getUserAccounts(UserHandle.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08001279 }
1280
1281 protected UserAccounts getUserAccounts(int userId) {
1282 synchronized (mUsers) {
1283 UserAccounts accounts = mUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001284 boolean validateAccounts = false;
Amith Yamasani04e0d262012-02-14 11:50:53 -08001285 if (accounts == null) {
Fyodor Kupolovda993802016-09-21 14:47:10 -07001286 File preNDbFile = new File(mInjector.getPreNDatabaseName(userId));
1287 File deDbFile = new File(mInjector.getDeDatabaseName(userId));
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001288 accounts = new UserAccounts(mContext, userId, preNDbFile, deDbFile);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001289 initializeDebugDbSizeAndCompileSqlStatementForLogging(accounts);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001290 mUsers.append(userId, accounts);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001291 purgeOldGrants(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001292 validateAccounts = true;
1293 }
1294 // open CE database if necessary
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001295 if (!accounts.accountsDb.isCeDatabaseAttached() && mLocalUnlockedUsers.get(userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001296 Log.i(TAG, "User " + userId + " is unlocked - opening CE database");
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001297 synchronized (accounts.dbLock) {
1298 synchronized (accounts.cacheLock) {
1299 File ceDatabaseFile = new File(mInjector.getCeDatabaseName(userId));
1300 accounts.accountsDb.attachCeDatabase(ceDatabaseFile);
1301 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001302 }
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001303 syncDeCeAccountsLocked(accounts);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001304 }
1305 if (validateAccounts) {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001306 validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001307 }
1308 return accounts;
1309 }
1310 }
1311
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001312 private void syncDeCeAccountsLocked(UserAccounts accounts) {
1313 Preconditions.checkState(Thread.holdsLock(mUsers), "mUsers lock must be held");
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07001314 List<Account> accountsToRemove = accounts.accountsDb.findCeAccountsNotInDe();
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001315 if (!accountsToRemove.isEmpty()) {
1316 Slog.i(TAG, "Accounts " + accountsToRemove + " were previously deleted while user "
1317 + accounts.userId + " was locked. Removing accounts from CE tables");
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001318 logRecord(accounts, AccountsDb.DEBUG_ACTION_SYNC_DE_CE_ACCOUNTS,
1319 AccountsDb.TABLE_ACCOUNTS);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001320
1321 for (Account account : accountsToRemove) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001322 removeAccountInternal(accounts, account, Process.SYSTEM_UID);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001323 }
1324 }
1325 }
1326
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001327 private void purgeOldGrantsAll() {
1328 synchronized (mUsers) {
1329 for (int i = 0; i < mUsers.size(); i++) {
1330 purgeOldGrants(mUsers.valueAt(i));
1331 }
1332 }
1333 }
1334
1335 private void purgeOldGrants(UserAccounts accounts) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001336 synchronized (accounts.dbLock) {
1337 synchronized (accounts.cacheLock) {
1338 List<Integer> uids = accounts.accountsDb.findAllUidGrants();
1339 for (int uid : uids) {
1340 final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
1341 if (packageExists) {
1342 continue;
1343 }
1344 Log.d(TAG, "deleting grants for UID " + uid
1345 + " because its package is no longer installed");
1346 accounts.accountsDb.deleteGrantsByUid(uid);
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001347 }
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07001348 }
1349 }
1350 }
1351
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001352 private void removeVisibilityValuesForPackage(String packageName) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001353 if (isSpecialPackageKey(packageName)) {
1354 return;
1355 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001356 synchronized (mUsers) {
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001357 int numberOfUsers = mUsers.size();
1358 for (int i = 0; i < numberOfUsers; i++) {
1359 UserAccounts accounts = mUsers.valueAt(i);
1360 try {
1361 mPackageManager.getPackageUidAsUser(packageName, accounts.userId);
1362 } catch (NameNotFoundException e) {
1363 // package does not exist - remove visibility values
1364 accounts.accountsDb.deleteAccountVisibilityForPackage(packageName);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001365 synchronized (accounts.dbLock) {
1366 synchronized (accounts.cacheLock) {
1367 for (Account account : accounts.visibilityCache.keySet()) {
1368 Map<String, Integer> accountVisibility =
1369 getPackagesAndVisibilityForAccountLocked(account, accounts);
1370 accountVisibility.remove(packageName);
1371 }
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07001372 }
1373 }
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001374 }
1375 }
1376 }
1377 }
1378
Fyodor Kupolov945c97e2017-06-21 17:45:19 -07001379 private void purgeUserData(int userId) {
Amith Yamasani13593602012-03-22 16:16:17 -07001380 UserAccounts accounts;
1381 synchronized (mUsers) {
1382 accounts = mUsers.get(userId);
1383 mUsers.remove(userId);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001384 mLocalUnlockedUsers.delete(userId);
Amith Yamasani13593602012-03-22 16:16:17 -07001385 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001386 if (accounts != null) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001387 synchronized (accounts.dbLock) {
1388 synchronized (accounts.cacheLock) {
Fyodor Kupolov56e158f2017-05-23 16:41:51 -07001389 accounts.statementForLogging.close();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001390 accounts.accountsDb.close();
1391 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001392 }
Amith Yamasani13593602012-03-22 16:16:17 -07001393 }
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001394 }
1395
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07001396 @VisibleForTesting
1397 void onUserUnlocked(Intent intent) {
Jeff Sharkey1cab76a2016-04-12 18:23:31 -06001398 onUnlockUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1));
1399 }
1400
1401 void onUnlockUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001402 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1403 Log.v(TAG, "onUserUnlocked " + userId);
1404 }
1405 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001406 mLocalUnlockedUsers.put(userId, true);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001407 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001408 if (userId < 1) return;
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001409 syncSharedAccounts(userId);
1410 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001411
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001412 private void syncSharedAccounts(int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001413 // Check if there's a shared account that needs to be created as an account
1414 Account[] sharedAccounts = getSharedAccountsAsUser(userId);
1415 if (sharedAccounts == null || sharedAccounts.length == 0) return;
Svetoslavf3f02ac2015-09-08 14:36:35 -07001416 Account[] accounts = getAccountsAsUser(null, userId, mContext.getOpPackageName());
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001417 int parentUserId = UserManager.isSplitSystemUser()
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07001418 ? getUserManager().getUserInfo(userId).restrictedProfileParentId
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001419 : UserHandle.USER_SYSTEM;
1420 if (parentUserId < 0) {
1421 Log.w(TAG, "User " + userId + " has shared accounts, but no parent user");
1422 return;
1423 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001424 for (Account sa : sharedAccounts) {
1425 if (ArrayUtils.contains(accounts, sa)) continue;
1426 // Account doesn't exist. Copy it now.
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001427 copyAccountToUser(null /*no response*/, sa, parentUserId, userId);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001428 }
1429 }
1430
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001431 @Override
1432 public void onServiceChanged(AuthenticatorDescription desc, int userId, boolean removed) {
Jeff Sharkey6eb96202012-10-10 13:13:54 -07001433 validateAccountsInternal(getUserAccounts(userId), false /* invalidateAuthenticatorCache */);
Fred Quintana60307342009-03-24 22:48:12 -07001434 }
1435
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001436 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07001437 public String getPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001438 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001439 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1440 Log.v(TAG, "getPassword: " + account
1441 + ", caller's uid " + Binder.getCallingUid()
1442 + ", pid " + Binder.getCallingPid());
1443 }
Fred Quintana382601f2010-03-25 12:25:10 -07001444 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001445 int userId = UserHandle.getCallingUserId();
1446 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001447 String msg = String.format(
1448 "uid %s cannot get secrets for accounts of type: %s",
1449 callingUid,
1450 account.type);
1451 throw new SecurityException(msg);
1452 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001453 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07001454 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001455 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001456 return readPasswordInternal(accounts, account);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001457 } finally {
1458 restoreCallingIdentity(identityToken);
1459 }
1460 }
1461
Amith Yamasani04e0d262012-02-14 11:50:53 -08001462 private String readPasswordInternal(UserAccounts accounts, Account account) {
Fred Quintana31957f12009-10-21 13:43:10 -07001463 if (account == null) {
1464 return null;
1465 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001466 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001467 Log.w(TAG, "Password is not available - user " + accounts.userId + " data is locked");
1468 return null;
1469 }
Fred Quintana31957f12009-10-21 13:43:10 -07001470
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001471 synchronized (accounts.dbLock) {
1472 synchronized (accounts.cacheLock) {
1473 return accounts.accountsDb
1474 .findAccountPasswordByNameAndType(account.name, account.type);
1475 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001476 }
1477 }
1478
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001479 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001480 public String getPreviousName(Account account) {
1481 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1482 Log.v(TAG, "getPreviousName: " + account
1483 + ", caller's uid " + Binder.getCallingUid()
1484 + ", pid " + Binder.getCallingPid());
1485 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001486 Preconditions.checkNotNull(account, "account cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001487 int userId = UserHandle.getCallingUserId();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001488 long identityToken = clearCallingIdentity();
1489 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001490 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001491 return readPreviousNameInternal(accounts, account);
1492 } finally {
1493 restoreCallingIdentity(identityToken);
1494 }
1495 }
1496
1497 private String readPreviousNameInternal(UserAccounts accounts, Account account) {
1498 if (account == null) {
1499 return null;
1500 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001501 synchronized (accounts.dbLock) {
1502 synchronized (accounts.cacheLock) {
1503 AtomicReference<String> previousNameRef = accounts.previousNameCache.get(account);
1504 if (previousNameRef == null) {
1505 String previousName = accounts.accountsDb.findDeAccountPreviousName(account);
1506 previousNameRef = new AtomicReference<>(previousName);
1507 accounts.previousNameCache.put(account, previousNameRef);
1508 return previousName;
1509 } else {
1510 return previousNameRef.get();
1511 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001512 }
1513 }
1514 }
1515
1516 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001517 public String getUserData(Account account, String key) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001518 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001519 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001520 String msg = String.format("getUserData( account: %s, key: %s, callerUid: %s, pid: %s",
1521 account, key, callingUid, Binder.getCallingPid());
1522 Log.v(TAG, msg);
Fred Quintana56285a62010-12-02 14:20:51 -08001523 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001524 Preconditions.checkNotNull(account, "account cannot be null");
1525 Preconditions.checkNotNull(key, "key cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001526 int userId = UserHandle.getCallingUserId();
1527 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001528 String msg = String.format(
1529 "uid %s cannot get user data for accounts of type: %s",
1530 callingUid,
1531 account.type);
1532 throw new SecurityException(msg);
1533 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001534 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07001535 Log.w(TAG, "User " + userId + " data is locked. callingUid " + callingUid);
1536 return null;
1537 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001538 long identityToken = clearCallingIdentity();
1539 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001540 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001541 if (!accountExistsCache(accounts, account)) {
1542 return null;
Simranjit Kohli858511c2016-03-10 18:36:11 +00001543 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07001544 return readUserDataInternal(accounts, account, key);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001545 } finally {
1546 restoreCallingIdentity(identityToken);
1547 }
1548 }
1549
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001550 @Override
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001551 public AuthenticatorDescription[] getAuthenticatorTypes(int userId) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001552 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08001553 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1554 Log.v(TAG, "getAuthenticatorTypes: "
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001555 + "for user id " + userId
Fyodor Kupolov35f68082016-04-06 12:14:17 -07001556 + " caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001557 + ", pid " + Binder.getCallingPid());
1558 }
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001559 // Only allow the system process to read accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001560 if (isCrossUser(callingUid, userId)) {
1561 throw new SecurityException(
1562 String.format(
1563 "User %s tying to get authenticator types for %s" ,
1564 UserHandle.getCallingUserId(),
1565 userId));
1566 }
1567
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07001568 final long identityToken = clearCallingIdentity();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001569 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001570 return getAuthenticatorTypesInternal(userId);
1571
Fred Quintana26fc5eb2009-04-09 15:05:50 -07001572 } finally {
1573 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07001574 }
Fred Quintanaa698f422009-04-08 19:14:54 -07001575 }
1576
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001577 /**
1578 * Should only be called inside of a clearCallingIdentity block.
1579 */
1580 private AuthenticatorDescription[] getAuthenticatorTypesInternal(int userId) {
Fyodor Kupolov81446482016-08-24 11:27:49 -07001581 mAuthenticatorCache.updateServices(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001582 Collection<AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription>>
1583 authenticatorCollection = mAuthenticatorCache.getAllServices(userId);
1584 AuthenticatorDescription[] types =
1585 new AuthenticatorDescription[authenticatorCollection.size()];
1586 int i = 0;
1587 for (AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticator
1588 : authenticatorCollection) {
1589 types[i] = authenticator.type;
1590 i++;
1591 }
1592 return types;
1593 }
1594
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001595 private boolean isCrossUser(int callingUid, int userId) {
1596 return (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001597 && callingUid != Process.SYSTEM_UID
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001598 && mContext.checkCallingOrSelfPermission(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001599 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1600 != PackageManager.PERMISSION_GRANTED);
Alexandra Gherghinac1cf1612014-06-05 10:49:14 +01001601 }
1602
Jatin Lodhia3df7d692013-03-27 10:57:23 -07001603 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07001604 public boolean addAccountExplicitly(Account account, String password, Bundle extras) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001605 return addAccountExplicitlyWithVisibility(account, password, extras, null);
Fred Quintana60307342009-03-24 22:48:12 -07001606 }
1607
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001608 @Override
1609 public void copyAccountToUser(final IAccountManagerResponse response, final Account account,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001610 final int userFrom, int userTo) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001611 int callingUid = Binder.getCallingUid();
1612 if (isCrossUser(callingUid, UserHandle.USER_ALL)) {
1613 throw new SecurityException("Calling copyAccountToUser requires "
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001614 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001615 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001616 final UserAccounts fromAccounts = getUserAccounts(userFrom);
1617 final UserAccounts toAccounts = getUserAccounts(userTo);
1618 if (fromAccounts == null || toAccounts == null) {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001619 if (response != null) {
1620 Bundle result = new Bundle();
1621 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
1622 try {
1623 response.onResult(result);
1624 } catch (RemoteException e) {
1625 Slog.w(TAG, "Failed to report error back to the client." + e);
1626 }
1627 }
1628 return;
Amith Yamasani67df64b2012-12-14 12:09:36 -08001629 }
1630
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001631 Slog.d(TAG, "Copying account " + account.name
1632 + " from user " + userFrom + " to user " + userTo);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001633 long identityToken = clearCallingIdentity();
1634 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001635 new Session(fromAccounts, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001636 false /* stripAuthTokenFromResult */, account.name,
1637 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001638 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001639 protected String toDebugString(long now) {
1640 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1641 + ", " + account.type;
1642 }
1643
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001644 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001645 public void run() throws RemoteException {
1646 mAuthenticator.getAccountCredentialsForCloning(this, account);
1647 }
1648
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001649 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001650 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001651 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001652 if (result != null
1653 && result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
1654 // Create a Session for the target user and pass in the bundle
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001655 completeCloningAccount(response, result, account, toAccounts, userFrom);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001656 } else {
Amith Yamasani67df64b2012-12-14 12:09:36 -08001657 super.onResult(result);
1658 }
1659 }
1660 }.bind();
1661 } finally {
1662 restoreCallingIdentity(identityToken);
1663 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001664 }
1665
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001666 @Override
1667 public boolean accountAuthenticated(final Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001668 final int callingUid = Binder.getCallingUid();
1669 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1670 String msg = String.format(
1671 "accountAuthenticated( account: %s, callerUid: %s)",
1672 account,
1673 callingUid);
1674 Log.v(TAG, msg);
1675 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001676 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001677 int userId = UserHandle.getCallingUserId();
1678 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001679 String msg = String.format(
1680 "uid %s cannot notify authentication for accounts of type: %s",
1681 callingUid,
1682 account.type);
1683 throw new SecurityException(msg);
1684 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001685
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00001686 if (!canUserModifyAccounts(userId, callingUid) ||
1687 !canUserModifyAccountsForType(userId, account.type, callingUid)) {
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001688 return false;
1689 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001690
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001691 long identityToken = clearCallingIdentity();
1692 try {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001693 UserAccounts accounts = getUserAccounts(userId);
1694 return updateLastAuthenticatedTime(account);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001695 } finally {
1696 restoreCallingIdentity(identityToken);
1697 }
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07001698 }
1699
1700 private boolean updateLastAuthenticatedTime(Account account) {
1701 final UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001702 synchronized (accounts.dbLock) {
1703 synchronized (accounts.cacheLock) {
1704 return accounts.accountsDb.updateAccountLastAuthenticatedTime(account);
1705 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001706 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001707 }
1708
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001709 private void completeCloningAccount(IAccountManagerResponse response,
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001710 final Bundle accountCredentials, final Account account, final UserAccounts targetUser,
1711 final int parentUserId){
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001712 Bundle.setDefusable(accountCredentials, true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001713 long id = clearCallingIdentity();
1714 try {
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001715 new Session(targetUser, response, account.type, false,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001716 false /* stripAuthTokenFromResult */, account.name,
1717 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001718 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001719 protected String toDebugString(long now) {
1720 return super.toDebugString(now) + ", getAccountCredentialsForClone"
1721 + ", " + account.type;
1722 }
1723
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001724 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001725 public void run() throws RemoteException {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001726 // Confirm that the owner's account still exists before this step.
Fyodor Kupolov16bedd42017-03-30 10:00:49 -07001727 for (Account acc : getAccounts(parentUserId, mContext.getOpPackageName())) {
1728 if (acc.equals(account)) {
1729 mAuthenticator.addAccountFromCredentials(
1730 this, account, accountCredentials);
1731 break;
Amith Yamasani5be347b2013-03-31 17:44:31 -07001732 }
1733 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08001734 }
1735
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001736 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001737 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001738 Bundle.setDefusable(result, true);
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001739 // TODO: Anything to do if if succedded?
1740 // TODO: If it failed: Show error notification? Should we remove the shadow
1741 // account to avoid retries?
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001742 // TODO: what we do with the visibility?
1743
Esteban Talavera22dc3b72014-10-31 15:41:12 +00001744 super.onResult(result);
Amith Yamasani67df64b2012-12-14 12:09:36 -08001745 }
1746
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001747 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08001748 public void onError(int errorCode, String errorMessage) {
1749 super.onError(errorCode, errorMessage);
1750 // TODO: Show error notification to user
1751 // TODO: Should we remove the shadow account so that it doesn't keep trying?
1752 }
1753
1754 }.bind();
1755 } finally {
1756 restoreCallingIdentity(id);
1757 }
1758 }
1759
Amith Yamasani04e0d262012-02-14 11:50:53 -08001760 private boolean addAccountInternal(UserAccounts accounts, Account account, String password,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001761 Bundle extras, int callingUid, Map<String, Integer> packageToVisibility) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001762 Bundle.setDefusable(extras, true);
Fred Quintana743dfad2010-07-15 10:59:25 -07001763 if (account == null) {
1764 return false;
1765 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001766 if (!isLocalUnlockedUser(accounts.userId)) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001767 Log.w(TAG, "Account " + account + " cannot be added - user " + accounts.userId
1768 + " is locked. callingUid=" + callingUid);
1769 return false;
1770 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001771 synchronized (accounts.dbLock) {
1772 synchronized (accounts.cacheLock) {
1773 accounts.accountsDb.beginTransaction();
1774 try {
1775 if (accounts.accountsDb.findCeAccountId(account) >= 0) {
1776 Log.w(TAG, "insertAccountIntoDatabase: " + account
1777 + ", skipping since the account already exists");
1778 return false;
1779 }
1780 long accountId = accounts.accountsDb.insertCeAccount(account, password);
1781 if (accountId < 0) {
1782 Log.w(TAG, "insertAccountIntoDatabase: " + account
1783 + ", skipping the DB insert failed");
1784 return false;
1785 }
1786 // Insert into DE table
1787 if (accounts.accountsDb.insertDeAccount(account, accountId) < 0) {
1788 Log.w(TAG, "insertAccountIntoDatabase: " + account
1789 + ", skipping the DB insert failed");
1790 return false;
1791 }
1792 if (extras != null) {
1793 for (String key : extras.keySet()) {
1794 final String value = extras.getString(key);
1795 if (accounts.accountsDb.insertExtra(accountId, key, value) < 0) {
1796 Log.w(TAG, "insertAccountIntoDatabase: " + account
1797 + ", skipping since insertExtra failed for key " + key);
1798 return false;
1799 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08001800 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001801 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001802
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001803 if (packageToVisibility != null) {
1804 for (Entry<String, Integer> entry : packageToVisibility.entrySet()) {
1805 setAccountVisibility(account, entry.getKey() /* package */,
1806 entry.getValue() /* visibility */, false /* notify */,
1807 accounts);
1808 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001809 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07001810 accounts.accountsDb.setTransactionSuccessful();
1811
1812 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
1813 accountId,
1814 accounts, callingUid);
1815
1816 insertAccountIntoCacheLocked(accounts, account);
1817 } finally {
1818 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001819 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001820 }
Amith Yamasani5be347b2013-03-31 17:44:31 -07001821 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001822 if (getUserManager().getUserInfo(accounts.userId).canHaveProfile()) {
1823 addAccountToLinkedRestrictedUsers(account, accounts.userId);
Amith Yamasani5be347b2013-03-31 17:44:31 -07001824 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001825
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001826 sendNotificationAccountUpdated(account, accounts);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07001827 // Only send LOGIN_ACCOUNTS_CHANGED when the database changed.
1828 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08001829
Amith Yamasani5be347b2013-03-31 17:44:31 -07001830 return true;
1831 }
1832
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001833 private boolean isLocalUnlockedUser(int userId) {
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001834 synchronized (mUsers) {
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001835 return mLocalUnlockedUsers.get(userId);
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07001836 }
1837 }
1838
Amith Yamasani5be347b2013-03-31 17:44:31 -07001839 /**
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001840 * Adds the account to all linked restricted users as shared accounts. If the user is currently
Amith Yamasani5be347b2013-03-31 17:44:31 -07001841 * running, then clone the account too.
1842 * @param account the account to share with limited users
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001843 *
Amith Yamasani5be347b2013-03-31 17:44:31 -07001844 */
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001845 private void addAccountToLinkedRestrictedUsers(Account account, int parentUserId) {
Mita Yunf4c240e2013-04-01 21:12:43 -07001846 List<UserInfo> users = getUserManager().getUsers();
Amith Yamasani5be347b2013-03-31 17:44:31 -07001847 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07001848 if (user.isRestricted() && (parentUserId == user.restrictedProfileParentId)) {
Amith Yamasani5be347b2013-03-31 17:44:31 -07001849 addSharedAccountAsUser(account, user.id);
Jeff Sharkeyce18c812016-04-27 16:00:41 -06001850 if (isLocalUnlockedUser(user.id)) {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07001851 mHandler.sendMessage(mHandler.obtainMessage(
Fyodor Kupolov041232a2016-02-22 15:01:45 -08001852 MESSAGE_COPY_SHARED_ACCOUNT, parentUserId, user.id, account));
Amith Yamasani5be347b2013-03-31 17:44:31 -07001853 }
1854 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07001855 }
1856 }
1857
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001858 @Override
Fred Quintana3084a6f2010-01-14 18:02:03 -08001859 public void hasFeatures(IAccountManagerResponse response,
Svetoslavf3f02ac2015-09-08 14:36:35 -07001860 Account account, String[] features, String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001861 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08001862 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08001863 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1864 Log.v(TAG, "hasFeatures: " + account
1865 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07001866 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001867 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08001868 + ", pid " + Binder.getCallingPid());
1869 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07001870 Preconditions.checkArgument(account != null, "account cannot be null");
1871 Preconditions.checkArgument(response != null, "response cannot be null");
1872 Preconditions.checkArgument(features != null, "features cannot be null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001873 int userId = UserHandle.getCallingUserId();
Svetoslavf3f02ac2015-09-08 14:36:35 -07001874 checkReadAccountsPermitted(callingUid, account.type, userId,
1875 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001876
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001877 long identityToken = clearCallingIdentity();
1878 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001879 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001880 new TestFeaturesSession(accounts, response, account, features).bind();
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001881 } finally {
1882 restoreCallingIdentity(identityToken);
1883 }
1884 }
1885
1886 private class TestFeaturesSession extends Session {
1887 private final String[] mFeatures;
1888 private final Account mAccount;
1889
Amith Yamasani04e0d262012-02-14 11:50:53 -08001890 public TestFeaturesSession(UserAccounts accounts, IAccountManagerResponse response,
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001891 Account account, String[] features) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001892 super(accounts, response, account.type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08001893 true /* stripAuthTokenFromResult */, account.name,
1894 false /* authDetailsRequired */);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001895 mFeatures = features;
1896 mAccount = account;
1897 }
1898
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001899 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001900 public void run() throws RemoteException {
1901 try {
1902 mAuthenticator.hasFeatures(this, mAccount, mFeatures);
1903 } catch (RemoteException e) {
1904 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
1905 }
1906 }
1907
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001908 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001909 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06001910 Bundle.setDefusable(result, true);
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001911 IAccountManagerResponse response = getResponseAndClose();
1912 if (response != null) {
1913 try {
1914 if (result == null) {
Fred Quintana166466d2011-10-24 14:51:40 -07001915 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001916 return;
1917 }
Fred Quintana56285a62010-12-02 14:20:51 -08001918 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1919 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
1920 + response);
1921 }
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001922 final Bundle newResult = new Bundle();
1923 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
1924 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
1925 response.onResult(newResult);
1926 } catch (RemoteException e) {
1927 // if the caller is dead then there is no one to care about remote exceptions
1928 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1929 Log.v(TAG, "failure while notifying response", e);
1930 }
1931 }
1932 }
1933 }
1934
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07001935 @Override
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001936 protected String toDebugString(long now) {
Fred Quintana3084a6f2010-01-14 18:02:03 -08001937 return super.toDebugString(now) + ", hasFeatures"
Fred Quintanabb68a4f2010-01-13 17:28:39 -08001938 + ", " + mAccount
1939 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
1940 }
1941 }
Fred Quintana307da1a2010-01-21 14:24:20 -08001942
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08001943 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001944 public void renameAccount(
1945 IAccountManagerResponse response, Account accountToRename, String newName) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001946 final int callingUid = Binder.getCallingUid();
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001947 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1948 Log.v(TAG, "renameAccount: " + accountToRename + " -> " + newName
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001949 + ", caller's uid " + callingUid
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001950 + ", pid " + Binder.getCallingPid());
1951 }
1952 if (accountToRename == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00001953 int userId = UserHandle.getCallingUserId();
1954 if (!isAccountManagedByCaller(accountToRename.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07001955 String msg = String.format(
1956 "uid %s cannot rename accounts of type: %s",
1957 callingUid,
1958 accountToRename.type);
1959 throw new SecurityException(msg);
1960 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001961 long identityToken = clearCallingIdentity();
1962 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07001963 UserAccounts accounts = getUserAccounts(userId);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001964 Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001965 Bundle result = new Bundle();
1966 result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
1967 result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07001968 result.putString(AccountManager.KEY_ACCOUNT_ACCESS_ID,
1969 resultingAccount.getAccessId());
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001970 try {
1971 response.onResult(result);
1972 } catch (RemoteException e) {
1973 Log.w(TAG, e.getMessage());
1974 }
1975 } finally {
1976 restoreCallingIdentity(identityToken);
1977 }
1978 }
1979
1980 private Account renameAccountInternal(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07001981 UserAccounts accounts, Account accountToRename, String newName) {
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001982 Account resultAccount = null;
1983 /*
1984 * Cancel existing notifications. Let authenticators
1985 * re-post notifications as required. But we don't know if
1986 * the authenticators have bound their notifications to
1987 * now stale account name data.
1988 *
1989 * With a rename api, we might not need to do this anymore but it
1990 * shouldn't hurt.
1991 */
1992 cancelNotification(
1993 getSigninRequiredNotificationId(accounts, accountToRename),
Chris Wren717a8812017-03-31 15:34:39 -04001994 new UserHandle(accounts.userId));
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07001995 synchronized(accounts.credentialsPermissionNotificationIds) {
1996 for (Pair<Pair<Account, String>, Integer> pair:
1997 accounts.credentialsPermissionNotificationIds.keySet()) {
1998 if (accountToRename.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04001999 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002000 cancelNotification(id, new UserHandle(accounts.userId));
2001 }
2002 }
2003 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002004 synchronized (accounts.dbLock) {
2005 synchronized (accounts.cacheLock) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002006 List<String> accountRemovedReceivers =
2007 getAccountRemovedReceivers(accountToRename, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002008 accounts.accountsDb.beginTransaction();
2009 Account renamedAccount = new Account(newName, accountToRename.type);
2010 if ((accounts.accountsDb.findCeAccountId(renamedAccount) >= 0)) {
2011 Log.e(TAG, "renameAccount failed - account with new name already exists");
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002012 return null;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002013 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002014 try {
2015 final long accountId = accounts.accountsDb.findDeAccountId(accountToRename);
2016 if (accountId >= 0) {
2017 accounts.accountsDb.renameCeAccount(accountId, newName);
2018 if (accounts.accountsDb.renameDeAccount(
2019 accountId, newName, accountToRename.name)) {
2020 accounts.accountsDb.setTransactionSuccessful();
2021 } else {
2022 Log.e(TAG, "renameAccount failed");
2023 return null;
2024 }
2025 } else {
2026 Log.e(TAG, "renameAccount failed - old account does not exist");
2027 return null;
2028 }
2029 } finally {
2030 accounts.accountsDb.endTransaction();
2031 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002032 /*
2033 * Database transaction was successful. Clean up cached
2034 * data associated with the account in the user profile.
2035 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002036 renamedAccount = insertAccountIntoCacheLocked(accounts, renamedAccount);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002037 /*
2038 * Extract the data and token caches before removing the
2039 * old account to preserve the user data associated with
2040 * the account.
2041 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002042 Map<String, String> tmpData = accounts.userDataCache.get(accountToRename);
2043 Map<String, String> tmpTokens = accounts.authTokenCache.get(accountToRename);
2044 Map<String, Integer> tmpVisibility = accounts.visibilityCache.get(accountToRename);
2045 removeAccountFromCacheLocked(accounts, accountToRename);
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002046 /*
2047 * Update the cached data associated with the renamed
2048 * account.
2049 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002050 accounts.userDataCache.put(renamedAccount, tmpData);
2051 accounts.authTokenCache.put(renamedAccount, tmpTokens);
2052 accounts.visibilityCache.put(renamedAccount, tmpVisibility);
2053 accounts.previousNameCache.put(
2054 renamedAccount,
2055 new AtomicReference<>(accountToRename.name));
2056 resultAccount = renamedAccount;
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002057
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002058 int parentUserId = accounts.userId;
2059 if (canHaveProfile(parentUserId)) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002060 /*
2061 * Owner or system user account was renamed, rename the account for
2062 * those users with which the account was shared.
2063 */
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002064 List<UserInfo> users = getUserManager().getUsers(true);
2065 for (UserInfo user : users) {
2066 if (user.isRestricted()
2067 && (user.restrictedProfileParentId == parentUserId)) {
2068 renameSharedAccountAsUser(accountToRename, newName, user.id);
2069 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002070 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002071 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002072
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002073 sendNotificationAccountUpdated(resultAccount, accounts);
2074 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002075 for (String packageName : accountRemovedReceivers) {
2076 sendAccountRemovedBroadcast(accountToRename, packageName, accounts.userId);
2077 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002078 }
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002079 }
2080 return resultAccount;
2081 }
2082
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002083 private boolean canHaveProfile(final int parentUserId) {
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002084 final UserInfo userInfo = getUserManager().getUserInfo(parentUserId);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002085 return userInfo != null && userInfo.canHaveProfile();
2086 }
2087
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07002088 @Override
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002089 public void removeAccount(IAccountManagerResponse response, Account account,
2090 boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002091 removeAccountAsUser(
2092 response,
2093 account,
2094 expectActivityLaunch,
2095 UserHandle.getCallingUserId());
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002096 }
2097
2098 @Override
2099 public void removeAccountAsUser(IAccountManagerResponse response, Account account,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002100 boolean expectActivityLaunch, int userId) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002101 final int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002102 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2103 Log.v(TAG, "removeAccount: " + account
2104 + ", response " + response
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002105 + ", caller's uid " + callingUid
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002106 + ", pid " + Binder.getCallingPid()
2107 + ", for user id " + userId);
2108 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002109 Preconditions.checkArgument(account != null, "account cannot be null");
2110 Preconditions.checkArgument(response != null, "response cannot be null");
2111
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002112 // Only allow the system process to modify accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002113 if (isCrossUser(callingUid, userId)) {
2114 throw new SecurityException(
2115 String.format(
2116 "User %s tying remove account for %s" ,
2117 UserHandle.getCallingUserId(),
2118 userId));
2119 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002120 /*
2121 * Only the system or authenticator should be allowed to remove accounts for that
2122 * authenticator. This will let users remove accounts (via Settings in the system) but not
2123 * arbitrary applications (like competing authenticators).
2124 */
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002125 UserHandle user = UserHandle.of(userId);
Ian Pedowitz358e51f2016-03-15 17:08:27 +00002126 if (!isAccountManagedByCaller(account.type, callingUid, user.getIdentifier())
2127 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002128 String msg = String.format(
2129 "uid %s cannot remove accounts of type: %s",
2130 callingUid,
2131 account.type);
2132 throw new SecurityException(msg);
2133 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002134 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002135 try {
2136 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
2137 "User cannot modify accounts");
2138 } catch (RemoteException re) {
2139 }
2140 return;
2141 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00002142 if (!canUserModifyAccountsForType(userId, account.type, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002143 try {
2144 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
2145 "User cannot modify accounts of this type (policy).");
2146 } catch (RemoteException re) {
2147 }
2148 return;
2149 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002150 long identityToken = clearCallingIdentity();
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002151 UserAccounts accounts = getUserAccounts(userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01002152 cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002153 synchronized(accounts.credentialsPermissionNotificationIds) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002154 for (Pair<Pair<Account, String>, Integer> pair:
Amith Yamasani04e0d262012-02-14 11:50:53 -08002155 accounts.credentialsPermissionNotificationIds.keySet()) {
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002156 if (account.equals(pair.first.first)) {
Chris Wren717a8812017-03-31 15:34:39 -04002157 NotificationId id = accounts.credentialsPermissionNotificationIds.get(pair);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002158 cancelNotification(id, user);
Costin Manolacheec0c4f42010-11-16 09:57:28 -08002159 }
2160 }
2161 }
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002162 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002163 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002164 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2165 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002166 accountId,
2167 accounts,
2168 callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002169 try {
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002170 new RemoveAccountSession(accounts, response, account, expectActivityLaunch).bind();
2171 } finally {
2172 restoreCallingIdentity(identityToken);
2173 }
2174 }
2175
2176 @Override
2177 public boolean removeAccountExplicitly(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002178 final int callingUid = Binder.getCallingUid();
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002179 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2180 Log.v(TAG, "removeAccountExplicitly: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002181 + ", caller's uid " + callingUid
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002182 + ", pid " + Binder.getCallingPid());
2183 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002184 int userId = Binder.getCallingUserHandle().getIdentifier();
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002185 if (account == null) {
2186 /*
2187 * Null accounts should result in returning false, as per
2188 * AccountManage.addAccountExplicitly(...) java doc.
2189 */
2190 Log.e(TAG, "account is null");
2191 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002192 } else if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002193 String msg = String.format(
Brandon Weeks9e4e96d2017-08-24 15:24:16 -07002194 "uid %s cannot explicitly remove accounts of type: %s",
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002195 callingUid,
2196 account.type);
2197 throw new SecurityException(msg);
2198 }
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002199 UserAccounts accounts = getUserAccountsForCaller();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002200 final long accountId = accounts.accountsDb.findDeAccountId(account);
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002201 logRecord(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07002202 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_REMOVE,
2203 AccountsDb.TABLE_ACCOUNTS,
Dmitry Dementyeve59fc5f2016-07-08 10:46:22 -07002204 accountId,
2205 accounts,
2206 callingUid);
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002207 long identityToken = clearCallingIdentity();
2208 try {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002209 return removeAccountInternal(accounts, account, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002210 } finally {
2211 restoreCallingIdentity(identityToken);
Fred Quintanaa698f422009-04-08 19:14:54 -07002212 }
Fred Quintana60307342009-03-24 22:48:12 -07002213 }
2214
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002215 private class RemoveAccountSession extends Session {
2216 final Account mAccount;
Amith Yamasani04e0d262012-02-14 11:50:53 -08002217 public RemoveAccountSession(UserAccounts accounts, IAccountManagerResponse response,
Simranjit Singh Kohli8778f992014-11-05 21:33:55 -08002218 Account account, boolean expectActivityLaunch) {
2219 super(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002220 true /* stripAuthTokenFromResult */, account.name,
2221 false /* authDetailsRequired */);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002222 mAccount = account;
2223 }
2224
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002225 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002226 protected String toDebugString(long now) {
2227 return super.toDebugString(now) + ", removeAccount"
2228 + ", account " + mAccount;
2229 }
2230
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002231 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002232 public void run() throws RemoteException {
2233 mAuthenticator.getAccountRemovalAllowed(this, mAccount);
2234 }
2235
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002236 @Override
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002237 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002238 Bundle.setDefusable(result, true);
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002239 if (result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)
2240 && !result.containsKey(AccountManager.KEY_INTENT)) {
2241 final boolean removalAllowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002242 if (removalAllowed) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002243 removeAccountInternal(mAccounts, mAccount, getCallingUid());
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002244 }
2245 IAccountManagerResponse response = getResponseAndClose();
2246 if (response != null) {
Fred Quintana56285a62010-12-02 14:20:51 -08002247 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2248 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2249 + response);
2250 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002251 Bundle result2 = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002252 result2.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, removalAllowed);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002253 try {
2254 response.onResult(result2);
2255 } catch (RemoteException e) {
2256 // ignore
2257 }
2258 }
2259 }
2260 super.onResult(result);
2261 }
2262 }
2263
Fyodor Kupoloveeca6582016-04-08 12:14:04 -07002264 @VisibleForTesting
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002265 protected void removeAccountInternal(Account account) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002266 removeAccountInternal(getUserAccountsForCaller(), account, getCallingUid());
Amith Yamasani04e0d262012-02-14 11:50:53 -08002267 }
2268
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002269 private boolean removeAccountInternal(UserAccounts accounts, Account account, int callingUid) {
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002270 boolean isChanged = false;
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002271 boolean userUnlocked = isLocalUnlockedUser(accounts.userId);
Fyodor Kupolov35f68082016-04-06 12:14:17 -07002272 if (!userUnlocked) {
2273 Slog.i(TAG, "Removing account " + account + " while user "+ accounts.userId
2274 + " is still locked. CE data will be removed later");
2275 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002276 synchronized (accounts.dbLock) {
2277 synchronized (accounts.cacheLock) {
2278 Map<String, Integer> packagesToVisibility = getRequestingPackages(account,
2279 accounts);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002280 List<String> accountRemovedReceivers =
2281 getAccountRemovedReceivers(account, accounts);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002282 accounts.accountsDb.beginTransaction();
2283 // Set to a dummy value, this will only be used if the database
2284 // transaction succeeds.
2285 long accountId = -1;
2286 try {
2287 accountId = accounts.accountsDb.findDeAccountId(account);
2288 if (accountId >= 0) {
2289 isChanged = accounts.accountsDb.deleteDeAccount(accountId);
Fyodor Kupolov98e9e852016-12-09 14:58:05 -08002290 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002291 // always delete from CE table if CE storage is available
2292 // DE account could be removed while CE was locked
2293 if (userUnlocked) {
2294 long ceAccountId = accounts.accountsDb.findCeAccountId(account);
2295 if (ceAccountId >= 0) {
2296 accounts.accountsDb.deleteCeAccount(ceAccountId);
2297 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002298 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002299 accounts.accountsDb.setTransactionSuccessful();
2300 } finally {
2301 accounts.accountsDb.endTransaction();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002302 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002303 if (isChanged) {
2304 removeAccountFromCacheLocked(accounts, account);
2305 for (Entry<String, Integer> packageToVisibility : packagesToVisibility
2306 .entrySet()) {
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002307 if ((packageToVisibility.getValue() == AccountManager.VISIBILITY_VISIBLE)
2308 || (packageToVisibility.getValue()
2309 == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)) {
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002310 notifyPackage(packageToVisibility.getKey(), accounts);
2311 }
2312 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002313
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002314 // Only broadcast LOGIN_ACCOUNTS_CHANGED if a change occurred.
2315 sendAccountsChangedBroadcast(accounts.userId);
Dmitry Dementyevb6a7dc02017-04-18 13:43:31 -07002316 for (String packageName : accountRemovedReceivers) {
2317 sendAccountRemovedBroadcast(account, packageName, accounts.userId);
2318 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002319 String action = userUnlocked ? AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE
2320 : AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE_DE;
2321 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts);
2322 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002323 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002324 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002325 long id = Binder.clearCallingIdentity();
2326 try {
2327 int parentUserId = accounts.userId;
2328 if (canHaveProfile(parentUserId)) {
2329 // Remove from any restricted profiles that are sharing this account.
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07002330 List<UserInfo> users = getUserManager().getUsers(true);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002331 for (UserInfo user : users) {
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002332 if (user.isRestricted() && parentUserId == (user.restrictedProfileParentId)) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002333 removeSharedAccountAsUser(account, user.id, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002334 }
2335 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08002336 }
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07002337 } finally {
2338 Binder.restoreCallingIdentity(id);
Amith Yamasani67df64b2012-12-14 12:09:36 -08002339 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002340
2341 if (isChanged) {
2342 synchronized (accounts.credentialsPermissionNotificationIds) {
2343 for (Pair<Pair<Account, String>, Integer> key
2344 : accounts.credentialsPermissionNotificationIds.keySet()) {
2345 if (account.equals(key.first.first)
Svet Ganovf6d424f12016-09-20 20:18:53 -07002346 && AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE.equals(key.first.second)) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002347 final int uid = (Integer) key.second;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07002348 mHandler.post(() -> cancelAccountAccessRequestNotificationIfNeeded(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002349 account, uid, false));
2350 }
2351 }
2352 }
2353 }
2354
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002355 return isChanged;
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002356 }
2357
Maggie Benthalla12fccf2013-03-14 18:02:12 -04002358 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002359 public void invalidateAuthToken(String accountType, String authToken) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002360 int callerUid = Binder.getCallingUid();
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002361 Preconditions.checkNotNull(accountType, "accountType cannot be null");
2362 Preconditions.checkNotNull(authToken, "authToken cannot be null");
Fred Quintana56285a62010-12-02 14:20:51 -08002363 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2364 Log.v(TAG, "invalidateAuthToken: accountType " + accountType
Carlos Valdivia91979be2015-05-22 14:11:35 -07002365 + ", caller's uid " + callerUid
Fred Quintana56285a62010-12-02 14:20:51 -08002366 + ", pid " + Binder.getCallingPid());
2367 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002368 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002369 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002370 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002371 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002372 List<Pair<Account, String>> deletedTokens;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002373 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002374 accounts.accountsDb.beginTransaction();
2375 try {
2376 deletedTokens = invalidateAuthTokenLocked(accounts, accountType, authToken);
2377 accounts.accountsDb.setTransactionSuccessful();
2378 } finally {
2379 accounts.accountsDb.endTransaction();
2380 }
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002381 synchronized (accounts.cacheLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002382 for (Pair<Account, String> tokenInfo : deletedTokens) {
2383 Account act = tokenInfo.first;
2384 String tokenType = tokenInfo.second;
2385 writeAuthTokenIntoCacheLocked(accounts, act, tokenType, null);
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002386 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002387 // wipe out cached token in memory.
2388 accounts.accountTokenCaches.remove(accountType, authToken);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002389 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002390 }
Fred Quintana60307342009-03-24 22:48:12 -07002391 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002392 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002393 }
2394 }
2395
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002396 private List<Pair<Account, String>> invalidateAuthTokenLocked(UserAccounts accounts, String accountType,
Carlos Valdivia91979be2015-05-22 14:11:35 -07002397 String authToken) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002398 // TODO Move to AccountsDB
2399 List<Pair<Account, String>> results = new ArrayList<>();
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002400 Cursor cursor = accounts.accountsDb.findAuthtokenForAllAccounts(accountType, authToken);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002401
Fred Quintana33269202009-04-20 16:05:10 -07002402 try {
2403 while (cursor.moveToNext()) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07002404 String authTokenId = cursor.getString(0);
Fred Quintana33269202009-04-20 16:05:10 -07002405 String accountName = cursor.getString(1);
2406 String authTokenType = cursor.getString(2);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07002407 accounts.accountsDb.deleteAuthToken(authTokenId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002408 results.add(Pair.create(new Account(accountName, accountType), authTokenType));
Fred Quintana60307342009-03-24 22:48:12 -07002409 }
Fred Quintana33269202009-04-20 16:05:10 -07002410 } finally {
2411 cursor.close();
Fred Quintana60307342009-03-24 22:48:12 -07002412 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002413 return results;
Fred Quintana60307342009-03-24 22:48:12 -07002414 }
2415
Carlos Valdivia91979be2015-05-22 14:11:35 -07002416 private void saveCachedToken(
2417 UserAccounts accounts,
2418 Account account,
2419 String callerPkg,
2420 byte[] callerSigDigest,
2421 String tokenType,
2422 String token,
2423 long expiryMillis) {
2424
2425 if (account == null || tokenType == null || callerPkg == null || callerSigDigest == null) {
2426 return;
2427 }
2428 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002429 UserHandle.of(accounts.userId));
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002430 synchronized (accounts.cacheLock) {
2431 accounts.accountTokenCaches.put(
2432 account, token, tokenType, callerPkg, callerSigDigest, expiryMillis);
Carlos Valdivia91979be2015-05-22 14:11:35 -07002433 }
2434 }
2435
Amith Yamasani04e0d262012-02-14 11:50:53 -08002436 private boolean saveAuthTokenToDatabase(UserAccounts accounts, Account account, String type,
2437 String authToken) {
Fred Quintana31957f12009-10-21 13:43:10 -07002438 if (account == null || type == null) {
2439 return false;
2440 }
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07002441 cancelNotification(getSigninRequiredNotificationId(accounts, account),
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07002442 UserHandle.of(accounts.userId));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002443 synchronized (accounts.dbLock) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002444 accounts.accountsDb.beginTransaction();
2445 boolean updateCache = false;
2446 try {
2447 long accountId = accounts.accountsDb.findDeAccountId(account);
2448 if (accountId < 0) {
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002449 return false;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07002450 }
2451 accounts.accountsDb.deleteAuthtokensByAccountIdAndType(accountId, type);
2452 if (accounts.accountsDb.insertAuthToken(accountId, type, authToken) >= 0) {
2453 accounts.accountsDb.setTransactionSuccessful();
2454 updateCache = true;
2455 return true;
2456 }
2457 return false;
2458 } finally {
2459 accounts.accountsDb.endTransaction();
2460 if (updateCache) {
2461 synchronized (accounts.cacheLock) {
2462 writeAuthTokenIntoCacheLocked(accounts, account, type, authToken);
2463 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08002464 }
Fred Quintana33269202009-04-20 16:05:10 -07002465 }
Fred Quintana60307342009-03-24 22:48:12 -07002466 }
2467 }
2468
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002469 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002470 public String peekAuthToken(Account account, String authTokenType) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002471 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002472 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2473 Log.v(TAG, "peekAuthToken: " + account
2474 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002475 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002476 + ", pid " + Binder.getCallingPid());
2477 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002478 Preconditions.checkNotNull(account, "account cannot be null");
2479 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002480 int userId = UserHandle.getCallingUserId();
2481 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002482 String msg = String.format(
2483 "uid %s cannot peek the authtokens associated with accounts of type: %s",
2484 callingUid,
2485 account.type);
2486 throw new SecurityException(msg);
2487 }
Jeff Sharkeyce18c812016-04-27 16:00:41 -06002488 if (!isLocalUnlockedUser(userId)) {
Fyodor Kupolovc86c3fd2016-04-18 13:57:31 -07002489 Log.w(TAG, "Authtoken not available - user " + userId + " data is locked. callingUid "
2490 + callingUid);
2491 return null;
2492 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002493 long identityToken = clearCallingIdentity();
2494 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002495 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002496 return readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002497 } finally {
2498 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002499 }
Fred Quintana60307342009-03-24 22:48:12 -07002500 }
2501
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002502 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002503 public void setAuthToken(Account account, String authTokenType, String authToken) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002504 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002505 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2506 Log.v(TAG, "setAuthToken: " + account
2507 + ", authTokenType " + authTokenType
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002508 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002509 + ", pid " + Binder.getCallingPid());
2510 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002511 Preconditions.checkNotNull(account, "account cannot be null");
2512 Preconditions.checkNotNull(authTokenType, "authTokenType cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002513 int userId = UserHandle.getCallingUserId();
2514 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002515 String msg = String.format(
2516 "uid %s cannot set auth tokens associated with accounts of type: %s",
2517 callingUid,
2518 account.type);
2519 throw new SecurityException(msg);
2520 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002521 long identityToken = clearCallingIdentity();
2522 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002523 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002524 saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002525 } finally {
2526 restoreCallingIdentity(identityToken);
2527 }
Fred Quintana60307342009-03-24 22:48:12 -07002528 }
2529
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002530 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002531 public void setPassword(Account account, String password) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002532 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002533 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2534 Log.v(TAG, "setAuthToken: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002535 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002536 + ", pid " + Binder.getCallingPid());
2537 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002538 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002539 int userId = UserHandle.getCallingUserId();
2540 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002541 String msg = String.format(
2542 "uid %s cannot set secrets for accounts of type: %s",
2543 callingUid,
2544 account.type);
2545 throw new SecurityException(msg);
2546 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002547 long identityToken = clearCallingIdentity();
2548 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002549 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002550 setPasswordInternal(accounts, account, password, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002551 } finally {
2552 restoreCallingIdentity(identityToken);
2553 }
Fred Quintana60307342009-03-24 22:48:12 -07002554 }
2555
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002556 private void setPasswordInternal(UserAccounts accounts, Account account, String password,
2557 int callingUid) {
Fred Quintana31957f12009-10-21 13:43:10 -07002558 if (account == null) {
2559 return;
2560 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002561 boolean isChanged = false;
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07002562 synchronized (accounts.dbLock) {
2563 synchronized (accounts.cacheLock) {
2564 accounts.accountsDb.beginTransaction();
2565 try {
2566 final long accountId = accounts.accountsDb.findDeAccountId(account);
2567 if (accountId >= 0) {
2568 accounts.accountsDb.updateCeAccountPassword(accountId, password);
2569 accounts.accountsDb.deleteAuthTokensByAccountId(accountId);
2570 accounts.authTokenCache.remove(account);
2571 accounts.accountTokenCaches.remove(account);
2572 accounts.accountsDb.setTransactionSuccessful();
2573 // If there is an account whose password will be updated and the database
2574 // transactions succeed, then we say that a change has occured. Even if the
2575 // new password is the same as the old and there were no authtokens to
2576 // delete.
2577 isChanged = true;
2578 String action = (password == null || password.length() == 0) ?
2579 AccountsDb.DEBUG_ACTION_CLEAR_PASSWORD
2580 : AccountsDb.DEBUG_ACTION_SET_PASSWORD;
2581 logRecord(action, AccountsDb.TABLE_ACCOUNTS, accountId, accounts,
2582 callingUid);
2583 }
2584 } finally {
2585 accounts.accountsDb.endTransaction();
2586 if (isChanged) {
2587 // Send LOGIN_ACCOUNTS_CHANGED only if the something changed.
2588 sendNotificationAccountUpdated(account, accounts);
2589 sendAccountsChangedBroadcast(accounts.userId);
2590 }
Carlos Valdivia98b5f9d2016-07-07 17:47:12 -07002591 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002592 }
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08002593 }
Fred Quintana3ecd5f42009-09-17 12:42:35 -07002594 }
2595
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002596 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002597 public void clearPassword(Account account) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002598 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002599 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2600 Log.v(TAG, "clearPassword: " + account
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002601 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002602 + ", pid " + Binder.getCallingPid());
2603 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002604 Preconditions.checkNotNull(account, "account cannot be null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002605 int userId = UserHandle.getCallingUserId();
2606 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002607 String msg = String.format(
2608 "uid %s cannot clear passwords for accounts of type: %s",
2609 callingUid,
2610 account.type);
2611 throw new SecurityException(msg);
2612 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002613 long identityToken = clearCallingIdentity();
2614 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002615 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07002616 setPasswordInternal(accounts, account, null, callingUid);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002617 } finally {
2618 restoreCallingIdentity(identityToken);
2619 }
Fred Quintana60307342009-03-24 22:48:12 -07002620 }
2621
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002622 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07002623 public void setUserData(Account account, String key, String value) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002624 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08002625 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2626 Log.v(TAG, "setUserData: " + account
2627 + ", key " + key
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002628 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08002629 + ", pid " + Binder.getCallingPid());
2630 }
Fred Quintana382601f2010-03-25 12:25:10 -07002631 if (key == null) throw new IllegalArgumentException("key is null");
2632 if (account == null) throw new IllegalArgumentException("account is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002633 int userId = UserHandle.getCallingUserId();
2634 if (!isAccountManagedByCaller(account.type, callingUid, userId)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07002635 String msg = String.format(
2636 "uid %s cannot set user data for accounts of type: %s",
2637 callingUid,
2638 account.type);
2639 throw new SecurityException(msg);
2640 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002641 long identityToken = clearCallingIdentity();
Fred Quintana60307342009-03-24 22:48:12 -07002642 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002643 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002644 if (!accountExistsCache(accounts, account)) {
2645 return;
Simranjit Kohli858511c2016-03-10 18:36:11 +00002646 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002647 setUserdataInternal(accounts, account, key, value);
Fred Quintana60307342009-03-24 22:48:12 -07002648 } finally {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002649 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07002650 }
2651 }
2652
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002653 private boolean accountExistsCache(UserAccounts accounts, Account account) {
2654 synchronized (accounts.cacheLock) {
2655 if (accounts.accountCache.containsKey(account.type)) {
2656 for (Account acc : accounts.accountCache.get(account.type)) {
2657 if (acc.name.equals(account.name)) {
2658 return true;
2659 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00002660 }
2661 }
2662 }
2663 return false;
2664 }
2665
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002666 private void setUserdataInternal(UserAccounts accounts, Account account, String key,
Amith Yamasani04e0d262012-02-14 11:50:53 -08002667 String value) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002668 synchronized (accounts.dbLock) {
2669 accounts.accountsDb.beginTransaction();
2670 try {
2671 long accountId = accounts.accountsDb.findDeAccountId(account);
2672 if (accountId < 0) {
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002673 return;
2674 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002675 long extrasId = accounts.accountsDb.findExtrasIdByAccountId(accountId, key);
2676 if (extrasId < 0) {
2677 extrasId = accounts.accountsDb.insertExtra(accountId, key, value);
2678 if (extrasId < 0) {
2679 return;
2680 }
2681 } else if (!accounts.accountsDb.updateExtra(extrasId, value)) {
2682 return;
2683 }
2684 accounts.accountsDb.setTransactionSuccessful();
2685 } finally {
2686 accounts.accountsDb.endTransaction();
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002687 }
Fyodor Kupolov3d734992017-03-29 17:28:52 -07002688 synchronized (accounts.cacheLock) {
2689 writeUserDataIntoCacheLocked(accounts, account, key, value);
2690 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07002691 }
2692 }
2693
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002694 private void onResult(IAccountManagerResponse response, Bundle result) {
Fred Quintana56285a62010-12-02 14:20:51 -08002695 if (result == null) {
2696 Log.e(TAG, "the result is unexpectedly null", new Exception());
2697 }
2698 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2699 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
2700 + response);
2701 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002702 try {
2703 response.onResult(result);
2704 } catch (RemoteException e) {
2705 // if the caller is dead then there is no one to care about remote
2706 // exceptions
2707 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2708 Log.v(TAG, "failure while notifying response", e);
2709 }
2710 }
2711 }
2712
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002713 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07002714 public void getAuthTokenLabel(IAccountManagerResponse response, final String accountType,
2715 final String authTokenType)
2716 throws RemoteException {
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002717 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
2718 Preconditions.checkArgument(authTokenType != null, "authTokenType cannot be null");
Costin Manolache5f383ad92010-12-02 16:44:46 -08002719
Fred Quintanad9640ec2012-05-23 12:37:00 -07002720 final int callingUid = getCallingUid();
2721 clearCallingIdentity();
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07002722 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07002723 throw new SecurityException("can only call from system");
2724 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002725 int userId = UserHandle.getUserId(callingUid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002726 long identityToken = clearCallingIdentity();
2727 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002728 UserAccounts accounts = getUserAccounts(userId);
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002729 new Session(accounts, response, accountType, false /* expectActivityLaunch */,
2730 false /* stripAuthTokenFromResult */, null /* accountName */,
2731 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002732 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002733 protected String toDebugString(long now) {
2734 return super.toDebugString(now) + ", getAuthTokenLabel"
Fred Quintanad9640ec2012-05-23 12:37:00 -07002735 + ", " + accountType
Costin Manolache5f383ad92010-12-02 16:44:46 -08002736 + ", authTokenType " + authTokenType;
2737 }
2738
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002739 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002740 public void run() throws RemoteException {
2741 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2742 }
2743
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002744 @Override
Costin Manolache5f383ad92010-12-02 16:44:46 -08002745 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002746 Bundle.setDefusable(result, true);
Costin Manolache5f383ad92010-12-02 16:44:46 -08002747 if (result != null) {
2748 String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
2749 Bundle bundle = new Bundle();
2750 bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
2751 super.onResult(bundle);
2752 return;
2753 } else {
2754 super.onResult(result);
2755 }
2756 }
2757 }.bind();
2758 } finally {
2759 restoreCallingIdentity(identityToken);
2760 }
2761 }
2762
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002763 @Override
Carlos Valdivia91979be2015-05-22 14:11:35 -07002764 public void getAuthToken(
2765 IAccountManagerResponse response,
2766 final Account account,
2767 final String authTokenType,
2768 final boolean notifyOnAuthFailure,
2769 final boolean expectActivityLaunch,
2770 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002771 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08002772 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2773 Log.v(TAG, "getAuthToken: " + account
2774 + ", response " + response
2775 + ", authTokenType " + authTokenType
2776 + ", notifyOnAuthFailure " + notifyOnAuthFailure
2777 + ", expectActivityLaunch " + expectActivityLaunch
2778 + ", caller's uid " + Binder.getCallingUid()
2779 + ", pid " + Binder.getCallingPid());
2780 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07002781 Preconditions.checkArgument(response != null, "response cannot be null");
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08002782 try {
2783 if (account == null) {
2784 Slog.w(TAG, "getAuthToken called with null account");
2785 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "account is null");
2786 return;
2787 }
2788 if (authTokenType == null) {
2789 Slog.w(TAG, "getAuthToken called with null authTokenType");
2790 response.onError(AccountManager.ERROR_CODE_BAD_ARGUMENTS, "authTokenType is null");
2791 return;
2792 }
2793 } catch (RemoteException e) {
2794 Slog.w(TAG, "Failed to report error back to the client." + e);
2795 return;
2796 }
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002797 int userId = UserHandle.getCallingUserId();
2798 long ident = Binder.clearCallingIdentity();
2799 final UserAccounts accounts;
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002800 final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002801 try {
2802 accounts = getUserAccounts(userId);
2803 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
2804 AuthenticatorDescription.newKey(account.type), accounts.userId);
2805 } finally {
2806 Binder.restoreCallingIdentity(ident);
2807 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002808
Costin Manolachea40c6302010-12-13 14:50:45 -08002809 final boolean customTokens =
Carlos Valdivia91979be2015-05-22 14:11:35 -07002810 authenticatorInfo != null && authenticatorInfo.type.customTokens;
Costin Manolachea40c6302010-12-13 14:50:45 -08002811
2812 // skip the check if customTokens
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002813 final int callerUid = Binder.getCallingUid();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00002814 final boolean permissionGranted =
2815 customTokens || permissionIsGranted(account, authTokenType, callerUid, userId);
Costin Manolachea40c6302010-12-13 14:50:45 -08002816
Carlos Valdivia91979be2015-05-22 14:11:35 -07002817 // Get the calling package. We will use it for the purpose of caching.
2818 final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
Amith Yamasanie7360012015-06-03 17:39:40 -07002819 List<String> callerOwnedPackageNames;
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07002820 ident = Binder.clearCallingIdentity();
Amith Yamasanie7360012015-06-03 17:39:40 -07002821 try {
2822 callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
2823 } finally {
2824 Binder.restoreCallingIdentity(ident);
2825 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002826 if (callerPkg == null || !callerOwnedPackageNames.contains(callerPkg)) {
2827 String msg = String.format(
2828 "Uid %s is attempting to illegally masquerade as package %s!",
2829 callerUid,
2830 callerPkg);
2831 throw new SecurityException(msg);
2832 }
2833
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002834 // let authenticator know the identity of the caller
2835 loginOptions.putInt(AccountManager.KEY_CALLER_UID, callerUid);
2836 loginOptions.putInt(AccountManager.KEY_CALLER_PID, Binder.getCallingPid());
Carlos Valdivia91979be2015-05-22 14:11:35 -07002837
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07002838 if (notifyOnAuthFailure) {
2839 loginOptions.putBoolean(AccountManager.KEY_NOTIFY_ON_FAILURE, true);
Costin Manolachea40c6302010-12-13 14:50:45 -08002840 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07002841
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002842 long identityToken = clearCallingIdentity();
2843 try {
Amith Yamasanie7360012015-06-03 17:39:40 -07002844 // Distill the caller's package signatures into a single digest.
2845 final byte[] callerPkgSigDigest = calculatePackageSignatureDigest(callerPkg);
2846
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002847 // if the caller has permission, do the peek. otherwise go the more expensive
2848 // route of starting a Session
Costin Manolachea40c6302010-12-13 14:50:45 -08002849 if (!customTokens && permissionGranted) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002850 String authToken = readAuthTokenInternal(accounts, account, authTokenType);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002851 if (authToken != null) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002852 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002853 result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
2854 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2855 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002856 onResult(response, result);
2857 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07002858 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002859 }
2860
Carlos Valdivia91979be2015-05-22 14:11:35 -07002861 if (customTokens) {
2862 /*
2863 * Look up tokens in the new cache only if the loginOptions don't have parameters
2864 * outside of those expected to be injected by the AccountManager, e.g.
2865 * ANDORID_PACKAGE_NAME.
2866 */
2867 String token = readCachedTokenInternal(
2868 accounts,
2869 account,
2870 authTokenType,
2871 callerPkg,
2872 callerPkgSigDigest);
2873 if (token != null) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002874 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2875 Log.v(TAG, "getAuthToken: cache hit ofr custom token authenticator.");
2876 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002877 Bundle result = new Bundle();
2878 result.putString(AccountManager.KEY_AUTHTOKEN, token);
2879 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
2880 result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
2881 onResult(response, result);
2882 return;
2883 }
2884 }
2885
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002886 new Session(
2887 accounts,
2888 response,
2889 account.type,
2890 expectActivityLaunch,
2891 false /* stripAuthTokenFromResult */,
2892 account.name,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08002893 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002894 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002895 protected String toDebugString(long now) {
2896 if (loginOptions != null) loginOptions.keySet();
2897 return super.toDebugString(now) + ", getAuthToken"
2898 + ", " + account
2899 + ", authTokenType " + authTokenType
2900 + ", loginOptions " + loginOptions
2901 + ", notifyOnAuthFailure " + notifyOnAuthFailure;
2902 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002903
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002904 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002905 public void run() throws RemoteException {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002906 // If the caller doesn't have permission then create and return the
2907 // "grant permission" intent instead of the "getAuthToken" intent.
2908 if (!permissionGranted) {
2909 mAuthenticator.getAuthTokenLabel(this, authTokenType);
2910 } else {
2911 mAuthenticator.getAuthToken(this, account, authTokenType, loginOptions);
2912 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002913 }
2914
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07002915 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002916 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06002917 Bundle.setDefusable(result, true);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002918 if (result != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002919 if (result.containsKey(AccountManager.KEY_AUTH_TOKEN_LABEL)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002920 Intent intent = newGrantCredentialsPermissionIntent(
2921 account,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002922 null,
Carlos Valdiviac37ee222015-06-17 20:17:37 -07002923 callerUid,
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002924 new AccountAuthenticatorResponse(this),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002925 authTokenType,
2926 true);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002927 Bundle bundle = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002928 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07002929 onResult(bundle);
2930 return;
2931 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002932 String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002933 if (authToken != null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002934 String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2935 String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002936 if (TextUtils.isEmpty(type) || TextUtils.isEmpty(name)) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002937 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002938 "the type and name should not be empty");
2939 return;
2940 }
Carlos Valdivia91979be2015-05-22 14:11:35 -07002941 Account resultAccount = new Account(name, type);
Costin Manolachea40c6302010-12-13 14:50:45 -08002942 if (!customTokens) {
Carlos Valdivia91979be2015-05-22 14:11:35 -07002943 saveAuthTokenToDatabase(
2944 mAccounts,
2945 resultAccount,
2946 authTokenType,
2947 authToken);
2948 }
2949 long expiryMillis = result.getLong(
2950 AbstractAccountAuthenticator.KEY_CUSTOM_TOKEN_EXPIRY, 0L);
2951 if (customTokens
2952 && expiryMillis > System.currentTimeMillis()) {
2953 saveCachedToken(
2954 mAccounts,
2955 account,
2956 callerPkg,
2957 callerPkgSigDigest,
2958 authTokenType,
2959 authToken,
2960 expiryMillis);
Costin Manolachea40c6302010-12-13 14:50:45 -08002961 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002962 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002963
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07002964 Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
Costin Manolached6060452011-01-24 16:11:36 -08002965 if (intent != null && notifyOnAuthFailure && !customTokens) {
Carlos Valdivia06329e5f2016-05-07 21:46:15 -07002966 /*
2967 * Make sure that the supplied intent is owned by the authenticator
2968 * giving it to the system. Otherwise a malicious authenticator could
2969 * have users launching arbitrary activities by tricking users to
2970 * interact with malicious notifications.
2971 */
2972 checkKeyIntent(
2973 Binder.getCallingUid(),
2974 intent);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08002975 doNotification(
2976 mAccounts,
2977 account,
2978 result.getString(AccountManager.KEY_AUTH_FAILED_MESSAGE),
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07002979 intent, "android", accounts.userId);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002980 }
Fred Quintanaa698f422009-04-08 19:14:54 -07002981 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002982 super.onResult(result);
Fred Quintanaa698f422009-04-08 19:14:54 -07002983 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07002984 }.bind();
2985 } finally {
2986 restoreCallingIdentity(identityToken);
2987 }
Fred Quintana60307342009-03-24 22:48:12 -07002988 }
2989
Carlos Valdivia91979be2015-05-22 14:11:35 -07002990 private byte[] calculatePackageSignatureDigest(String callerPkg) {
2991 MessageDigest digester;
2992 try {
2993 digester = MessageDigest.getInstance("SHA-256");
2994 PackageInfo pkgInfo = mPackageManager.getPackageInfo(
2995 callerPkg, PackageManager.GET_SIGNATURES);
2996 for (Signature sig : pkgInfo.signatures) {
2997 digester.update(sig.toByteArray());
2998 }
2999 } catch (NoSuchAlgorithmException x) {
3000 Log.wtf(TAG, "SHA-256 should be available", x);
3001 digester = null;
3002 } catch (NameNotFoundException e) {
3003 Log.w(TAG, "Could not find packageinfo for: " + callerPkg);
3004 digester = null;
3005 }
3006 return (digester == null) ? null : digester.digest();
3007 }
3008
Dianne Hackborn41203752012-08-31 14:05:51 -07003009 private void createNoCredentialsPermissionNotification(Account account, Intent intent,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003010 String packageName, int userId) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003011 int uid = intent.getIntExtra(
3012 GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, -1);
3013 String authTokenType = intent.getStringExtra(
3014 GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE);
Eric Fischeree452ee2009-08-31 17:58:06 -07003015 final String titleAndSubtitle =
3016 mContext.getString(R.string.permission_request_notification_with_subtitle,
3017 account.name);
3018 final int index = titleAndSubtitle.indexOf('\n');
Costin Manolache85e72792011-10-07 09:42:49 -07003019 String title = titleAndSubtitle;
3020 String subtitle = "";
3021 if (index > 0) {
3022 title = titleAndSubtitle.substring(0, index);
Maggie Benthalla12fccf2013-03-14 18:02:12 -04003023 subtitle = titleAndSubtitle.substring(index + 1);
Costin Manolache85e72792011-10-07 09:42:49 -07003024 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07003025 UserHandle user = UserHandle.of(userId);
Kenny Guy07ad8dc2014-09-01 20:56:12 +01003026 Context contextForUser = getContextForUser(user);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05003027 Notification n =
3028 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
3029 .setSmallIcon(android.R.drawable.stat_sys_warning)
3030 .setWhen(0)
3031 .setColor(contextForUser.getColor(
3032 com.android.internal.R.color.system_notification_accent_color))
3033 .setContentTitle(title)
3034 .setContentText(subtitle)
3035 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, intent,
3036 PendingIntent.FLAG_CANCEL_CURRENT, null, user))
3037 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07003038 installNotification(getCredentialPermissionNotificationId(
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003039 account, authTokenType, uid), n, packageName, user.getIdentifier());
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003040 }
3041
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003042 private Intent newGrantCredentialsPermissionIntent(Account account, String packageName,
3043 int uid, AccountAuthenticatorResponse response, String authTokenType,
3044 boolean startInNewTask) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003045
3046 Intent intent = new Intent(mContext, GrantCredentialsPermissionActivity.class);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003047
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003048 if (startInNewTask) {
3049 // See FLAG_ACTIVITY_NEW_TASK docs for limitations and benefits of the flag.
3050 // Since it was set in Eclair+ we can't change it without breaking apps using
3051 // the intent from a non-Activity context. This is the default behavior.
3052 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3053 }
Chris Wren717a8812017-03-31 15:34:39 -04003054 intent.addCategory(getCredentialPermissionNotificationId(account,
3055 authTokenType, uid).mTag + (packageName != null ? packageName : ""));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003056 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_ACCOUNT, account);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003057 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_AUTH_TOKEN_TYPE, authTokenType);
3058 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_RESPONSE, response);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003059 intent.putExtra(GrantCredentialsPermissionActivity.EXTRAS_REQUESTING_UID, uid);
Costin Manolache5f383ad92010-12-02 16:44:46 -08003060
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003061 return intent;
3062 }
3063
Chris Wren717a8812017-03-31 15:34:39 -04003064 private NotificationId getCredentialPermissionNotificationId(Account account,
3065 String authTokenType, int uid) {
3066 NotificationId nId;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003067 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Amith Yamasani04e0d262012-02-14 11:50:53 -08003068 synchronized (accounts.credentialsPermissionNotificationIds) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003069 final Pair<Pair<Account, String>, Integer> key =
3070 new Pair<Pair<Account, String>, Integer>(
3071 new Pair<Account, String>(account, authTokenType), uid);
Chris Wren717a8812017-03-31 15:34:39 -04003072 nId = accounts.credentialsPermissionNotificationIds.get(key);
3073 if (nId == null) {
3074 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION
3075 + ":" + account.hashCode() + ":" + authTokenType.hashCode();
3076 int id = SystemMessage.NOTE_ACCOUNT_CREDENTIAL_PERMISSION;
3077 nId = new NotificationId(tag, id);
3078 accounts.credentialsPermissionNotificationIds.put(key, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003079 }
3080 }
Chris Wren717a8812017-03-31 15:34:39 -04003081 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003082 }
3083
Chris Wren717a8812017-03-31 15:34:39 -04003084 private NotificationId getSigninRequiredNotificationId(UserAccounts accounts, Account account) {
3085 NotificationId nId;
Amith Yamasani04e0d262012-02-14 11:50:53 -08003086 synchronized (accounts.signinRequiredNotificationIds) {
Chris Wren717a8812017-03-31 15:34:39 -04003087 nId = accounts.signinRequiredNotificationIds.get(account);
3088 if (nId == null) {
3089 String tag = TAG + ":" + SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN
3090 + ":" + account.hashCode();
3091 int id = SystemMessage.NOTE_ACCOUNT_REQUIRE_SIGNIN;
3092 nId = new NotificationId(tag, id);
3093 accounts.signinRequiredNotificationIds.put(account, nId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003094 }
3095 }
Chris Wren717a8812017-03-31 15:34:39 -04003096 return nId;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07003097 }
3098
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003099 @Override
Amith Yamasani27db4682013-03-30 17:07:47 -07003100 public void addAccount(final IAccountManagerResponse response, final String accountType,
Fred Quintana33269202009-04-20 16:05:10 -07003101 final String authTokenType, final String[] requiredFeatures,
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003102 final boolean expectActivityLaunch, final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003103 Bundle.setDefusable(optionsIn, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003104 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3105 Log.v(TAG, "addAccount: accountType " + accountType
3106 + ", response " + response
3107 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003108 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Fred Quintana56285a62010-12-02 14:20:51 -08003109 + ", expectActivityLaunch " + expectActivityLaunch
3110 + ", caller's uid " + Binder.getCallingUid()
3111 + ", pid " + Binder.getCallingPid());
3112 }
Fred Quintana382601f2010-03-25 12:25:10 -07003113 if (response == null) throw new IllegalArgumentException("response is null");
3114 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003115
Amith Yamasani71e6c692013-03-24 17:39:28 -07003116 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003117 final int uid = Binder.getCallingUid();
3118 final int userId = UserHandle.getUserId(uid);
3119 if (!canUserModifyAccounts(userId, uid)) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003120 try {
3121 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3122 "User is not allowed to add an account!");
3123 } catch (RemoteException re) {
3124 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003125 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003126 return;
3127 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003128 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003129 try {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003130 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3131 "User cannot modify accounts of this type (policy).");
3132 } catch (RemoteException re) {
Amith Yamasani23c8b962013-04-10 13:37:18 -07003133 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003134 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3135 userId);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08003136 return;
3137 }
3138
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003139 final int pid = Binder.getCallingPid();
Costin Manolacheb61e8fb2011-09-08 11:26:09 -07003140 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3141 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3142 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3143
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003144 int usrId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003145 long identityToken = clearCallingIdentity();
3146 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003147 UserAccounts accounts = getUserAccounts(usrId);
3148 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003149 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3150 uid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003151 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003152 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003153 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003154 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003155 public void run() throws RemoteException {
Costin Manolache3348f142009-09-29 18:58:36 -07003156 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
Fred Quintana33269202009-04-20 16:05:10 -07003157 options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003158 }
Fred Quintanaa698f422009-04-08 19:14:54 -07003159
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003160 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003161 protected String toDebugString(long now) {
3162 return super.toDebugString(now) + ", addAccount"
Fred Quintana33269202009-04-20 16:05:10 -07003163 + ", accountType " + accountType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003164 + ", requiredFeatures " + Arrays.toString(requiredFeatures);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003165 }
3166 }.bind();
3167 } finally {
3168 restoreCallingIdentity(identityToken);
3169 }
Fred Quintana60307342009-03-24 22:48:12 -07003170 }
3171
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003172 @Override
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003173 public void addAccountAsUser(final IAccountManagerResponse response, final String accountType,
3174 final String authTokenType, final String[] requiredFeatures,
3175 final boolean expectActivityLaunch, final Bundle optionsIn, int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003176 Bundle.setDefusable(optionsIn, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003177 int callingUid = Binder.getCallingUid();
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003178 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3179 Log.v(TAG, "addAccount: accountType " + accountType
3180 + ", response " + response
3181 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003182 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003183 + ", expectActivityLaunch " + expectActivityLaunch
3184 + ", caller's uid " + Binder.getCallingUid()
3185 + ", pid " + Binder.getCallingPid()
3186 + ", for user id " + userId);
3187 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003188 Preconditions.checkArgument(response != null, "response cannot be null");
3189 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003190 // Only allow the system process to add accounts of other users
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003191 if (isCrossUser(callingUid, userId)) {
3192 throw new SecurityException(
3193 String.format(
3194 "User %s trying to add account for %s" ,
3195 UserHandle.getCallingUserId(),
3196 userId));
3197 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003198
3199 // Is user disallowed from modifying accounts?
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003200 if (!canUserModifyAccounts(userId, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003201 try {
3202 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3203 "User is not allowed to add an account!");
3204 } catch (RemoteException re) {
3205 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003206 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003207 return;
3208 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003209 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003210 try {
3211 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3212 "User cannot modify accounts of this type (policy).");
3213 } catch (RemoteException re) {
3214 }
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003215 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3216 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003217 return;
3218 }
3219
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003220 final int pid = Binder.getCallingPid();
3221 final int uid = Binder.getCallingUid();
3222 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3223 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3224 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3225
3226 long identityToken = clearCallingIdentity();
3227 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003228 UserAccounts accounts = getUserAccounts(userId);
3229 logRecordWithUid(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003230 accounts, AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_ADD, AccountsDb.TABLE_ACCOUNTS,
3231 userId);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003232 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003233 true /* stripAuthTokenFromResult */, null /* accountName */,
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07003234 false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003235 @Override
3236 public void run() throws RemoteException {
3237 mAuthenticator.addAccount(this, mAccountType, authTokenType, requiredFeatures,
3238 options);
3239 }
3240
3241 @Override
3242 protected String toDebugString(long now) {
3243 return super.toDebugString(now) + ", addAccount"
3244 + ", accountType " + accountType
3245 + ", requiredFeatures "
3246 + (requiredFeatures != null
3247 ? TextUtils.join(",", requiredFeatures)
3248 : null);
3249 }
3250 }.bind();
3251 } finally {
3252 restoreCallingIdentity(identityToken);
3253 }
3254 }
3255
Sandra Kwan78812282015-11-04 11:19:47 -08003256 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003257 public void startAddAccountSession(
3258 final IAccountManagerResponse response,
3259 final String accountType,
3260 final String authTokenType,
3261 final String[] requiredFeatures,
Sandra Kwan78812282015-11-04 11:19:47 -08003262 final boolean expectActivityLaunch,
3263 final Bundle optionsIn) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003264 Bundle.setDefusable(optionsIn, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003265 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3266 Log.v(TAG,
3267 "startAddAccountSession: accountType " + accountType
3268 + ", response " + response
3269 + ", authTokenType " + authTokenType
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003270 + ", requiredFeatures " + Arrays.toString(requiredFeatures)
Sandra Kwan78812282015-11-04 11:19:47 -08003271 + ", expectActivityLaunch " + expectActivityLaunch
3272 + ", caller's uid " + Binder.getCallingUid()
3273 + ", pid " + Binder.getCallingPid());
3274 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003275 Preconditions.checkArgument(response != null, "response cannot be null");
3276 Preconditions.checkArgument(accountType != null, "accountType cannot be null");
Sandra Kwan78812282015-11-04 11:19:47 -08003277
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003278 final int uid = Binder.getCallingUid();
3279 final int userId = UserHandle.getUserId(uid);
3280 if (!canUserModifyAccounts(userId, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003281 try {
3282 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
3283 "User is not allowed to add an account!");
3284 } catch (RemoteException re) {
3285 }
3286 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3287 return;
3288 }
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00003289 if (!canUserModifyAccountsForType(userId, accountType, uid)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003290 try {
3291 response.onError(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3292 "User cannot modify accounts of this type (policy).");
3293 } catch (RemoteException re) {
3294 }
3295 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3296 userId);
3297 return;
3298 }
Sandra Kwan78812282015-11-04 11:19:47 -08003299 final int pid = Binder.getCallingPid();
Sandra Kwan78812282015-11-04 11:19:47 -08003300 final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
3301 options.putInt(AccountManager.KEY_CALLER_UID, uid);
3302 options.putInt(AccountManager.KEY_CALLER_PID, pid);
3303
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003304 // Check to see if the Password should be included to the caller.
3305 String callerPkg = optionsIn.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3306 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003307 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003308
Sandra Kwan78812282015-11-04 11:19:47 -08003309 long identityToken = clearCallingIdentity();
3310 try {
Hongming Jin368aa192016-07-29 14:29:54 -07003311 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003312 logRecordWithUid(accounts, AccountsDb.DEBUG_ACTION_CALLED_START_ACCOUNT_ADD,
3313 AccountsDb.TABLE_ACCOUNTS, uid);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003314 new StartAccountSession(
3315 accounts,
3316 response,
3317 accountType,
3318 expectActivityLaunch,
3319 null /* accountName */,
3320 false /* authDetailsRequired */,
3321 true /* updateLastAuthenticationTime */,
3322 isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003323 @Override
3324 public void run() throws RemoteException {
3325 mAuthenticator.startAddAccountSession(this, mAccountType, authTokenType,
3326 requiredFeatures, options);
3327 }
3328
3329 @Override
3330 protected String toDebugString(long now) {
3331 String requiredFeaturesStr = TextUtils.join(",", requiredFeatures);
3332 return super.toDebugString(now) + ", startAddAccountSession" + ", accountType "
3333 + accountType + ", requiredFeatures "
3334 + (requiredFeatures != null ? requiredFeaturesStr : null);
3335 }
3336 }.bind();
3337 } finally {
3338 restoreCallingIdentity(identityToken);
3339 }
3340 }
3341
3342 /** Session that will encrypt the KEY_ACCOUNT_SESSION_BUNDLE in result. */
3343 private abstract class StartAccountSession extends Session {
3344
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003345 private final boolean mIsPasswordForwardingAllowed;
3346
3347 public StartAccountSession(
3348 UserAccounts accounts,
3349 IAccountManagerResponse response,
3350 String accountType,
3351 boolean expectActivityLaunch,
3352 String accountName,
3353 boolean authDetailsRequired,
3354 boolean updateLastAuthenticationTime,
3355 boolean isPasswordForwardingAllowed) {
Sandra Kwan78812282015-11-04 11:19:47 -08003356 super(accounts, response, accountType, expectActivityLaunch,
3357 true /* stripAuthTokenFromResult */, accountName, authDetailsRequired,
3358 updateLastAuthenticationTime);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003359 mIsPasswordForwardingAllowed = isPasswordForwardingAllowed;
Sandra Kwan78812282015-11-04 11:19:47 -08003360 }
3361
3362 @Override
3363 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003364 Bundle.setDefusable(result, true);
Sandra Kwan78812282015-11-04 11:19:47 -08003365 mNumResults++;
3366 Intent intent = null;
Sandra Kwan78812282015-11-04 11:19:47 -08003367 if (result != null
3368 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08003369 checkKeyIntent(
3370 Binder.getCallingUid(),
3371 intent);
Sandra Kwan78812282015-11-04 11:19:47 -08003372 }
Sandra Kwan78812282015-11-04 11:19:47 -08003373 IAccountManagerResponse response;
3374 if (mExpectActivityLaunch && result != null
3375 && result.containsKey(AccountManager.KEY_INTENT)) {
3376 response = mResponse;
3377 } else {
3378 response = getResponseAndClose();
3379 }
3380 if (response == null) {
3381 return;
3382 }
3383 if (result == null) {
3384 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3385 Log.v(TAG, getClass().getSimpleName() + " calling onError() on response "
3386 + response);
3387 }
3388 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3389 "null bundle returned");
3390 return;
3391 }
3392
3393 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) && (intent == null)) {
3394 // All AccountManager error codes are greater
3395 // than 0
3396 sendErrorResponse(response, result.getInt(AccountManager.KEY_ERROR_CODE),
3397 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3398 return;
3399 }
3400
Hongming Jin368aa192016-07-29 14:29:54 -07003401 // Omit passwords if the caller isn't permitted to see them.
3402 if (!mIsPasswordForwardingAllowed) {
3403 result.remove(AccountManager.KEY_PASSWORD);
3404 }
3405
Sandra Kwan78812282015-11-04 11:19:47 -08003406 // Strip auth token from result.
3407 result.remove(AccountManager.KEY_AUTHTOKEN);
3408
3409 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3410 Log.v(TAG,
3411 getClass().getSimpleName() + " calling onResult() on response " + response);
3412 }
3413
3414 // Get the session bundle created by authenticator. The
3415 // bundle contains data necessary for finishing the session
3416 // later. The session bundle will be encrypted here and
3417 // decrypted later when trying to finish the session.
3418 Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
3419 if (sessionBundle != null) {
3420 String accountType = sessionBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3421 if (TextUtils.isEmpty(accountType)
Andreas Gampe9b041742015-12-11 17:23:33 -08003422 || !mAccountType.equalsIgnoreCase(accountType)) {
Sandra Kwan78812282015-11-04 11:19:47 -08003423 Log.w(TAG, "Account type in session bundle doesn't match request.");
3424 }
3425 // Add accountType info to session bundle. This will
3426 // override any value set by authenticator.
3427 sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
3428
3429 // Encrypt session bundle before returning to caller.
3430 try {
3431 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3432 Bundle encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3433 result.putBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE, encryptedBundle);
3434 } catch (GeneralSecurityException e) {
3435 if (Log.isLoggable(TAG, Log.DEBUG)) {
3436 Log.v(TAG, "Failed to encrypt session bundle!", e);
3437 }
3438 sendErrorResponse(response, AccountManager.ERROR_CODE_INVALID_RESPONSE,
3439 "failed to encrypt session bundle");
3440 return;
3441 }
3442 }
3443
3444 sendResponse(response, result);
3445 }
3446 }
3447
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003448 @Override
Sandra Kwan0b84b452016-01-20 15:25:42 -08003449 public void finishSessionAsUser(IAccountManagerResponse response,
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003450 @NonNull Bundle sessionBundle,
3451 boolean expectActivityLaunch,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003452 Bundle appInfo,
3453 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003454 Bundle.setDefusable(sessionBundle, true);
Sandra Kwan0b84b452016-01-20 15:25:42 -08003455 int callingUid = Binder.getCallingUid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003456 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3457 Log.v(TAG,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003458 "finishSession: response "+ response
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003459 + ", expectActivityLaunch " + expectActivityLaunch
Sandra Kwan0b84b452016-01-20 15:25:42 -08003460 + ", caller's uid " + callingUid
3461 + ", caller's user id " + UserHandle.getCallingUserId()
3462 + ", pid " + Binder.getCallingPid()
3463 + ", for user id " + userId);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003464 }
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003465 Preconditions.checkArgument(response != null, "response cannot be null");
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003466 // Session bundle is the encrypted bundle of the original bundle created by authenticator.
3467 // Account type is added to it before encryption.
3468 if (sessionBundle == null || sessionBundle.size() == 0) {
3469 throw new IllegalArgumentException("sessionBundle is empty");
3470 }
3471
Dmitry Dementyev52745472016-12-02 10:27:45 -08003472 // Only allow the system process to finish session for other users.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003473 if (isCrossUser(callingUid, userId)) {
3474 throw new SecurityException(
3475 String.format(
3476 "User %s trying to finish session for %s without cross user permission",
3477 UserHandle.getCallingUserId(),
3478 userId));
3479 }
3480
Sandra Kwan0b84b452016-01-20 15:25:42 -08003481 if (!canUserModifyAccounts(userId, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003482 sendErrorResponse(response,
3483 AccountManager.ERROR_CODE_USER_RESTRICTED,
3484 "User is not allowed to add an account!");
3485 showCantAddAccount(AccountManager.ERROR_CODE_USER_RESTRICTED, userId);
3486 return;
3487 }
3488
3489 final int pid = Binder.getCallingPid();
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003490 final Bundle decryptedBundle;
3491 final String accountType;
3492 // First decrypt session bundle to get account type for checking permission.
3493 try {
3494 CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3495 decryptedBundle = cryptoHelper.decryptBundle(sessionBundle);
3496 if (decryptedBundle == null) {
3497 sendErrorResponse(
3498 response,
3499 AccountManager.ERROR_CODE_BAD_REQUEST,
3500 "failed to decrypt session bundle");
3501 return;
3502 }
3503 accountType = decryptedBundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
3504 // Account type cannot be null. This should not happen if session bundle was created
3505 // properly by #StartAccountSession.
3506 if (TextUtils.isEmpty(accountType)) {
3507 sendErrorResponse(
3508 response,
3509 AccountManager.ERROR_CODE_BAD_ARGUMENTS,
3510 "accountType is empty");
3511 return;
3512 }
3513
3514 // If by any chances, decryptedBundle contains colliding keys with
3515 // system info
3516 // such as AccountManager.KEY_ANDROID_PACKAGE_NAME required by the add account flow or
3517 // update credentials flow, we should replace with the new values of the current call.
3518 if (appInfo != null) {
3519 decryptedBundle.putAll(appInfo);
3520 }
3521
3522 // Add info that may be used by add account or update credentials flow.
Sandra Kwan0b84b452016-01-20 15:25:42 -08003523 decryptedBundle.putInt(AccountManager.KEY_CALLER_UID, callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003524 decryptedBundle.putInt(AccountManager.KEY_CALLER_PID, pid);
3525 } catch (GeneralSecurityException e) {
3526 if (Log.isLoggable(TAG, Log.DEBUG)) {
3527 Log.v(TAG, "Failed to decrypt session bundle!", e);
3528 }
3529 sendErrorResponse(
3530 response,
3531 AccountManager.ERROR_CODE_BAD_REQUEST,
3532 "failed to decrypt session bundle");
3533 return;
3534 }
3535
Sandra Kwan0b84b452016-01-20 15:25:42 -08003536 if (!canUserModifyAccountsForType(userId, accountType, callingUid)) {
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003537 sendErrorResponse(
3538 response,
3539 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3540 "User cannot modify accounts of this type (policy).");
3541 showCantAddAccount(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE,
3542 userId);
3543 return;
3544 }
3545
3546 long identityToken = clearCallingIdentity();
3547 try {
3548 UserAccounts accounts = getUserAccounts(userId);
3549 logRecordWithUid(
3550 accounts,
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07003551 AccountsDb.DEBUG_ACTION_CALLED_ACCOUNT_SESSION_FINISH,
3552 AccountsDb.TABLE_ACCOUNTS,
Sandra Kwan0b84b452016-01-20 15:25:42 -08003553 callingUid);
Sandra Kwan920f6ef2015-11-10 14:13:29 -08003554 new Session(
3555 accounts,
3556 response,
3557 accountType,
3558 expectActivityLaunch,
3559 true /* stripAuthTokenFromResult */,
3560 null /* accountName */,
3561 false /* authDetailsRequired */,
3562 true /* updateLastAuthenticationTime */) {
3563 @Override
3564 public void run() throws RemoteException {
3565 mAuthenticator.finishSession(this, mAccountType, decryptedBundle);
3566 }
3567
3568 @Override
3569 protected String toDebugString(long now) {
3570 return super.toDebugString(now)
3571 + ", finishSession"
3572 + ", accountType " + accountType;
3573 }
3574 }.bind();
3575 } finally {
3576 restoreCallingIdentity(identityToken);
3577 }
3578 }
3579
Amith Yamasaniae7034a2014-09-22 12:42:12 -07003580 private void showCantAddAccount(int errorCode, int userId) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003581 final DevicePolicyManagerInternal dpmi =
3582 LocalServices.getService(DevicePolicyManagerInternal.class);
3583 Intent intent = null;
Nicolas Prevot14fc1972016-08-24 14:21:38 +01003584 if (dpmi == null) {
3585 intent = getDefaultCantAddAccountIntent(errorCode);
3586 } else if (errorCode == AccountManager.ERROR_CODE_USER_RESTRICTED) {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003587 intent = dpmi.createUserRestrictionSupportIntent(userId,
3588 UserManager.DISALLOW_MODIFY_ACCOUNTS);
3589 } else if (errorCode == AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE) {
3590 intent = dpmi.createShowAdminSupportIntent(userId, false);
3591 }
3592 if (intent == null) {
3593 intent = getDefaultCantAddAccountIntent(errorCode);
3594 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003595 long identityToken = clearCallingIdentity();
3596 try {
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003597 mContext.startActivityAsUser(intent, new UserHandle(userId));
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003598 } finally {
3599 restoreCallingIdentity(identityToken);
3600 }
3601 }
3602
Nicolas Prevot709a63d2016-06-09 13:14:00 +01003603 /**
3604 * Called when we don't know precisely who is preventing us from adding an account.
3605 */
3606 private Intent getDefaultCantAddAccountIntent(int errorCode) {
3607 Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
3608 cantAddAccount.putExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, errorCode);
3609 cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3610 return cantAddAccount;
3611 }
3612
Alexandra Gherghina999d3942014-07-03 11:40:08 +01003613 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003614 public void confirmCredentialsAsUser(
3615 IAccountManagerResponse response,
3616 final Account account,
3617 final Bundle options,
3618 final boolean expectActivityLaunch,
Amith Yamasani2c7bc262012-11-05 16:46:02 -08003619 int userId) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003620 Bundle.setDefusable(options, true);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003621 int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003622 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3623 Log.v(TAG, "confirmCredentials: " + account
3624 + ", response " + response
3625 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003626 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003627 + ", pid " + Binder.getCallingPid());
3628 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07003629 // Only allow the system process to read accounts of other users
3630 if (isCrossUser(callingUid, userId)) {
3631 throw new SecurityException(
3632 String.format(
3633 "User %s trying to confirm account credentials for %s" ,
3634 UserHandle.getCallingUserId(),
3635 userId));
3636 }
Fred Quintana382601f2010-03-25 12:25:10 -07003637 if (response == null) throw new IllegalArgumentException("response is null");
3638 if (account == null) throw new IllegalArgumentException("account is null");
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003639 long identityToken = clearCallingIdentity();
3640 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003641 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003642 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003643 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003644 true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003645 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003646 public void run() throws RemoteException {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07003647 mAuthenticator.confirmCredentials(this, account, options);
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003648 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003649 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003650 protected String toDebugString(long now) {
3651 return super.toDebugString(now) + ", confirmCredentials"
3652 + ", " + account;
3653 }
3654 }.bind();
3655 } finally {
3656 restoreCallingIdentity(identityToken);
3657 }
Fred Quintana60307342009-03-24 22:48:12 -07003658 }
3659
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003660 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003661 public void updateCredentials(IAccountManagerResponse response, final Account account,
3662 final String authTokenType, final boolean expectActivityLaunch,
3663 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003664 Bundle.setDefusable(loginOptions, true);
Fred Quintana56285a62010-12-02 14:20:51 -08003665 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3666 Log.v(TAG, "updateCredentials: " + account
3667 + ", response " + response
3668 + ", authTokenType " + authTokenType
3669 + ", expectActivityLaunch " + expectActivityLaunch
3670 + ", caller's uid " + Binder.getCallingUid()
3671 + ", pid " + Binder.getCallingPid());
3672 }
Fred Quintana382601f2010-03-25 12:25:10 -07003673 if (response == null) throw new IllegalArgumentException("response is null");
3674 if (account == null) throw new IllegalArgumentException("account is null");
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003675 int userId = UserHandle.getCallingUserId();
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003676 long identityToken = clearCallingIdentity();
3677 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003678 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003679 new Session(accounts, response, account.type, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003680 true /* stripAuthTokenFromResult */, account.name,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07003681 false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003682 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003683 public void run() throws RemoteException {
3684 mAuthenticator.updateCredentials(this, account, authTokenType, loginOptions);
3685 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003686 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003687 protected String toDebugString(long now) {
3688 if (loginOptions != null) loginOptions.keySet();
3689 return super.toDebugString(now) + ", updateCredentials"
3690 + ", " + account
3691 + ", authTokenType " + authTokenType
3692 + ", loginOptions " + loginOptions;
3693 }
3694 }.bind();
3695 } finally {
3696 restoreCallingIdentity(identityToken);
3697 }
Fred Quintana60307342009-03-24 22:48:12 -07003698 }
3699
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08003700 @Override
Sandra Kwane68c37e2015-11-12 17:11:49 -08003701 public void startUpdateCredentialsSession(
3702 IAccountManagerResponse response,
3703 final Account account,
3704 final String authTokenType,
3705 final boolean expectActivityLaunch,
3706 final Bundle loginOptions) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003707 Bundle.setDefusable(loginOptions, true);
Sandra Kwane68c37e2015-11-12 17:11:49 -08003708 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3709 Log.v(TAG,
3710 "startUpdateCredentialsSession: " + account + ", response " + response
3711 + ", authTokenType " + authTokenType + ", expectActivityLaunch "
3712 + expectActivityLaunch + ", caller's uid " + Binder.getCallingUid()
3713 + ", pid " + Binder.getCallingPid());
3714 }
3715 if (response == null) {
3716 throw new IllegalArgumentException("response is null");
3717 }
3718 if (account == null) {
3719 throw new IllegalArgumentException("account is null");
3720 }
Sandra Kwana578d112015-12-16 16:01:43 -08003721
3722 final int uid = Binder.getCallingUid();
Sandra Kwane68c37e2015-11-12 17:11:49 -08003723 int userId = UserHandle.getCallingUserId();
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003724
3725 // Check to see if the Password should be included to the caller.
3726 String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
3727 boolean isPasswordForwardingAllowed = isPermitted(
Carlos Valdivia714bbd82016-04-22 14:10:40 -07003728 callerPkg, uid, Manifest.permission.GET_PASSWORD);
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003729
Sandra Kwane68c37e2015-11-12 17:11:49 -08003730 long identityToken = clearCallingIdentity();
3731 try {
3732 UserAccounts accounts = getUserAccounts(userId);
3733 new StartAccountSession(
3734 accounts,
3735 response,
3736 account.type,
3737 expectActivityLaunch,
3738 account.name,
3739 false /* authDetailsRequired */,
Carlos Valdivia51b651a2016-03-30 13:44:28 -07003740 true /* updateLastCredentialTime */,
3741 isPasswordForwardingAllowed) {
Sandra Kwane68c37e2015-11-12 17:11:49 -08003742 @Override
3743 public void run() throws RemoteException {
3744 mAuthenticator.startUpdateCredentialsSession(this, account, authTokenType,
3745 loginOptions);
3746 }
3747
3748 @Override
3749 protected String toDebugString(long now) {
3750 if (loginOptions != null)
3751 loginOptions.keySet();
3752 return super.toDebugString(now)
3753 + ", startUpdateCredentialsSession"
3754 + ", " + account
3755 + ", authTokenType " + authTokenType
3756 + ", loginOptions " + loginOptions;
3757 }
3758 }.bind();
3759 } finally {
3760 restoreCallingIdentity(identityToken);
3761 }
3762 }
3763
3764 @Override
Sandra Kwan390c9d22016-01-12 14:13:37 -08003765 public void isCredentialsUpdateSuggested(
3766 IAccountManagerResponse response,
3767 final Account account,
3768 final String statusToken) {
3769 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3770 Log.v(TAG,
3771 "isCredentialsUpdateSuggested: " + account + ", response " + response
3772 + ", caller's uid " + Binder.getCallingUid()
3773 + ", pid " + Binder.getCallingPid());
3774 }
3775 if (response == null) {
3776 throw new IllegalArgumentException("response is null");
3777 }
3778 if (account == null) {
3779 throw new IllegalArgumentException("account is null");
3780 }
3781 if (TextUtils.isEmpty(statusToken)) {
3782 throw new IllegalArgumentException("status token is empty");
3783 }
3784
Sandra Kwan390c9d22016-01-12 14:13:37 -08003785 int usrId = UserHandle.getCallingUserId();
3786 long identityToken = clearCallingIdentity();
3787 try {
3788 UserAccounts accounts = getUserAccounts(usrId);
3789 new Session(accounts, response, account.type, false /* expectActivityLaunch */,
3790 false /* stripAuthTokenFromResult */, account.name,
3791 false /* authDetailsRequired */) {
3792 @Override
3793 protected String toDebugString(long now) {
3794 return super.toDebugString(now) + ", isCredentialsUpdateSuggested"
3795 + ", " + account;
3796 }
3797
3798 @Override
3799 public void run() throws RemoteException {
3800 mAuthenticator.isCredentialsUpdateSuggested(this, account, statusToken);
3801 }
3802
3803 @Override
3804 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06003805 Bundle.setDefusable(result, true);
Sandra Kwan390c9d22016-01-12 14:13:37 -08003806 IAccountManagerResponse response = getResponseAndClose();
3807 if (response == null) {
3808 return;
3809 }
3810
3811 if (result == null) {
3812 sendErrorResponse(
3813 response,
3814 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3815 "null bundle");
3816 return;
3817 }
3818
3819 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3820 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
3821 + response);
3822 }
3823 // Check to see if an error occurred. We know if an error occurred because all
3824 // error codes are greater than 0.
3825 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0)) {
3826 sendErrorResponse(response,
3827 result.getInt(AccountManager.KEY_ERROR_CODE),
3828 result.getString(AccountManager.KEY_ERROR_MESSAGE));
3829 return;
3830 }
3831 if (!result.containsKey(AccountManager.KEY_BOOLEAN_RESULT)) {
3832 sendErrorResponse(
3833 response,
3834 AccountManager.ERROR_CODE_INVALID_RESPONSE,
3835 "no result in response");
3836 return;
3837 }
3838 final Bundle newResult = new Bundle();
3839 newResult.putBoolean(AccountManager.KEY_BOOLEAN_RESULT,
3840 result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false));
3841 sendResponse(response, newResult);
3842 }
3843 }.bind();
3844 } finally {
3845 restoreCallingIdentity(identityToken);
3846 }
3847 }
3848
3849 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07003850 public void editProperties(IAccountManagerResponse response, final String accountType,
3851 final boolean expectActivityLaunch) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003852 final int callingUid = Binder.getCallingUid();
Fred Quintana56285a62010-12-02 14:20:51 -08003853 if (Log.isLoggable(TAG, Log.VERBOSE)) {
3854 Log.v(TAG, "editProperties: accountType " + accountType
3855 + ", response " + response
3856 + ", expectActivityLaunch " + expectActivityLaunch
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003857 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08003858 + ", pid " + Binder.getCallingPid());
3859 }
Fred Quintana382601f2010-03-25 12:25:10 -07003860 if (response == null) throw new IllegalArgumentException("response is null");
3861 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00003862 int userId = UserHandle.getCallingUserId();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003863 if (!isAccountManagedByCaller(accountType, callingUid, userId)
3864 && !isSystemUid(callingUid)) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07003865 String msg = String.format(
3866 "uid %s cannot edit authenticator properites for account type: %s",
3867 callingUid,
3868 accountType);
3869 throw new SecurityException(msg);
3870 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003871 long identityToken = clearCallingIdentity();
3872 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07003873 UserAccounts accounts = getUserAccounts(userId);
Amith Yamasani04e0d262012-02-14 11:50:53 -08003874 new Session(accounts, response, accountType, expectActivityLaunch,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08003875 true /* stripAuthTokenFromResult */, null /* accountName */,
3876 false /* authDetailsRequired */) {
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003877 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003878 public void run() throws RemoteException {
3879 mAuthenticator.editProperties(this, mAccountType);
3880 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07003881 @Override
Fred Quintana26fc5eb2009-04-09 15:05:50 -07003882 protected String toDebugString(long now) {
3883 return super.toDebugString(now) + ", editProperties"
3884 + ", accountType " + accountType;
3885 }
3886 }.bind();
3887 } finally {
3888 restoreCallingIdentity(identityToken);
3889 }
Fred Quintana60307342009-03-24 22:48:12 -07003890 }
3891
Amith Yamasani12747872015-12-07 14:19:49 -08003892 @Override
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003893 public boolean hasAccountAccess(@NonNull Account account, @NonNull String packageName,
3894 @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003895 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003896 throw new SecurityException("Can be called only by system UID");
3897 }
3898 Preconditions.checkNotNull(account, "account cannot be null");
3899 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3900 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3901
3902 final int userId = userHandle.getIdentifier();
3903
3904 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3905
3906 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003907 int uid = mPackageManager.getPackageUidAsUser(packageName, userId);
Svet Ganovf6d424f12016-09-20 20:18:53 -07003908 return hasAccountAccess(account, packageName, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003909 } catch (NameNotFoundException e) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003910 Log.d(TAG, "Package not found " + e.getMessage());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003911 return false;
3912 }
3913 }
3914
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003915 // Returns package with oldest target SDK for given UID.
3916 private String getPackageNameForUid(int uid) {
3917 String[] packageNames = mPackageManager.getPackagesForUid(uid);
3918 if (ArrayUtils.isEmpty(packageNames)) {
3919 return null;
3920 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003921 String packageName = packageNames[0];
Fyodor Kupolov892fc8d2017-03-22 12:57:04 -07003922 if (packageNames.length == 1) {
3923 return packageName;
3924 }
3925 // Due to visibility changes we want to use package with oldest target SDK
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003926 int oldestVersion = Integer.MAX_VALUE;
3927 for (String name : packageNames) {
3928 try {
3929 ApplicationInfo applicationInfo = mPackageManager.getApplicationInfo(name, 0);
3930 if (applicationInfo != null) {
3931 int version = applicationInfo.targetSdkVersion;
3932 if (version < oldestVersion) {
3933 oldestVersion = version;
3934 packageName = name;
3935 }
3936 }
3937 } catch (NameNotFoundException e) {
3938 // skip
3939 }
3940 }
3941 return packageName;
3942 }
3943
Svet Ganovf6d424f12016-09-20 20:18:53 -07003944 private boolean hasAccountAccess(@NonNull Account account, @Nullable String packageName,
3945 int uid) {
3946 if (packageName == null) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003947 packageName = getPackageNameForUid(uid);
3948 if (packageName == null) {
Svet Ganovf6d424f12016-09-20 20:18:53 -07003949 return false;
3950 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07003951 }
3952
3953 // Use null token which means any token. Having a token means the package
3954 // is trusted by the authenticator, hence it is fine to access the account.
3955 if (permissionIsGranted(account, null, uid, UserHandle.getUserId(uid))) {
3956 return true;
3957 }
3958 // In addition to the permissions required to get an auth token we also allow
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003959 // the account to be accessed by apps for which user or authenticator granted visibility.
Svet Ganovf6d424f12016-09-20 20:18:53 -07003960
Dmitry Dementyeve366f822017-01-31 10:25:10 -08003961 int visibility = resolveAccountVisibility(account, packageName,
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003962 getUserAccounts(UserHandle.getUserId(uid)));
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08003963 return (visibility == AccountManager.VISIBILITY_VISIBLE
Dmitry Dementyev8882d882017-03-14 17:25:46 -07003964 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003965 }
3966
3967 @Override
3968 public IntentSender createRequestAccountAccessIntentSenderAsUser(@NonNull Account account,
3969 @NonNull String packageName, @NonNull UserHandle userHandle) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003970 if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07003971 throw new SecurityException("Can be called only by system UID");
3972 }
3973
3974 Preconditions.checkNotNull(account, "account cannot be null");
3975 Preconditions.checkNotNull(packageName, "packageName cannot be null");
3976 Preconditions.checkNotNull(userHandle, "userHandle cannot be null");
3977
3978 final int userId = userHandle.getIdentifier();
3979
3980 Preconditions.checkArgumentInRange(userId, 0, Integer.MAX_VALUE, "user must be concrete");
3981
3982 final int uid;
3983 try {
3984 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
3985 } catch (NameNotFoundException e) {
3986 Slog.e(TAG, "Unknown package " + packageName);
3987 return null;
3988 }
3989
3990 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, null);
3991
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07003992 final long identity = Binder.clearCallingIdentity();
3993 try {
3994 return PendingIntent.getActivityAsUser(
3995 mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT
3996 | PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE,
3997 null, new UserHandle(userId)).getIntentSender();
3998 } finally {
3999 Binder.restoreCallingIdentity(identity);
4000 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004001 }
4002
4003 private Intent newRequestAccountAccessIntent(Account account, String packageName,
4004 int uid, RemoteCallback callback) {
4005 return newGrantCredentialsPermissionIntent(account, packageName, uid,
4006 new AccountAuthenticatorResponse(new IAccountAuthenticatorResponse.Stub() {
4007 @Override
4008 public void onResult(Bundle value) throws RemoteException {
4009 handleAuthenticatorResponse(true);
4010 }
4011
4012 @Override
4013 public void onRequestContinued() {
4014 /* ignore */
4015 }
4016
4017 @Override
4018 public void onError(int errorCode, String errorMessage) throws RemoteException {
4019 handleAuthenticatorResponse(false);
4020 }
4021
4022 private void handleAuthenticatorResponse(boolean accessGranted) throws RemoteException {
4023 cancelNotification(getCredentialPermissionNotificationId(account,
Svet Ganovf6d424f12016-09-20 20:18:53 -07004024 AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, uid), packageName,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004025 UserHandle.getUserHandleForUid(uid));
4026 if (callback != null) {
4027 Bundle result = new Bundle();
4028 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, accessGranted);
4029 callback.sendResult(result);
4030 }
4031 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07004032 }), AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE, false);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07004033 }
4034
4035 @Override
Amith Yamasani12747872015-12-07 14:19:49 -08004036 public boolean someUserHasAccount(@NonNull final Account account) {
4037 if (!UserHandle.isSameApp(Process.SYSTEM_UID, Binder.getCallingUid())) {
4038 throw new SecurityException("Only system can check for accounts across users");
4039 }
4040 final long token = Binder.clearCallingIdentity();
4041 try {
4042 AccountAndUser[] allAccounts = getAllAccounts();
4043 for (int i = allAccounts.length - 1; i >= 0; i--) {
4044 if (allAccounts[i].account.equals(account)) {
4045 return true;
4046 }
4047 }
4048 return false;
4049 } finally {
4050 Binder.restoreCallingIdentity(token);
4051 }
4052 }
4053
Fred Quintana33269202009-04-20 16:05:10 -07004054 private class GetAccountsByTypeAndFeatureSession extends Session {
4055 private final String[] mFeatures;
4056 private volatile Account[] mAccountsOfType = null;
4057 private volatile ArrayList<Account> mAccountsWithFeatures = null;
4058 private volatile int mCurrentAccount = 0;
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004059 private final int mCallingUid;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004060 private final String mPackageName;
sunjianf29d5492017-05-11 15:42:31 -07004061 private final boolean mIncludeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004062
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004063 public GetAccountsByTypeAndFeatureSession(
4064 UserAccounts accounts,
4065 IAccountManagerResponse response,
4066 String type,
4067 String[] features,
4068 int callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004069 String packageName,
4070 boolean includeManagedNotVisible) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08004071 super(accounts, response, type, false /* expectActivityLaunch */,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004072 true /* stripAuthTokenFromResult */, null /* accountName */,
4073 false /* authDetailsRequired */);
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004074 mCallingUid = callingUid;
Fred Quintana33269202009-04-20 16:05:10 -07004075 mFeatures = features;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004076 mPackageName = packageName;
sunjianf29d5492017-05-11 15:42:31 -07004077 mIncludeManagedNotVisible = includeManagedNotVisible;
Fred Quintana33269202009-04-20 16:05:10 -07004078 }
4079
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004080 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004081 public void run() throws RemoteException {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004082 mAccountsOfType = getAccountsFromCache(mAccounts, mAccountType,
sunjianf29d5492017-05-11 15:42:31 -07004083 mCallingUid, mPackageName, mIncludeManagedNotVisible);
Fred Quintana33269202009-04-20 16:05:10 -07004084 // check whether each account matches the requested features
Tejas Khorana5edff3b2016-06-28 20:59:52 -07004085 mAccountsWithFeatures = new ArrayList<>(mAccountsOfType.length);
Fred Quintana33269202009-04-20 16:05:10 -07004086 mCurrentAccount = 0;
4087
4088 checkAccount();
4089 }
4090
4091 public void checkAccount() {
4092 if (mCurrentAccount >= mAccountsOfType.length) {
4093 sendResult();
4094 return;
Fred Quintanaa698f422009-04-08 19:14:54 -07004095 }
Fred Quintana33269202009-04-20 16:05:10 -07004096
Fred Quintana29e94b82010-03-10 12:11:51 -08004097 final IAccountAuthenticator accountAuthenticator = mAuthenticator;
4098 if (accountAuthenticator == null) {
4099 // It is possible that the authenticator has died, which is indicated by
4100 // mAuthenticator being set to null. If this happens then just abort.
4101 // There is no need to send back a result or error in this case since
4102 // that already happened when mAuthenticator was cleared.
4103 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4104 Log.v(TAG, "checkAccount: aborting session since we are no longer"
4105 + " connected to the authenticator, " + toDebugString());
4106 }
4107 return;
4108 }
Fred Quintana33269202009-04-20 16:05:10 -07004109 try {
Fred Quintana29e94b82010-03-10 12:11:51 -08004110 accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
Fred Quintana33269202009-04-20 16:05:10 -07004111 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004112 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
Fred Quintana33269202009-04-20 16:05:10 -07004113 }
4114 }
4115
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004116 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004117 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004118 Bundle.setDefusable(result, true);
Fred Quintana33269202009-04-20 16:05:10 -07004119 mNumResults++;
4120 if (result == null) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004121 onError(AccountManager.ERROR_CODE_INVALID_RESPONSE, "null bundle");
Fred Quintana33269202009-04-20 16:05:10 -07004122 return;
4123 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004124 if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
Fred Quintana33269202009-04-20 16:05:10 -07004125 mAccountsWithFeatures.add(mAccountsOfType[mCurrentAccount]);
4126 }
4127 mCurrentAccount++;
4128 checkAccount();
4129 }
4130
4131 public void sendResult() {
4132 IAccountManagerResponse response = getResponseAndClose();
4133 if (response != null) {
4134 try {
4135 Account[] accounts = new Account[mAccountsWithFeatures.size()];
4136 for (int i = 0; i < accounts.length; i++) {
4137 accounts[i] = mAccountsWithFeatures.get(i);
4138 }
Fred Quintana56285a62010-12-02 14:20:51 -08004139 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4140 Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
4141 + response);
4142 }
Fred Quintana33269202009-04-20 16:05:10 -07004143 Bundle result = new Bundle();
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004144 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
Fred Quintana33269202009-04-20 16:05:10 -07004145 response.onResult(result);
4146 } catch (RemoteException e) {
4147 // if the caller is dead then there is no one to care about remote exceptions
4148 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4149 Log.v(TAG, "failure while notifying response", e);
4150 }
4151 }
4152 }
4153 }
4154
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004155 @Override
Fred Quintana33269202009-04-20 16:05:10 -07004156 protected String toDebugString(long now) {
4157 return super.toDebugString(now) + ", getAccountsByTypeAndFeatures"
4158 + ", " + (mFeatures != null ? TextUtils.join(",", mFeatures) : null);
4159 }
4160 }
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004161
Amith Yamasani04e0d262012-02-14 11:50:53 -08004162 /**
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004163 * Returns the accounts visible to the client within the context of a specific user
Amith Yamasani04e0d262012-02-14 11:50:53 -08004164 * @hide
4165 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004166 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004167 public Account[] getAccounts(int userId, String opPackageName) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08004168 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004169 mAppOpsManager.checkPackage(callingUid, opPackageName);
Svetoslavf3f02ac2015-09-08 14:36:35 -07004170 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4171 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004172 if (visibleAccountTypes.isEmpty()) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004173 return EMPTY_ACCOUNT_ARRAY;
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004174 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08004175 long identityToken = clearCallingIdentity();
4176 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004177 UserAccounts accounts = getUserAccounts(userId);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004178 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004179 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004180 callingUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004181 opPackageName,
4182 visibleAccountTypes,
4183 false /* includeUserManagedNotVisible */);
Amith Yamasani04e0d262012-02-14 11:50:53 -08004184 } finally {
4185 restoreCallingIdentity(identityToken);
4186 }
4187 }
4188
Amith Yamasanif29f2362012-04-05 18:29:52 -07004189 /**
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004190 * Returns accounts for all running users, ignores visibility values.
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004191 *
Amith Yamasanif29f2362012-04-05 18:29:52 -07004192 * @hide
4193 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004194 @NonNull
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004195 public AccountAndUser[] getRunningAccounts() {
4196 final int[] runningUserIds;
4197 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004198 runningUserIds = ActivityManager.getService().getRunningUserIds();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004199 } catch (RemoteException e) {
4200 // Running in system_server; should never happen
4201 throw new RuntimeException(e);
4202 }
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004203 return getAccounts(runningUserIds);
4204 }
Amith Yamasanif29f2362012-04-05 18:29:52 -07004205
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004206 /**
4207 * Returns accounts for all users, ignores visibility values.
4208 *
4209 * @hide
4210 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004211 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004212 public AccountAndUser[] getAllAccounts() {
Amith Yamasanid04aaa32016-06-13 12:09:36 -07004213 final List<UserInfo> users = getUserManager().getUsers(true);
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004214 final int[] userIds = new int[users.size()];
4215 for (int i = 0; i < userIds.length; i++) {
4216 userIds[i] = users.get(i).id;
4217 }
4218 return getAccounts(userIds);
4219 }
4220
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004221 @NonNull
Jeff Sharkey6eb96202012-10-10 13:13:54 -07004222 private AccountAndUser[] getAccounts(int[] userIds) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004223 final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
Amith Yamasani0c19bf52013-10-03 10:34:58 -07004224 for (int userId : userIds) {
4225 UserAccounts userAccounts = getUserAccounts(userId);
4226 if (userAccounts == null) continue;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004227 Account[] accounts = getAccountsFromCache(
4228 userAccounts,
4229 null /* type */,
4230 Binder.getCallingUid(),
4231 null /* packageName */,
4232 false /* include managed not visible*/);
4233 for (Account account : accounts) {
4234 runningAccounts.add(new AccountAndUser(account, userId));
Amith Yamasanif29f2362012-04-05 18:29:52 -07004235 }
4236 }
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004237
4238 AccountAndUser[] accountsArray = new AccountAndUser[runningAccounts.size()];
4239 return runningAccounts.toArray(accountsArray);
Amith Yamasanif29f2362012-04-05 18:29:52 -07004240 }
4241
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004242 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004243 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004244 public Account[] getAccountsAsUser(String type, int userId, String opPackageName) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004245 int callingUid = Binder.getCallingUid();
4246 mAppOpsManager.checkPackage(callingUid, opPackageName);
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004247 return getAccountsAsUserForPackage(type, userId, opPackageName /* callingPackage */, -1,
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004248 opPackageName, false /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004249 }
4250
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004251 @NonNull
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004252 private Account[] getAccountsAsUserForPackage(
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004253 String type,
4254 int userId,
4255 String callingPackage,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004256 int packageUid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004257 String opPackageName,
4258 boolean includeUserManagedNotVisible) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004259 int callingUid = Binder.getCallingUid();
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004260 // Only allow the system process to read accounts of other users
4261 if (userId != UserHandle.getCallingUserId()
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004262 && callingUid != Process.SYSTEM_UID
Jim Miller464f5302013-02-27 18:33:25 -08004263 && mContext.checkCallingOrSelfPermission(
4264 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4265 != PackageManager.PERMISSION_GRANTED) {
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004266 throw new SecurityException("User " + UserHandle.getCallingUserId()
4267 + " trying to get account for " + userId);
4268 }
4269
Fred Quintana56285a62010-12-02 14:20:51 -08004270 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4271 Log.v(TAG, "getAccounts: accountType " + type
4272 + ", caller's uid " + Binder.getCallingUid()
4273 + ", pid " + Binder.getCallingPid());
4274 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004275
4276 // If the original calling app was using account choosing activity
4277 // provided by the framework or authenticator we'll passing in
4278 // the original caller's uid here, which is what should be used for filtering.
4279 List<String> managedTypes =
4280 getTypesManagedByCaller(callingUid, UserHandle.getUserId(callingUid));
4281 if (packageUid != -1 &&
4282 ((UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
4283 || (type != null && managedTypes.contains(type))))) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004284 callingUid = packageUid;
Svetoslav5579e412015-09-10 15:30:45 -07004285 opPackageName = callingPackage;
Amith Yamasani27db4682013-03-30 17:07:47 -07004286 }
Svetoslavf3f02ac2015-09-08 14:36:35 -07004287 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4288 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004289 if (visibleAccountTypes.isEmpty()
4290 || (type != null && !visibleAccountTypes.contains(type))) {
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004291 return EMPTY_ACCOUNT_ARRAY;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004292 } else if (visibleAccountTypes.contains(type)) {
4293 // Prune the list down to just the requested type.
4294 visibleAccountTypes = new ArrayList<>();
4295 visibleAccountTypes.add(type);
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07004296 } // else aggregate all the visible accounts (it won't matter if the
4297 // list is empty).
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004298
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004299 long identityToken = clearCallingIdentity();
4300 try {
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004301 UserAccounts accounts = getUserAccounts(userId);
Dmitry Dementyev52745472016-12-02 10:27:45 -08004302 return getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004303 accounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004304 callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004305 opPackageName,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004306 visibleAccountTypes,
4307 includeUserManagedNotVisible);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004308 } finally {
4309 restoreCallingIdentity(identityToken);
4310 }
4311 }
4312
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004313 @NonNull
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004314 private Account[] getAccountsInternal(
Carlos Valdiviaa3721e12015-08-10 18:40:06 -07004315 UserAccounts userAccounts,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004316 int callingUid,
4317 String callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004318 List<String> visibleAccountTypes,
4319 boolean includeUserManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004320 ArrayList<Account> visibleAccounts = new ArrayList<>();
4321 for (String visibleType : visibleAccountTypes) {
4322 Account[] accountsForType = getAccountsFromCache(
4323 userAccounts, visibleType, callingUid, callingPackage,
4324 includeUserManagedNotVisible);
4325 if (accountsForType != null) {
4326 visibleAccounts.addAll(Arrays.asList(accountsForType));
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004327 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004328 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004329 Account[] result = new Account[visibleAccounts.size()];
4330 for (int i = 0; i < visibleAccounts.size(); i++) {
4331 result[i] = visibleAccounts.get(i);
4332 }
4333 return result;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004334 }
4335
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004336 @Override
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004337 public void addSharedAccountsFromParentUser(int parentUserId, int userId,
4338 String opPackageName) {
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07004339 checkManageOrCreateUsersPermission("addSharedAccountsFromParentUser");
Sudheer Shankaf88ebeb2017-02-14 18:30:40 -08004340 Account[] accounts = getAccountsAsUser(null, parentUserId, opPackageName);
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004341 for (Account account : accounts) {
4342 addSharedAccountAsUser(account, userId);
4343 }
4344 }
4345
4346 private boolean addSharedAccountAsUser(Account account, int userId) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004347 userId = handleIncomingUser(userId);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004348 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004349 accounts.accountsDb.deleteSharedAccount(account);
4350 long accountId = accounts.accountsDb.insertSharedAccount(account);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004351 if (accountId < 0) {
4352 Log.w(TAG, "insertAccountIntoDatabase: " + account
4353 + ", skipping the DB insert failed");
4354 return false;
4355 }
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004356 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_ADD, AccountsDb.TABLE_SHARED_ACCOUNTS, accountId,
4357 accounts);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004358 return true;
4359 }
4360
4361 @Override
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004362 public boolean renameSharedAccountAsUser(Account account, String newName, int userId) {
4363 userId = handleIncomingUser(userId);
4364 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004365 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4366 int r = accounts.accountsDb.renameSharedAccount(account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004367 if (r > 0) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004368 int callingUid = getCallingUid();
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004369 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_RENAME, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004370 sharedTableAccountId, accounts, callingUid);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004371 // Recursively rename the account.
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004372 renameAccountInternal(accounts, account, newName);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07004373 }
4374 return r > 0;
4375 }
4376
4377 @Override
Amith Yamasani67df64b2012-12-14 12:09:36 -08004378 public boolean removeSharedAccountAsUser(Account account, int userId) {
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004379 return removeSharedAccountAsUser(account, userId, getCallingUid());
4380 }
4381
4382 private boolean removeSharedAccountAsUser(Account account, int userId, int callingUid) {
Amith Yamasani67df64b2012-12-14 12:09:36 -08004383 userId = handleIncomingUser(userId);
4384 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004385 long sharedTableAccountId = accounts.accountsDb.findSharedAccountId(account);
4386 boolean deleted = accounts.accountsDb.deleteSharedAccount(account);
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004387 if (deleted) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004388 logRecord(AccountsDb.DEBUG_ACTION_ACCOUNT_REMOVE, AccountsDb.TABLE_SHARED_ACCOUNTS,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07004389 sharedTableAccountId, accounts, callingUid);
Fyodor Kupolov06a484a2015-08-21 16:33:20 -07004390 removeAccountInternal(accounts, account, callingUid);
Amith Yamasani67df64b2012-12-14 12:09:36 -08004391 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07004392 return deleted;
Amith Yamasani67df64b2012-12-14 12:09:36 -08004393 }
4394
4395 @Override
4396 public Account[] getSharedAccountsAsUser(int userId) {
4397 userId = handleIncomingUser(userId);
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004398 UserAccounts accounts = getUserAccounts(userId);
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004399 synchronized (accounts.dbLock) {
4400 List<Account> accountList = accounts.accountsDb.getSharedAccounts();
4401 Account[] accountArray = new Account[accountList.size()];
4402 accountList.toArray(accountArray);
4403 return accountArray;
4404 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004405 }
4406
4407 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004408 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004409 public Account[] getAccounts(String type, String opPackageName) {
Tejas Khorana69990d92016-08-03 11:19:40 -07004410 return getAccountsAsUser(type, UserHandle.getCallingUserId(), opPackageName);
Amith Yamasani2c7bc262012-11-05 16:46:02 -08004411 }
4412
Amith Yamasani27db4682013-03-30 17:07:47 -07004413 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004414 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004415 public Account[] getAccountsForPackage(String packageName, int uid, String opPackageName) {
Amith Yamasani27db4682013-03-30 17:07:47 -07004416 int callingUid = Binder.getCallingUid();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004417 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)) {
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004418 // Don't do opPackageName check - caller is system.
Amith Yamasani27db4682013-03-30 17:07:47 -07004419 throw new SecurityException("getAccountsForPackage() called from unauthorized uid "
4420 + callingUid + " with uid=" + uid);
4421 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004422 return getAccountsAsUserForPackage(null, UserHandle.getCallingUserId(), packageName, uid,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004423 opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani27db4682013-03-30 17:07:47 -07004424 }
4425
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004426 @Override
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07004427 @NonNull
Svetoslavf3f02ac2015-09-08 14:36:35 -07004428 public Account[] getAccountsByTypeForPackage(String type, String packageName,
4429 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004430 int callingUid = Binder.getCallingUid();
4431 int userId = UserHandle.getCallingUserId();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004432 mAppOpsManager.checkPackage(callingUid, opPackageName);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004433 int packageUid = -1;
4434 try {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004435 packageUid = mPackageManager.getPackageUidAsUser(packageName, userId);
4436 } catch (NameNotFoundException re) {
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004437 Slog.e(TAG, "Couldn't determine the packageUid for " + packageName + re);
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004438 return EMPTY_ACCOUNT_ARRAY;
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004439 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004440 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID)
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004441 && (type != null && !isAccountManagedByCaller(type, callingUid, userId))) {
4442 return EMPTY_ACCOUNT_ARRAY;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004443 }
sunjiand62dc392017-06-01 12:05:59 -07004444 if (!UserHandle.isSameApp(callingUid, Process.SYSTEM_UID) && type == null) {
4445 return getAccountsAsUserForPackage(type, userId,
4446 packageName, packageUid, opPackageName, false /* includeUserManagedNotVisible */);
4447 }
Dmitry Dementyev5159f432017-03-09 12:59:56 -08004448 return getAccountsAsUserForPackage(type, userId,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004449 packageName, packageUid, opPackageName, true /* includeUserManagedNotVisible */);
Amith Yamasani3b458ad2013-04-18 18:40:07 -07004450 }
4451
sunjianf29d5492017-05-11 15:42:31 -07004452 private boolean needToStartChooseAccountActivity(Account[] accounts, String callingPackage) {
4453 if (accounts.length < 1) return false;
4454 if (accounts.length > 1) return true;
4455 Account account = accounts[0];
4456 UserAccounts userAccounts = getUserAccounts(UserHandle.getCallingUserId());
4457 int visibility = resolveAccountVisibility(account, callingPackage, userAccounts);
4458 if (visibility == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE) return true;
4459 return false;
4460 }
4461
4462 private void startChooseAccountActivityWithAccounts(
sunjianbdabd402017-06-06 17:54:07 -07004463 IAccountManagerResponse response, Account[] accounts, String callingPackage) {
sunjianf29d5492017-05-11 15:42:31 -07004464 Intent intent = new Intent(mContext, ChooseAccountActivity.class);
4465 intent.putExtra(AccountManager.KEY_ACCOUNTS, accounts);
4466 intent.putExtra(AccountManager.KEY_ACCOUNT_MANAGER_RESPONSE,
4467 new AccountManagerResponse(response));
sunjianbdabd402017-06-06 17:54:07 -07004468 intent.putExtra(AccountManager.KEY_ANDROID_PACKAGE_NAME, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004469
4470 mContext.startActivityAsUser(intent, UserHandle.of(UserHandle.getCallingUserId()));
4471 }
4472
4473 private void handleGetAccountsResult(
4474 IAccountManagerResponse response,
4475 Account[] accounts,
4476 String callingPackage) {
4477
4478 if (needToStartChooseAccountActivity(accounts, callingPackage)) {
sunjianbdabd402017-06-06 17:54:07 -07004479 startChooseAccountActivityWithAccounts(response, accounts, callingPackage);
sunjianf29d5492017-05-11 15:42:31 -07004480 return;
4481 }
4482 if (accounts.length == 1) {
4483 Bundle bundle = new Bundle();
4484 bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accounts[0].name);
4485 bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accounts[0].type);
4486 onResult(response, bundle);
4487 return;
4488 }
4489 // No qualified account exists, return an empty Bundle.
4490 onResult(response, new Bundle());
4491 }
4492
4493 @Override
4494 public void getAccountByTypeAndFeatures(
4495 IAccountManagerResponse response,
4496 String accountType,
4497 String[] features,
4498 String opPackageName) {
4499
4500 int callingUid = Binder.getCallingUid();
4501 mAppOpsManager.checkPackage(callingUid, opPackageName);
4502 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4503 Log.v(TAG, "getAccount: accountType " + accountType
4504 + ", response " + response
4505 + ", features " + Arrays.toString(features)
4506 + ", caller's uid " + callingUid
4507 + ", pid " + Binder.getCallingPid());
4508 }
4509 if (response == null) throw new IllegalArgumentException("response is null");
4510 if (accountType == null) throw new IllegalArgumentException("accountType is null");
4511
4512 int userId = UserHandle.getCallingUserId();
4513
4514 long identityToken = clearCallingIdentity();
4515 try {
4516 UserAccounts userAccounts = getUserAccounts(userId);
4517 if (ArrayUtils.isEmpty(features)) {
4518 Account[] accountsWithManagedNotVisible = getAccountsFromCache(
4519 userAccounts, accountType, callingUid, opPackageName,
4520 true /* include managed not visible */);
4521 handleGetAccountsResult(
4522 response, accountsWithManagedNotVisible, opPackageName);
4523 return;
4524 }
4525
4526 IAccountManagerResponse retrieveAccountsResponse =
4527 new IAccountManagerResponse.Stub() {
4528 @Override
4529 public void onResult(Bundle value) throws RemoteException {
4530 Parcelable[] parcelables = value.getParcelableArray(
4531 AccountManager.KEY_ACCOUNTS);
4532 Account[] accounts = new Account[parcelables.length];
4533 for (int i = 0; i < parcelables.length; i++) {
4534 accounts[i] = (Account) parcelables[i];
4535 }
4536 handleGetAccountsResult(
4537 response, accounts, opPackageName);
4538 }
4539
4540 @Override
4541 public void onError(int errorCode, String errorMessage)
4542 throws RemoteException {
4543 // Will not be called in this case.
4544 }
4545 };
4546 new GetAccountsByTypeAndFeatureSession(
4547 userAccounts,
4548 retrieveAccountsResponse,
4549 accountType,
4550 features,
4551 callingUid,
4552 opPackageName,
4553 true /* include managed not visible */).bind();
4554 } finally {
4555 restoreCallingIdentity(identityToken);
4556 }
4557 }
4558
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004559 @Override
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004560 public void getAccountsByFeatures(
4561 IAccountManagerResponse response,
4562 String type,
Svetoslavf3f02ac2015-09-08 14:36:35 -07004563 String[] features,
4564 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004565 int callingUid = Binder.getCallingUid();
Dmitry Dementyeve366f822017-01-31 10:25:10 -08004566 mAppOpsManager.checkPackage(callingUid, opPackageName);
Fred Quintana56285a62010-12-02 14:20:51 -08004567 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4568 Log.v(TAG, "getAccounts: accountType " + type
4569 + ", response " + response
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004570 + ", features " + Arrays.toString(features)
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004571 + ", caller's uid " + callingUid
Fred Quintana56285a62010-12-02 14:20:51 -08004572 + ", pid " + Binder.getCallingPid());
4573 }
Fred Quintana382601f2010-03-25 12:25:10 -07004574 if (response == null) throw new IllegalArgumentException("response is null");
4575 if (type == null) throw new IllegalArgumentException("accountType is null");
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004576 int userId = UserHandle.getCallingUserId();
4577
Svetoslavf3f02ac2015-09-08 14:36:35 -07004578 List<String> visibleAccountTypes = getTypesVisibleToCaller(callingUid, userId,
4579 opPackageName);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004580 if (!visibleAccountTypes.contains(type)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004581 Bundle result = new Bundle();
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004582 // Need to return just the accounts that are from matching signatures.
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08004583 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, EMPTY_ACCOUNT_ARRAY);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07004584 try {
4585 response.onResult(result);
4586 } catch (RemoteException e) {
4587 Log.e(TAG, "Cannot respond to caller do to exception." , e);
4588 }
4589 return;
4590 }
sunjianf29d5492017-05-11 15:42:31 -07004591
Fred Quintana33269202009-04-20 16:05:10 -07004592 long identityToken = clearCallingIdentity();
4593 try {
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07004594 UserAccounts userAccounts = getUserAccounts(userId);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004595 if (features == null || features.length == 0) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07004596 Account[] accounts = getAccountsFromCache(userAccounts, type, callingUid,
4597 opPackageName, false);
Fred Quintanad4a9d6c2010-02-24 12:07:53 -08004598 Bundle result = new Bundle();
4599 result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
4600 onResult(response, result);
Fred Quintanaffd0cb042009-08-15 21:45:26 -07004601 return;
4602 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00004603 new GetAccountsByTypeAndFeatureSession(
4604 userAccounts,
4605 response,
4606 type,
4607 features,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004608 callingUid,
sunjianf29d5492017-05-11 15:42:31 -07004609 opPackageName,
4610 false /* include managed not visible */).bind();
Fred Quintana33269202009-04-20 16:05:10 -07004611 } finally {
4612 restoreCallingIdentity(identityToken);
Fred Quintana60307342009-03-24 22:48:12 -07004613 }
4614 }
4615
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004616 @Override
4617 public void onAccountAccessed(String token) throws RemoteException {
4618 final int uid = Binder.getCallingUid();
4619 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID) {
4620 return;
4621 }
4622 final int userId = UserHandle.getCallingUserId();
4623 final long identity = Binder.clearCallingIdentity();
4624 try {
4625 for (Account account : getAccounts(userId, mContext.getOpPackageName())) {
4626 if (Objects.equals(account.getAccessId(), token)) {
4627 // An app just accessed the account. At this point it knows about
4628 // it and there is not need to hide this account from the app.
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08004629 // Do we need to update account visibility here?
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07004630 if (!hasAccountAccess(account, null, uid)) {
4631 updateAppPermission(account, AccountManager.ACCOUNT_ACCESS_TOKEN_TYPE,
4632 uid, true);
4633 }
4634 }
4635 }
4636 } finally {
4637 Binder.restoreCallingIdentity(identity);
4638 }
4639 }
4640
Fred Quintanaa698f422009-04-08 19:14:54 -07004641 private abstract class Session extends IAccountAuthenticatorResponse.Stub
Fred Quintanab839afc2009-10-14 15:57:28 -07004642 implements IBinder.DeathRecipient, ServiceConnection {
Fred Quintana60307342009-03-24 22:48:12 -07004643 IAccountManagerResponse mResponse;
4644 final String mAccountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004645 final boolean mExpectActivityLaunch;
4646 final long mCreationTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004647 final String mAccountName;
4648 // Indicates if we need to add auth details(like last credential time)
4649 final boolean mAuthDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004650 // If set, we need to update the last authenticated time. This is
4651 // currently
4652 // used on
4653 // successful confirming credentials.
4654 final boolean mUpdateLastAuthenticatedTime;
Fred Quintanaa698f422009-04-08 19:14:54 -07004655
Fred Quintana33269202009-04-20 16:05:10 -07004656 public int mNumResults = 0;
Fred Quintanaa698f422009-04-08 19:14:54 -07004657 private int mNumRequestContinued = 0;
4658 private int mNumErrors = 0;
4659
Fred Quintana60307342009-03-24 22:48:12 -07004660 IAccountAuthenticator mAuthenticator = null;
4661
Fred Quintana8570f742010-02-18 10:32:54 -08004662 private final boolean mStripAuthTokenFromResult;
Amith Yamasani04e0d262012-02-14 11:50:53 -08004663 protected final UserAccounts mAccounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004664
Amith Yamasani04e0d262012-02-14 11:50:53 -08004665 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004666 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4667 boolean authDetailsRequired) {
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004668 this(accounts, response, accountType, expectActivityLaunch, stripAuthTokenFromResult,
4669 accountName, authDetailsRequired, false /* updateLastAuthenticatedTime */);
4670 }
4671
4672 public Session(UserAccounts accounts, IAccountManagerResponse response, String accountType,
4673 boolean expectActivityLaunch, boolean stripAuthTokenFromResult, String accountName,
4674 boolean authDetailsRequired, boolean updateLastAuthenticatedTime) {
Fred Quintana60307342009-03-24 22:48:12 -07004675 super();
Amith Yamasani67df64b2012-12-14 12:09:36 -08004676 //if (response == null) throw new IllegalArgumentException("response is null");
Fred Quintana33269202009-04-20 16:05:10 -07004677 if (accountType == null) throw new IllegalArgumentException("accountType is null");
Amith Yamasani04e0d262012-02-14 11:50:53 -08004678 mAccounts = accounts;
Fred Quintana8570f742010-02-18 10:32:54 -08004679 mStripAuthTokenFromResult = stripAuthTokenFromResult;
Fred Quintana60307342009-03-24 22:48:12 -07004680 mResponse = response;
4681 mAccountType = accountType;
Fred Quintanaa698f422009-04-08 19:14:54 -07004682 mExpectActivityLaunch = expectActivityLaunch;
4683 mCreationTime = SystemClock.elapsedRealtime();
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004684 mAccountName = accountName;
4685 mAuthDetailsRequired = authDetailsRequired;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004686 mUpdateLastAuthenticatedTime = updateLastAuthenticatedTime;
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004687
Fred Quintanaa698f422009-04-08 19:14:54 -07004688 synchronized (mSessions) {
4689 mSessions.put(toString(), this);
4690 }
Amith Yamasani67df64b2012-12-14 12:09:36 -08004691 if (response != null) {
4692 try {
4693 response.asBinder().linkToDeath(this, 0 /* flags */);
4694 } catch (RemoteException e) {
4695 mResponse = null;
4696 binderDied();
4697 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004698 }
Fred Quintana60307342009-03-24 22:48:12 -07004699 }
4700
Fred Quintanaa698f422009-04-08 19:14:54 -07004701 IAccountManagerResponse getResponseAndClose() {
Fred Quintana60307342009-03-24 22:48:12 -07004702 if (mResponse == null) {
4703 // this session has already been closed
4704 return null;
4705 }
Fred Quintana60307342009-03-24 22:48:12 -07004706 IAccountManagerResponse response = mResponse;
Fred Quintanaa698f422009-04-08 19:14:54 -07004707 close(); // this clears mResponse so we need to save the response before this call
Fred Quintana60307342009-03-24 22:48:12 -07004708 return response;
4709 }
4710
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004711 /**
4712 * Checks Intents, supplied via KEY_INTENT, to make sure that they don't violate our
4713 * security policy.
4714 *
4715 * In particular we want to make sure that the Authenticator doesn't try to trick users
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004716 * into launching arbitrary intents on the device via by tricking to click authenticator
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004717 * supplied entries in the system Settings app.
4718 */
4719 protected void checkKeyIntent(
4720 int authUid,
4721 Intent intent) throws SecurityException {
Jeff Sharkeyd722e782017-06-12 17:33:07 -06004722 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_READ_URI_PERMISSION
4723 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
4724 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
4725 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION));
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004726 long bid = Binder.clearCallingIdentity();
4727 try {
4728 PackageManager pm = mContext.getPackageManager();
4729 ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId);
4730 ActivityInfo targetActivityInfo = resolveInfo.activityInfo;
4731 int targetUid = targetActivityInfo.applicationInfo.uid;
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004732 if (!isExportedSystemActivity(targetActivityInfo)
4733 && (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid,
4734 targetUid))) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004735 String pkgName = targetActivityInfo.packageName;
4736 String activityName = targetActivityInfo.name;
4737 String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that "
4738 + "does not share a signature with the supplying authenticator (%s).";
4739 throw new SecurityException(
4740 String.format(tmpl, activityName, pkgName, mAccountType));
4741 }
4742 } finally {
4743 Binder.restoreCallingIdentity(bid);
4744 }
4745 }
4746
Dmitry Dementyevd5210ba2017-03-14 13:13:35 -07004747 private boolean isExportedSystemActivity(ActivityInfo activityInfo) {
4748 String className = activityInfo.name;
4749 return "android".equals(activityInfo.packageName) &&
4750 (GrantCredentialsPermissionActivity.class.getName().equals(className)
4751 || CantAddAccountActivity.class.getName().equals(className));
4752 }
4753
Fred Quintanaa698f422009-04-08 19:14:54 -07004754 private void close() {
4755 synchronized (mSessions) {
4756 if (mSessions.remove(toString()) == null) {
4757 // the session was already closed, so bail out now
4758 return;
4759 }
4760 }
4761 if (mResponse != null) {
4762 // stop listening for response deaths
4763 mResponse.asBinder().unlinkToDeath(this, 0 /* flags */);
4764
4765 // clear this so that we don't accidentally send any further results
4766 mResponse = null;
4767 }
4768 cancelTimeout();
4769 unbind();
4770 }
4771
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004772 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004773 public void binderDied() {
4774 mResponse = null;
4775 close();
4776 }
4777
4778 protected String toDebugString() {
4779 return toDebugString(SystemClock.elapsedRealtime());
4780 }
4781
4782 protected String toDebugString(long now) {
4783 return "Session: expectLaunch " + mExpectActivityLaunch
4784 + ", connected " + (mAuthenticator != null)
4785 + ", stats (" + mNumResults + "/" + mNumRequestContinued
4786 + "/" + mNumErrors + ")"
4787 + ", lifetime " + ((now - mCreationTime) / 1000.0);
4788 }
4789
Fred Quintana60307342009-03-24 22:48:12 -07004790 void bind() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004791 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4792 Log.v(TAG, "initiating bind to authenticator type " + mAccountType);
4793 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004794 if (!bindToAuthenticator(mAccountType)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004795 Log.d(TAG, "bind attempt failed for " + toDebugString());
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004796 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
Fred Quintana60307342009-03-24 22:48:12 -07004797 }
4798 }
4799
4800 private void unbind() {
4801 if (mAuthenticator != null) {
4802 mAuthenticator = null;
Fred Quintanab839afc2009-10-14 15:57:28 -07004803 mContext.unbindService(this);
Fred Quintana60307342009-03-24 22:48:12 -07004804 }
4805 }
4806
Fred Quintana60307342009-03-24 22:48:12 -07004807 public void cancelTimeout() {
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07004808 mHandler.removeMessages(MESSAGE_TIMED_OUT, this);
Fred Quintana60307342009-03-24 22:48:12 -07004809 }
4810
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004811 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004812 public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintana60307342009-03-24 22:48:12 -07004813 mAuthenticator = IAccountAuthenticator.Stub.asInterface(service);
Fred Quintanaa698f422009-04-08 19:14:54 -07004814 try {
4815 run();
4816 } catch (RemoteException e) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004817 onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
Fred Quintanaa698f422009-04-08 19:14:54 -07004818 "remote exception");
4819 }
Fred Quintana60307342009-03-24 22:48:12 -07004820 }
4821
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004822 @Override
Fred Quintanab839afc2009-10-14 15:57:28 -07004823 public void onServiceDisconnected(ComponentName name) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004824 mAuthenticator = null;
4825 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004826 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004827 try {
4828 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4829 "disconnected");
4830 } catch (RemoteException e) {
4831 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4832 Log.v(TAG, "Session.onServiceDisconnected: "
4833 + "caught RemoteException while responding", e);
4834 }
4835 }
Fred Quintana60307342009-03-24 22:48:12 -07004836 }
4837 }
4838
Fred Quintanab839afc2009-10-14 15:57:28 -07004839 public abstract void run() throws RemoteException;
4840
Fred Quintana60307342009-03-24 22:48:12 -07004841 public void onTimedOut() {
Fred Quintanaa698f422009-04-08 19:14:54 -07004842 IAccountManagerResponse response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004843 if (response != null) {
Fred Quintana166466d2011-10-24 14:51:40 -07004844 try {
4845 response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
4846 "timeout");
4847 } catch (RemoteException e) {
4848 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4849 Log.v(TAG, "Session.onTimedOut: caught RemoteException while responding",
4850 e);
4851 }
4852 }
Fred Quintana60307342009-03-24 22:48:12 -07004853 }
4854 }
4855
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004856 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004857 public void onResult(Bundle result) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -06004858 Bundle.setDefusable(result, true);
Fred Quintanaa698f422009-04-08 19:14:54 -07004859 mNumResults++;
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004860 Intent intent = null;
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004861 if (result != null) {
4862 boolean isSuccessfulConfirmCreds = result.getBoolean(
4863 AccountManager.KEY_BOOLEAN_RESULT, false);
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004864 boolean isSuccessfulUpdateCredsOrAddAccount =
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004865 result.containsKey(AccountManager.KEY_ACCOUNT_NAME)
4866 && result.containsKey(AccountManager.KEY_ACCOUNT_TYPE);
Carlos Valdivia91979be2015-05-22 14:11:35 -07004867 // We should only update lastAuthenticated time, if
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004868 // mUpdateLastAuthenticatedTime is true and the confirmRequest
4869 // or updateRequest was successful
Carlos Valdivia91979be2015-05-22 14:11:35 -07004870 boolean needUpdate = mUpdateLastAuthenticatedTime
Simranjit Singh Kohli0b8a7c02015-06-19 12:45:27 -07004871 && (isSuccessfulConfirmCreds || isSuccessfulUpdateCredsOrAddAccount);
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004872 if (needUpdate || mAuthDetailsRequired) {
4873 boolean accountPresent = isAccountPresentForCaller(mAccountName, mAccountType);
4874 if (needUpdate && accountPresent) {
4875 updateLastAuthenticatedTime(new Account(mAccountName, mAccountType));
4876 }
4877 if (mAuthDetailsRequired) {
4878 long lastAuthenticatedTime = -1;
4879 if (accountPresent) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07004880 lastAuthenticatedTime = mAccounts.accountsDb
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004881 .findAccountLastAuthenticatedTime(
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07004882 new Account(mAccountName, mAccountType));
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004883 }
Simranjit Singh Kohli1663b442015-04-28 11:11:12 -07004884 result.putLong(AccountManager.KEY_LAST_AUTHENTICATED_TIME,
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07004885 lastAuthenticatedTime);
4886 }
4887 }
Simranjit Singh Kohli6c7c4ad2015-02-23 18:11:14 -08004888 }
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004889 if (result != null
4890 && (intent = result.getParcelable(AccountManager.KEY_INTENT)) != null) {
Carlos Valdivia6ede9c32016-03-10 20:12:32 -08004891 checkKeyIntent(
4892 Binder.getCallingUid(),
4893 intent);
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07004894 }
4895 if (result != null
4896 && !TextUtils.isEmpty(result.getString(AccountManager.KEY_AUTHTOKEN))) {
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004897 String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
4898 String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004899 if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) {
4900 Account account = new Account(accountName, accountType);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004901 cancelNotification(getSigninRequiredNotificationId(mAccounts, account),
4902 new UserHandle(mAccounts.userId));
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07004903 }
Fred Quintana60307342009-03-24 22:48:12 -07004904 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004905 IAccountManagerResponse response;
4906 if (mExpectActivityLaunch && result != null
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004907 && result.containsKey(AccountManager.KEY_INTENT)) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004908 response = mResponse;
4909 } else {
4910 response = getResponseAndClose();
Fred Quintana60307342009-03-24 22:48:12 -07004911 }
Fred Quintana60307342009-03-24 22:48:12 -07004912 if (response != null) {
4913 try {
Fred Quintanaa698f422009-04-08 19:14:54 -07004914 if (result == null) {
Fred Quintana56285a62010-12-02 14:20:51 -08004915 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4916 Log.v(TAG, getClass().getSimpleName()
4917 + " calling onError() on response " + response);
4918 }
Fred Quintanaf7ae77c2009-10-02 17:19:31 -07004919 response.onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
Fred Quintanaa698f422009-04-08 19:14:54 -07004920 "null bundle returned");
4921 } else {
Fred Quintana8570f742010-02-18 10:32:54 -08004922 if (mStripAuthTokenFromResult) {
4923 result.remove(AccountManager.KEY_AUTHTOKEN);
4924 }
Fred Quintana56285a62010-12-02 14:20:51 -08004925 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4926 Log.v(TAG, getClass().getSimpleName()
4927 + " calling onResult() on response " + response);
4928 }
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004929 if ((result.getInt(AccountManager.KEY_ERROR_CODE, -1) > 0) &&
4930 (intent == null)) {
4931 // All AccountManager error codes are greater than 0
4932 response.onError(result.getInt(AccountManager.KEY_ERROR_CODE),
4933 result.getString(AccountManager.KEY_ERROR_MESSAGE));
4934 } else {
4935 response.onResult(result);
4936 }
Fred Quintanaa698f422009-04-08 19:14:54 -07004937 }
Fred Quintana60307342009-03-24 22:48:12 -07004938 } catch (RemoteException e) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004939 // if the caller is dead then there is no one to care about remote exceptions
4940 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4941 Log.v(TAG, "failure while notifying response", e);
4942 }
Fred Quintana60307342009-03-24 22:48:12 -07004943 }
4944 }
4945 }
Fred Quintana60307342009-03-24 22:48:12 -07004946
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004947 @Override
Fred Quintanaa698f422009-04-08 19:14:54 -07004948 public void onRequestContinued() {
4949 mNumRequestContinued++;
Fred Quintana60307342009-03-24 22:48:12 -07004950 }
4951
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08004952 @Override
Fred Quintana60307342009-03-24 22:48:12 -07004953 public void onError(int errorCode, String errorMessage) {
Fred Quintanaa698f422009-04-08 19:14:54 -07004954 mNumErrors++;
Fred Quintanaa698f422009-04-08 19:14:54 -07004955 IAccountManagerResponse response = getResponseAndClose();
4956 if (response != null) {
4957 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Fred Quintana56285a62010-12-02 14:20:51 -08004958 Log.v(TAG, getClass().getSimpleName()
4959 + " calling onError() on response " + response);
Fred Quintanaa698f422009-04-08 19:14:54 -07004960 }
4961 try {
4962 response.onError(errorCode, errorMessage);
4963 } catch (RemoteException e) {
4964 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4965 Log.v(TAG, "Session.onError: caught RemoteException while responding", e);
4966 }
4967 }
4968 } else {
4969 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4970 Log.v(TAG, "Session.onError: already closed");
4971 }
Fred Quintana60307342009-03-24 22:48:12 -07004972 }
4973 }
Fred Quintanab839afc2009-10-14 15:57:28 -07004974
4975 /**
4976 * find the component name for the authenticator and initiate a bind
4977 * if no authenticator or the bind fails then return false, otherwise return true
4978 */
4979 private boolean bindToAuthenticator(String authenticatorType) {
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07004980 final AccountAuthenticatorCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
4981 authenticatorInfo = mAuthenticatorCache.getServiceInfo(
4982 AuthenticatorDescription.newKey(authenticatorType), mAccounts.userId);
Fred Quintanab839afc2009-10-14 15:57:28 -07004983 if (authenticatorInfo == null) {
4984 if (Log.isLoggable(TAG, Log.VERBOSE)) {
4985 Log.v(TAG, "there is no authenticator for " + authenticatorType
4986 + ", bailing out");
4987 }
4988 return false;
4989 }
4990
Jeff Sharkeyce18c812016-04-27 16:00:41 -06004991 if (!isLocalUnlockedUser(mAccounts.userId)
Jeff Sharkey8a372a02016-03-16 16:25:45 -06004992 && !authenticatorInfo.componentInfo.directBootAware) {
Jeff Sharkey9d8a1042015-12-03 17:56:20 -07004993 Slog.w(TAG, "Blocking binding to authenticator " + authenticatorInfo.componentName
4994 + " which isn't encryption aware");
4995 return false;
4996 }
4997
Fred Quintanab839afc2009-10-14 15:57:28 -07004998 Intent intent = new Intent();
4999 intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
5000 intent.setComponent(authenticatorInfo.componentName);
5001 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5002 Log.v(TAG, "performing bindService to " + authenticatorInfo.componentName);
5003 }
Amith Yamasani27b89e62013-01-16 12:30:11 -08005004 if (!mContext.bindServiceAsUser(intent, this, Context.BIND_AUTO_CREATE,
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005005 UserHandle.of(mAccounts.userId))) {
Fred Quintanab839afc2009-10-14 15:57:28 -07005006 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5007 Log.v(TAG, "bindService to " + authenticatorInfo.componentName + " failed");
5008 }
5009 return false;
5010 }
5011
Fred Quintanab839afc2009-10-14 15:57:28 -07005012 return true;
5013 }
Fred Quintana60307342009-03-24 22:48:12 -07005014 }
5015
Svet Ganov5d09c992016-09-07 09:57:41 -07005016 class MessageHandler extends Handler {
Fred Quintana60307342009-03-24 22:48:12 -07005017 MessageHandler(Looper looper) {
5018 super(looper);
5019 }
Costin Manolache3348f142009-09-29 18:58:36 -07005020
Carlos Valdivia5bab9da2013-09-29 05:11:56 -07005021 @Override
Fred Quintana60307342009-03-24 22:48:12 -07005022 public void handleMessage(Message msg) {
Fred Quintana60307342009-03-24 22:48:12 -07005023 switch (msg.what) {
5024 case MESSAGE_TIMED_OUT:
5025 Session session = (Session)msg.obj;
5026 session.onTimedOut();
5027 break;
5028
Amith Yamasani5be347b2013-03-31 17:44:31 -07005029 case MESSAGE_COPY_SHARED_ACCOUNT:
Esteban Talavera22dc3b72014-10-31 15:41:12 +00005030 copyAccountToUser(/*no response*/ null, (Account) msg.obj, msg.arg1, msg.arg2);
Amith Yamasani5be347b2013-03-31 17:44:31 -07005031 break;
5032
Fred Quintana60307342009-03-24 22:48:12 -07005033 default:
5034 throw new IllegalStateException("unhandled message: " + msg.what);
5035 }
5036 }
5037 }
5038
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005039 private void logRecord(UserAccounts accounts, String action, String tableName) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005040 logRecord(action, tableName, -1, accounts);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005041 }
5042
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005043 private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005044 logRecord(action, tableName, -1, accounts, uid);
Simranjit Singh Kohliba0b10a2015-07-16 20:33:14 -07005045 }
5046
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005047 /*
5048 * This function receives an opened writable database.
5049 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005050 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005051 UserAccounts userAccount) {
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005052 logRecord(action, tableName, accountId, userAccount, getCallingUid());
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005053 }
5054
5055 /*
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005056 * This function receives an opened writable database and writes to it in a separate thread.
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005057 */
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005058 private void logRecord(String action, String tableName, long accountId,
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005059 UserAccounts userAccount, int callingUid) {
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005060
5061 class LogRecordTask implements Runnable {
5062 private final String action;
5063 private final String tableName;
5064 private final long accountId;
5065 private final UserAccounts userAccount;
5066 private final int callingUid;
5067 private final long userDebugDbInsertionPoint;
5068
5069 LogRecordTask(final String action,
5070 final String tableName,
5071 final long accountId,
5072 final UserAccounts userAccount,
5073 final int callingUid,
5074 final long userDebugDbInsertionPoint) {
5075 this.action = action;
5076 this.tableName = tableName;
5077 this.accountId = accountId;
5078 this.userAccount = userAccount;
5079 this.callingUid = callingUid;
5080 this.userDebugDbInsertionPoint = userDebugDbInsertionPoint;
5081 }
5082
Andrew Scullc7770d62017-05-22 17:49:58 +01005083 @Override
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005084 public void run() {
5085 SQLiteStatement logStatement = userAccount.statementForLogging;
5086 logStatement.bindLong(1, accountId);
5087 logStatement.bindString(2, action);
Fyodor Kupolov1ce01612016-08-26 11:39:07 -07005088 logStatement.bindString(3, mDateFormat.format(new Date()));
Tejas Khorana7b88f0e2016-06-13 13:06:35 -07005089 logStatement.bindLong(4, callingUid);
5090 logStatement.bindString(5, tableName);
5091 logStatement.bindLong(6, userDebugDbInsertionPoint);
5092 logStatement.execute();
5093 logStatement.clearBindings();
5094 }
5095 }
5096
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07005097 LogRecordTask logTask = new LogRecordTask(action, tableName, accountId, userAccount,
5098 callingUid, userAccount.debugDbInsertionPoint);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005099 userAccount.debugDbInsertionPoint = (userAccount.debugDbInsertionPoint + 1)
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005100 % AccountsDb.MAX_DEBUG_DB_SIZE;
Fyodor Kupolov8873aa32016-08-25 15:25:40 -07005101 mHandler.post(logTask);
Simranjit Singh Kohli1d0c1a62015-04-09 13:58:44 -07005102 }
5103
5104 /*
5105 * This should only be called once to compile the sql statement for logging
5106 * and to find the insertion point.
5107 */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005108 private void initializeDebugDbSizeAndCompileSqlStatementForLogging(UserAccounts userAccount) {
5109 userAccount.debugDbInsertionPoint = userAccount.accountsDb
5110 .calculateDebugTableInsertionPoint();
5111 userAccount.statementForLogging = userAccount.accountsDb.compileSqlStatementForLogging();
Fyodor Kupolovef73aaa2016-03-25 10:23:42 -07005112 }
5113
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005114 public IBinder onBind(@SuppressWarnings("unused") Intent intent) {
Fred Quintana60307342009-03-24 22:48:12 -07005115 return asBinder();
5116 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005117
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005118 /**
5119 * Searches array of arguments for the specified string
5120 * @param args array of argument strings
5121 * @param value value to search for
5122 * @return true if the value is contained in the array
5123 */
5124 private static boolean scanArgs(String[] args, String value) {
5125 if (args != null) {
5126 for (String arg : args) {
5127 if (value.equals(arg)) {
5128 return true;
5129 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005130 }
5131 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005132 return false;
5133 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005134
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005135 @Override
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005136 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06005137 if (!DumpUtils.checkDumpPermission(mContext, TAG, fout)) return;
Amith Yamasani04e0d262012-02-14 11:50:53 -08005138 final boolean isCheckinRequest = scanArgs(args, "--checkin") || scanArgs(args, "-c");
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005139 final IndentingPrintWriter ipw = new IndentingPrintWriter(fout, " ");
Kenny Root3abd75b2011-09-29 11:00:41 -07005140
Jeff Sharkey6eb96202012-10-10 13:13:54 -07005141 final List<UserInfo> users = getUserManager().getUsers();
5142 for (UserInfo user : users) {
5143 ipw.println("User " + user + ":");
5144 ipw.increaseIndent();
5145 dumpUser(getUserAccounts(user.id), fd, ipw, args, isCheckinRequest);
5146 ipw.println();
5147 ipw.decreaseIndent();
Amith Yamasani04e0d262012-02-14 11:50:53 -08005148 }
5149 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005150
Amith Yamasani04e0d262012-02-14 11:50:53 -08005151 private void dumpUser(UserAccounts userAccounts, FileDescriptor fd, PrintWriter fout,
5152 String[] args, boolean isCheckinRequest) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005153 if (isCheckinRequest) {
5154 // This is a checkin request. *Only* upload the account types and the count of
5155 // each.
5156 synchronized (userAccounts.dbLock) {
5157 userAccounts.accountsDb.dumpDeAccountsTable(fout);
5158 }
5159 } else {
5160 Account[] accounts = getAccountsFromCache(userAccounts, null /* type */,
5161 Process.SYSTEM_UID, null /* packageName */, false);
5162 fout.println("Accounts: " + accounts.length);
5163 for (Account account : accounts) {
5164 fout.println(" " + account);
5165 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005166
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005167 // Add debug information.
5168 fout.println();
5169 synchronized (userAccounts.dbLock) {
5170 userAccounts.accountsDb.dumpDebugTable(fout);
5171 }
5172 fout.println();
5173 synchronized (mSessions) {
5174 final long now = SystemClock.elapsedRealtime();
5175 fout.println("Active Sessions: " + mSessions.size());
5176 for (Session session : mSessions.values()) {
5177 fout.println(" " + session.toDebugString(now));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005178 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005179 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005180
5181 fout.println();
5182 mAuthenticatorCache.dump(fd, fout, args, userAccounts.userId);
Tony Mak6d14d772017-07-13 17:49:46 +08005183
5184 boolean isUserUnlocked;
5185 synchronized (mUsers) {
5186 isUserUnlocked = isLocalUnlockedUser(userAccounts.userId);
5187 }
5188 // Following logs are printed only when user is unlocked.
5189 if (!isUserUnlocked) {
5190 return;
5191 }
5192 fout.println();
5193 synchronized (userAccounts.dbLock) {
5194 Map<Account, Map<String, Integer>> allVisibilityValues =
5195 userAccounts.accountsDb.findAllVisibilityValues();
5196 fout.println("Account visibility:");
5197 for (Account account : allVisibilityValues.keySet()) {
5198 fout.println(" " + account.name);
5199 Map<String, Integer> visibilities = allVisibilityValues.get(account);
5200 for (Entry<String, Integer> entry : visibilities.entrySet()) {
5201 fout.println(" " + entry.getKey() + ", " + entry.getValue());
5202 }
5203 }
5204 }
Jason Parks1cd7d0e2009-09-28 14:48:34 -07005205 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005206 }
5207
Amith Yamasani04e0d262012-02-14 11:50:53 -08005208 private void doNotification(UserAccounts accounts, Account account, CharSequence message,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005209 Intent intent, String packageName, final int userId) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005210 long identityToken = clearCallingIdentity();
5211 try {
5212 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5213 Log.v(TAG, "doNotification: " + message + " intent:" + intent);
5214 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005215
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005216 if (intent.getComponent() != null &&
5217 GrantCredentialsPermissionActivity.class.getName().equals(
5218 intent.getComponent().getClassName())) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005219 createNoCredentialsPermissionNotification(account, intent, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005220 } else {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005221 Context contextForUser = getContextForUser(new UserHandle(userId));
Chris Wren717a8812017-03-31 15:34:39 -04005222 final NotificationId id = getSigninRequiredNotificationId(accounts, account);
5223 intent.addCategory(id.mTag);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005224
Fred Quintana33f889a2009-09-14 17:31:26 -07005225 final String notificationTitleFormat =
Kenny Guy07ad8dc2014-09-01 20:56:12 +01005226 contextForUser.getText(R.string.notification_title).toString();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05005227 Notification n =
5228 new Notification.Builder(contextForUser, SystemNotificationChannels.ACCOUNT)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005229 .setWhen(0)
5230 .setSmallIcon(android.R.drawable.stat_sys_warning)
5231 .setColor(contextForUser.getColor(
5232 com.android.internal.R.color.system_notification_accent_color))
5233 .setContentTitle(String.format(notificationTitleFormat, account.name))
5234 .setContentText(message)
5235 .setContentIntent(PendingIntent.getActivityAsUser(
5236 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005237 null, new UserHandle(userId)))
Chris Wren1ce4b6d2015-06-11 10:19:43 -04005238 .build();
Chris Wren717a8812017-03-31 15:34:39 -04005239 installNotification(id, n, packageName, userId);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005240 }
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005241 } finally {
5242 restoreCallingIdentity(identityToken);
5243 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005244 }
5245
Chris Wren717a8812017-03-31 15:34:39 -04005246 private void installNotification(NotificationId id, final Notification notification,
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005247 String packageName, int userId) {
5248 final long token = clearCallingIdentity();
5249 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005250 INotificationManager notificationManager = mInjector.getNotificationManager();
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005251 try {
Chris Wren717a8812017-03-31 15:34:39 -04005252 notificationManager.enqueueNotificationWithTag(packageName, packageName,
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04005253 id.mTag, id.mId, notification, userId);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005254 } catch (RemoteException e) {
5255 /* ignore - local call */
5256 }
5257 } finally {
5258 Binder.restoreCallingIdentity(token);
5259 }
Fred Quintana56285a62010-12-02 14:20:51 -08005260 }
5261
Chris Wren717a8812017-03-31 15:34:39 -04005262 private void cancelNotification(NotificationId id, UserHandle user) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005263 cancelNotification(id, mContext.getPackageName(), user);
5264 }
5265
Chris Wren717a8812017-03-31 15:34:39 -04005266 private void cancelNotification(NotificationId id, String packageName, UserHandle user) {
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005267 long identityToken = clearCallingIdentity();
5268 try {
Fyodor Kupolovda993802016-09-21 14:47:10 -07005269 INotificationManager service = mInjector.getNotificationManager();
Chris Wren717a8812017-03-31 15:34:39 -04005270 service.cancelNotificationWithTag(packageName, id.mTag, id.mId, user.getIdentifier());
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005271 } catch (RemoteException e) {
5272 /* ignore - local call */
Fred Quintana26fc5eb2009-04-09 15:05:50 -07005273 } finally {
5274 restoreCallingIdentity(identityToken);
5275 }
Fred Quintanaa698f422009-04-08 19:14:54 -07005276 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005277
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005278 private boolean isPermittedForPackage(String packageName, int uid, int userId,
5279 String... permissions) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005280 final long identity = Binder.clearCallingIdentity();
5281 try {
5282 IPackageManager pm = ActivityThread.getPackageManager();
5283 for (String perm : permissions) {
5284 if (pm.checkPermission(perm, packageName, userId)
5285 == PackageManager.PERMISSION_GRANTED) {
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005286 // Checks runtime permission revocation.
5287 final int opCode = AppOpsManager.permissionToOpCode(perm);
5288 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5289 opCode, uid, packageName) == AppOpsManager.MODE_ALLOWED) {
5290 return true;
5291 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005292 }
5293 }
5294 } catch (RemoteException e) {
5295 /* ignore - local call */
5296 } finally {
5297 Binder.restoreCallingIdentity(identity);
5298 }
5299 return false;
5300 }
5301
Ian Pedowitz358e51f2016-03-15 17:08:27 +00005302 private boolean isPermitted(String opPackageName, int callingUid, String... permissions) {
5303 for (String perm : permissions) {
5304 if (mContext.checkCallingOrSelfPermission(perm) == PackageManager.PERMISSION_GRANTED) {
5305 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5306 Log.v(TAG, " caller uid " + callingUid + " has " + perm);
5307 }
5308 final int opCode = AppOpsManager.permissionToOpCode(perm);
5309 if (opCode == AppOpsManager.OP_NONE || mAppOpsManager.noteOp(
5310 opCode, callingUid, opPackageName) == AppOpsManager.MODE_ALLOWED) {
5311 return true;
5312 }
5313 }
5314 }
5315 return false;
5316 }
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005317
Amith Yamasani67df64b2012-12-14 12:09:36 -08005318 private int handleIncomingUser(int userId) {
5319 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08005320 return ActivityManager.getService().handleIncomingUser(
Amith Yamasani67df64b2012-12-14 12:09:36 -08005321 Binder.getCallingPid(), Binder.getCallingUid(), userId, true, true, "", null);
5322 } catch (RemoteException re) {
5323 // Shouldn't happen, local.
5324 }
5325 return userId;
5326 }
5327
Christopher Tateccbf84f2013-05-08 15:25:41 -07005328 private boolean isPrivileged(int callingUid) {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005329 String[] packages;
5330 long identityToken = Binder.clearCallingIdentity();
Jeff Sharkey6ab72d72012-10-08 16:44:37 -07005331 try {
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005332 packages = mPackageManager.getPackagesForUid(callingUid);
sunjian9ae597b62017-08-14 15:45:04 -07005333 if (packages == null) {
5334 Log.d(TAG, "No packages for callingUid " + callingUid);
Fred Quintana7be59642009-08-24 18:29:25 -07005335 return false;
5336 }
sunjian9ae597b62017-08-14 15:45:04 -07005337 for (String name : packages) {
5338 try {
5339 PackageInfo packageInfo =
5340 mPackageManager.getPackageInfo(name, 0 /* flags */);
5341 if (packageInfo != null
5342 && (packageInfo.applicationInfo.privateFlags
5343 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5344 return true;
5345 }
5346 } catch (PackageManager.NameNotFoundException e) {
5347 Log.d(TAG, "Package not found " + e.getMessage());
5348 }
5349 }
5350 } finally {
5351 Binder.restoreCallingIdentity(identityToken);
Fred Quintana7be59642009-08-24 18:29:25 -07005352 }
5353 return false;
5354 }
5355
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005356 private boolean permissionIsGranted(
5357 Account account, String authTokenType, int callerUid, int userId) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005358 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
5359 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5360 Log.v(TAG, "Access to " + account + " granted calling uid is system");
5361 }
5362 return true;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005363 }
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005364
5365 if (isPrivileged(callerUid)) {
5366 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5367 Log.v(TAG, "Access to " + account + " granted calling uid "
5368 + callerUid + " privileged");
5369 }
5370 return true;
5371 }
5372 if (account != null && isAccountManagedByCaller(account.type, callerUid, userId)) {
5373 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5374 Log.v(TAG, "Access to " + account + " granted calling uid "
5375 + callerUid + " manages the account");
5376 }
5377 return true;
5378 }
5379 if (account != null && hasExplicitlyGrantedPermission(account, authTokenType, callerUid)) {
5380 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5381 Log.v(TAG, "Access to " + account + " granted calling uid "
5382 + callerUid + " user granted access");
5383 }
5384 return true;
5385 }
5386
5387 if (Log.isLoggable(TAG, Log.VERBOSE)) {
5388 Log.v(TAG, "Access to " + account + " not granted for uid " + callerUid);
5389 }
5390
5391 return false;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005392 }
5393
Svetoslavf3f02ac2015-09-08 14:36:35 -07005394 private boolean isAccountVisibleToCaller(String accountType, int callingUid, int userId,
5395 String opPackageName) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005396 if (accountType == null) {
5397 return false;
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005398 } else {
Svetoslavf3f02ac2015-09-08 14:36:35 -07005399 return getTypesVisibleToCaller(callingUid, userId,
5400 opPackageName).contains(accountType);
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005401 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005402 }
5403
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005404 // Method checks visibility for applications targeing API level below {@link
5405 // android.os.Build.VERSION_CODES#O},
Dmitry Dementyeve366f822017-01-31 10:25:10 -08005406 // returns true if the the app has GET_ACCOUNTS or GET_ACCOUNTS_PRIVILEGED permission.
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005407 private boolean checkGetAccountsPermission(String packageName, int uid, int userId) {
5408 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.GET_ACCOUNTS,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005409 Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
5410 }
5411
Dmitry Dementyevd6f06722017-04-05 12:43:26 -07005412 private boolean checkReadContactsPermission(String packageName, int uid, int userId) {
5413 return isPermittedForPackage(packageName, uid, userId, Manifest.permission.READ_CONTACTS);
5414 }
5415
5416 // Heuristic to check that account type may be associated with some contacts data and
5417 // therefore READ_CONTACTS permission grants the access to account by default.
5418 private boolean accountTypeManagesContacts(String accountType, int userId) {
5419 if (accountType == null) {
5420 return false;
5421 }
5422 long identityToken = Binder.clearCallingIdentity();
5423 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5424 try {
5425 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5426 } finally {
5427 Binder.restoreCallingIdentity(identityToken);
5428 }
5429 // Check contacts related permissions for authenticator.
5430 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5431 : serviceInfos) {
5432 if (accountType.equals(serviceInfo.type.type)) {
5433 return isPermittedForPackage(serviceInfo.type.packageName, serviceInfo.uid, userId,
5434 Manifest.permission.WRITE_CONTACTS);
5435 }
5436 }
5437 return false;
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005438 }
5439
5440 /**
5441 * Method checks package uid and signature with Authenticator which manages accountType.
5442 *
5443 * @return SIGNATURE_CHECK_UID_MATCH for uid match, SIGNATURE_CHECK_MATCH for signature match,
5444 * SIGNATURE_CHECK_MISMATCH otherwise.
5445 */
5446 private int checkPackageSignature(String accountType, int callingUid, int userId) {
5447 if (accountType == null) {
5448 return SIGNATURE_CHECK_MISMATCH;
5449 }
5450
5451 long identityToken = Binder.clearCallingIdentity();
5452 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5453 try {
5454 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5455 } finally {
5456 Binder.restoreCallingIdentity(identityToken);
5457 }
5458 // Check for signature match with Authenticator.
5459 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo
5460 : serviceInfos) {
5461 if (accountType.equals(serviceInfo.type.type)) {
5462 if (serviceInfo.uid == callingUid) {
5463 return SIGNATURE_CHECK_UID_MATCH;
5464 }
5465 final int sigChk = mPackageManager.checkSignatures(serviceInfo.uid, callingUid);
5466 if (sigChk == PackageManager.SIGNATURE_MATCH) {
5467 return SIGNATURE_CHECK_MATCH;
5468 }
5469 }
5470 }
5471 return SIGNATURE_CHECK_MISMATCH;
5472 }
5473
5474 // returns true for applications with the same signature as authenticator.
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005475 private boolean isAccountManagedByCaller(String accountType, int callingUid, int userId) {
5476 if (accountType == null) {
5477 return false;
5478 } else {
5479 return getTypesManagedByCaller(callingUid, userId).contains(accountType);
5480 }
5481 }
5482
Svetoslavf3f02ac2015-09-08 14:36:35 -07005483 private List<String> getTypesVisibleToCaller(int callingUid, int userId,
5484 String opPackageName) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005485 return getTypesForCaller(callingUid, userId, true /* isOtherwisePermitted*/);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005486 }
5487
5488 private List<String> getTypesManagedByCaller(int callingUid, int userId) {
Dmitry Dementyev2e22cfb2017-01-09 18:42:14 +00005489 return getTypesForCaller(callingUid, userId, false);
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005490 }
5491
5492 private List<String> getTypesForCaller(
5493 int callingUid, int userId, boolean isOtherwisePermitted) {
5494 List<String> managedAccountTypes = new ArrayList<>();
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005495 long identityToken = Binder.clearCallingIdentity();
5496 Collection<RegisteredServicesCache.ServiceInfo<AuthenticatorDescription>> serviceInfos;
5497 try {
5498 serviceInfos = mAuthenticatorCache.getAllServices(userId);
5499 } finally {
5500 Binder.restoreCallingIdentity(identityToken);
5501 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005502 for (RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> serviceInfo :
Simranjit Singh Kohlib77d8b62015-08-07 17:07:23 -07005503 serviceInfos) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005504 if (isOtherwisePermitted || (mPackageManager.checkSignatures(serviceInfo.uid,
5505 callingUid) == PackageManager.SIGNATURE_MATCH)) {
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005506 managedAccountTypes.add(serviceInfo.type.type);
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005507 }
5508 }
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005509 return managedAccountTypes;
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005510 }
5511
Simranjit Singh Kohli82d01782015-04-09 17:27:06 -07005512 private boolean isAccountPresentForCaller(String accountName, String accountType) {
5513 if (getUserAccountsForCaller().accountCache.containsKey(accountType)) {
5514 for (Account account : getUserAccountsForCaller().accountCache.get(accountType)) {
5515 if (account.name.equals(accountName)) {
5516 return true;
5517 }
5518 }
5519 }
5520 return false;
5521 }
5522
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -07005523 private static void checkManageUsersPermission(String message) {
5524 if (ActivityManager.checkComponentPermission(
5525 android.Manifest.permission.MANAGE_USERS, Binder.getCallingUid(), -1, true)
5526 != PackageManager.PERMISSION_GRANTED) {
5527 throw new SecurityException("You need MANAGE_USERS permission to: " + message);
5528 }
5529 }
5530
Sudheer Shanka3b2297d2016-06-20 10:44:30 -07005531 private static void checkManageOrCreateUsersPermission(String message) {
5532 if (ActivityManager.checkComponentPermission(android.Manifest.permission.MANAGE_USERS,
5533 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED &&
5534 ActivityManager.checkComponentPermission(android.Manifest.permission.CREATE_USERS,
5535 Binder.getCallingUid(), -1, true) != PackageManager.PERMISSION_GRANTED) {
5536 throw new SecurityException("You need MANAGE_USERS or CREATE_USERS permission to: "
5537 + message);
5538 }
5539 }
5540
Amith Yamasani04e0d262012-02-14 11:50:53 -08005541 private boolean hasExplicitlyGrantedPermission(Account account, String authTokenType,
5542 int callerUid) {
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005543 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) {
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005544 return true;
5545 }
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005546 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callerUid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005547 synchronized (accounts.dbLock) {
5548 synchronized (accounts.cacheLock) {
5549 long grantsCount;
5550 if (authTokenType != null) {
5551 grantsCount = accounts.accountsDb
5552 .findMatchingGrantsCount(callerUid, authTokenType, account);
5553 } else {
5554 grantsCount = accounts.accountsDb.findMatchingGrantsCountAnyToken(callerUid,
5555 account);
5556 }
5557 final boolean permissionGranted = grantsCount > 0;
Svet Ganov890a2102016-08-24 00:08:00 -07005558
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005559 if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
5560 // TODO: Skip this check when running automated tests. Replace this
5561 // with a more general solution.
5562 Log.d(TAG, "no credentials permission for usage of " + account + ", "
5563 + authTokenType + " by uid " + callerUid
5564 + " but ignoring since device is in test harness.");
5565 return true;
5566 }
5567 return permissionGranted;
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005568 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005569 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005570 }
5571
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005572 private boolean isSystemUid(int callingUid) {
5573 String[] packages = null;
5574 long ident = Binder.clearCallingIdentity();
5575 try {
5576 packages = mPackageManager.getPackagesForUid(callingUid);
5577 } finally {
5578 Binder.restoreCallingIdentity(ident);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005579 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005580 if (packages != null) {
5581 for (String name : packages) {
5582 try {
5583 PackageInfo packageInfo = mPackageManager.getPackageInfo(name, 0 /* flags */);
5584 if (packageInfo != null
5585 && (packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
5586 != 0) {
5587 return true;
5588 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005589 } catch (NameNotFoundException e) {
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005590 Log.w(TAG, String.format("Could not find package [%s]", name), e);
5591 }
5592 }
5593 } else {
5594 Log.w(TAG, "No known packages with uid " + callingUid);
Carlos Valdiviaffb46022015-06-08 19:07:54 -07005595 }
Carlos Valdivia6eb73a52015-06-11 13:07:11 -07005596 return false;
Carlos Valdiviadcddc472015-06-11 20:04:04 +00005597 }
5598
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005599 /** Succeeds if any of the specified permissions are granted. */
5600 private void checkReadAccountsPermitted(
5601 int callingUid,
Ian Pedowitz6cc066d2015-08-05 14:23:43 +00005602 String accountType,
Svetoslavf3f02ac2015-09-08 14:36:35 -07005603 int userId,
5604 String opPackageName) {
5605 if (!isAccountVisibleToCaller(accountType, callingUid, userId, opPackageName)) {
Carlos Valdiviac37ee222015-06-17 20:17:37 -07005606 String msg = String.format(
5607 "caller uid %s cannot access %s accounts",
5608 callingUid,
5609 accountType);
5610 Log.w(TAG, " " + msg);
5611 throw new SecurityException(msg);
5612 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005613 }
5614
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005615 private boolean canUserModifyAccounts(int userId, int callingUid) {
5616 // the managing app can always modify accounts
5617 if (isProfileOwner(callingUid)) {
5618 return true;
5619 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005620 if (getUserManager().getUserRestrictions(new UserHandle(userId))
5621 .getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
5622 return false;
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005623 }
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005624 return true;
5625 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005626
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005627 private boolean canUserModifyAccountsForType(int userId, String accountType, int callingUid) {
5628 // the managing app can always modify accounts
5629 if (isProfileOwner(callingUid)) {
5630 return true;
5631 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005632 DevicePolicyManager dpm = (DevicePolicyManager) mContext
5633 .getSystemService(Context.DEVICE_POLICY_SERVICE);
Alexandra Gherghina999d3942014-07-03 11:40:08 +01005634 String[] typesArray = dpm.getAccountTypesWithManagementDisabledAsUser(userId);
Adili Muguro4e68b652014-07-25 16:42:39 +02005635 if (typesArray == null) {
5636 return true;
5637 }
Sander Alewijnseda1350f2014-05-08 16:59:42 +01005638 for (String forbiddenType : typesArray) {
5639 if (forbiddenType.equals(accountType)) {
5640 return false;
5641 }
5642 }
Amith Yamasanie4cf7342012-12-17 11:12:09 -08005643 return true;
5644 }
5645
Benjamin Franzb6c0ce42015-11-05 10:06:51 +00005646 private boolean isProfileOwner(int uid) {
5647 final DevicePolicyManagerInternal dpmi =
5648 LocalServices.getService(DevicePolicyManagerInternal.class);
5649 return (dpmi != null)
5650 && dpmi.isActiveAdminWithPolicy(uid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5651 }
5652
Jatin Lodhia09e7e0e2013-11-07 00:14:25 -08005653 @Override
Fred Quintanad9640ec2012-05-23 12:37:00 -07005654 public void updateAppPermission(Account account, String authTokenType, int uid, boolean value)
5655 throws RemoteException {
5656 final int callingUid = getCallingUid();
5657
Svetoslav Ganov7ee37f42016-08-24 14:40:16 -07005658 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) {
Fred Quintanad9640ec2012-05-23 12:37:00 -07005659 throw new SecurityException();
5660 }
5661
5662 if (value) {
5663 grantAppPermission(account, authTokenType, uid);
5664 } else {
5665 revokeAppPermission(account, authTokenType, uid);
5666 }
5667 }
5668
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005669 /**
5670 * Allow callers with the given uid permission to get credentials for account/authTokenType.
5671 * <p>
5672 * Although this is public it can only be accessed via the AccountManagerService object
5673 * which is in the system. This means we don't need to protect it with permissions.
5674 * @hide
5675 */
Svet Ganov5d09c992016-09-07 09:57:41 -07005676 void grantAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005677 if (account == null || authTokenType == null) {
5678 Log.e(TAG, "grantAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005679 return;
5680 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005681 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005682 synchronized (accounts.dbLock) {
5683 synchronized (accounts.cacheLock) {
5684 long accountId = accounts.accountsDb.findDeAccountId(account);
5685 if (accountId >= 0) {
5686 accounts.accountsDb.insertGrant(accountId, authTokenType, uid);
5687 }
5688 cancelNotification(
5689 getCredentialPermissionNotificationId(account, authTokenType, uid),
5690 UserHandle.of(accounts.userId));
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07005691
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005692 cancelAccountAccessRequestNotificationIfNeeded(account, uid, true);
5693 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005694 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005695
5696 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5697 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5698 : mAppPermissionChangeListeners) {
5699 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5700 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005701 }
5702
5703 /**
5704 * Don't allow callers with the given uid permission to get credentials for
5705 * account/authTokenType.
5706 * <p>
5707 * Although this is public it can only be accessed via the AccountManagerService object
5708 * which is in the system. This means we don't need to protect it with permissions.
5709 * @hide
5710 */
Fred Quintanad9640ec2012-05-23 12:37:00 -07005711 private void revokeAppPermission(Account account, String authTokenType, int uid) {
Fred Quintana382601f2010-03-25 12:25:10 -07005712 if (account == null || authTokenType == null) {
5713 Log.e(TAG, "revokeAppPermission: called with invalid arguments", new Exception());
Fred Quintana31957f12009-10-21 13:43:10 -07005714 return;
5715 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005716 UserAccounts accounts = getUserAccounts(UserHandle.getUserId(uid));
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005717 synchronized (accounts.dbLock) {
5718 synchronized (accounts.cacheLock) {
5719 accounts.accountsDb.beginTransaction();
5720 try {
5721 long accountId = accounts.accountsDb.findDeAccountId(account);
5722 if (accountId >= 0) {
5723 accounts.accountsDb.deleteGrantsByAccountIdAuthTokenTypeAndUid(
5724 accountId, authTokenType, uid);
5725 accounts.accountsDb.setTransactionSuccessful();
5726 }
5727 } finally {
5728 accounts.accountsDb.endTransaction();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005729 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005730
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005731 cancelNotification(
5732 getCredentialPermissionNotificationId(account, authTokenType, uid),
5733 UserHandle.of(accounts.userId));
5734 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005735 }
Svet Ganovf6d424f12016-09-20 20:18:53 -07005736
5737 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
5738 for (AccountManagerInternal.OnAppPermissionChangeListener listener
5739 : mAppPermissionChangeListeners) {
5740 mHandler.post(() -> listener.onAppPermissionChanged(account, uid));
5741 }
Fred Quintanad4a1d2e2009-07-16 16:36:38 -07005742 }
Fred Quintana56285a62010-12-02 14:20:51 -08005743
Amith Yamasani04e0d262012-02-14 11:50:53 -08005744 private void removeAccountFromCacheLocked(UserAccounts accounts, Account account) {
5745 final Account[] oldAccountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005746 if (oldAccountsForType != null) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005747 ArrayList<Account> newAccountsList = new ArrayList<>();
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005748 for (Account curAccount : oldAccountsForType) {
5749 if (!curAccount.equals(account)) {
5750 newAccountsList.add(curAccount);
Fred Quintana56285a62010-12-02 14:20:51 -08005751 }
5752 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005753 if (newAccountsList.isEmpty()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005754 accounts.accountCache.remove(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005755 } else {
5756 Account[] newAccountsForType = new Account[newAccountsList.size()];
5757 newAccountsForType = newAccountsList.toArray(newAccountsForType);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005758 accounts.accountCache.put(account.type, newAccountsForType);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005759 }
Fred Quintana56285a62010-12-02 14:20:51 -08005760 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08005761 accounts.userDataCache.remove(account);
5762 accounts.authTokenCache.remove(account);
Carlos Valdiviaf193b9a2014-07-18 01:34:57 -07005763 accounts.previousNameCache.remove(account);
Dmitry Dementyev71fa5262017-03-23 12:29:17 -07005764 accounts.visibilityCache.remove(account);
Fred Quintana56285a62010-12-02 14:20:51 -08005765 }
5766
5767 /**
5768 * This assumes that the caller has already checked that the account is not already present.
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005769 * IMPORTANT: The account being inserted will begin to be tracked for access in remote
5770 * processes and if you will return this account to apps you should return the result.
5771 * @return The inserted account which is a new instance that is being tracked.
Fred Quintana56285a62010-12-02 14:20:51 -08005772 */
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005773 private Account insertAccountIntoCacheLocked(UserAccounts accounts, Account account) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08005774 Account[] accountsForType = accounts.accountCache.get(account.type);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005775 int oldLength = (accountsForType != null) ? accountsForType.length : 0;
5776 Account[] newAccountsForType = new Account[oldLength + 1];
5777 if (accountsForType != null) {
5778 System.arraycopy(accountsForType, 0, newAccountsForType, 0, oldLength);
Fred Quintana56285a62010-12-02 14:20:51 -08005779 }
Svet Ganovc1c0d1c2016-09-23 19:15:47 -07005780 String token = account.getAccessId() != null ? account.getAccessId()
5781 : UUID.randomUUID().toString();
5782 newAccountsForType[oldLength] = new Account(account, token);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005783 accounts.accountCache.put(account.type, newAccountsForType);
Svetoslav Ganov57f62592016-09-16 17:29:05 -07005784 return newAccountsForType[oldLength];
Fred Quintana56285a62010-12-02 14:20:51 -08005785 }
5786
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005787 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005788 private Account[] filterAccounts(UserAccounts accounts, Account[] unfiltered, int callingUid,
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005789 @Nullable String callingPackage, boolean includeManagedNotVisible) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005790 String visibilityFilterPackage = callingPackage;
5791 if (visibilityFilterPackage == null) {
5792 visibilityFilterPackage = getPackageNameForUid(callingUid);
5793 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005794 Map<Account, Integer> firstPass = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005795 for (Account account : unfiltered) {
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005796 int visibility = resolveAccountVisibility(account, visibilityFilterPackage, accounts);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005797 if ((visibility == AccountManager.VISIBILITY_VISIBLE
5798 || visibility == AccountManager.VISIBILITY_USER_MANAGED_VISIBLE)
5799 || (includeManagedNotVisible
5800 && (visibility
5801 == AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE))) {
5802 firstPass.put(account, visibility);
5803 }
5804 }
5805 Map<Account, Integer> secondPass =
5806 filterSharedAccounts(accounts, firstPass, callingUid, callingPackage);
5807
5808 Account[] filtered = new Account[secondPass.size()];
5809 filtered = secondPass.keySet().toArray(filtered);
5810 return filtered;
5811 }
5812
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005813 @NonNull
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005814 private Map<Account, Integer> filterSharedAccounts(UserAccounts userAccounts,
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005815 @NonNull Map<Account, Integer> unfiltered, int callingUid,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005816 @Nullable String callingPackage) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005817 // first part is to filter shared accounts.
5818 // unfiltered type check is not necessary.
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005819 if (getUserManager() == null || userAccounts == null || userAccounts.userId < 0
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005820 || callingUid == Process.SYSTEM_UID) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005821 return unfiltered;
5822 }
Erik Wolsheimerec1a9182016-03-17 10:39:51 -07005823 UserInfo user = getUserManager().getUserInfo(userAccounts.userId);
Amith Yamasani0c19bf52013-10-03 10:34:58 -07005824 if (user != null && user.isRestricted()) {
Dmitry Dementyev16e37892017-03-22 13:13:40 -07005825 String[] packages = mPackageManager.getPackagesForUid(callingUid);
Dmitry Dementyev5e46e572017-02-16 12:25:49 -08005826 if (packages == null) {
5827 packages = new String[] {};
5828 }
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005829 // If any of the packages is a visible listed package, return the full set,
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005830 // otherwise return non-shared accounts only.
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005831 // This might be a temporary way to specify a visible list
5832 String visibleList = mContext.getResources().getString(
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005833 com.android.internal.R.string.config_appsAuthorizedForSharedAccounts);
5834 for (String packageName : packages) {
Tejas Khorana5edff3b2016-06-28 20:59:52 -07005835 if (visibleList.contains(";" + packageName + ";")) {
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005836 return unfiltered;
5837 }
5838 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005839 Account[] sharedAccounts = getSharedAccountsAsUser(userAccounts.userId);
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005840 if (ArrayUtils.isEmpty(sharedAccounts)) {
5841 return unfiltered;
5842 }
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005843 String requiredAccountType = "";
5844 try {
Amith Yamasanie3423092013-05-22 19:41:45 -07005845 // If there's an explicit callingPackage specified, check if that package
5846 // opted in to see restricted accounts.
5847 if (callingPackage != null) {
5848 PackageInfo pi = mPackageManager.getPackageInfo(callingPackage, 0);
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005849 if (pi != null && pi.restrictedAccountType != null) {
5850 requiredAccountType = pi.restrictedAccountType;
Amith Yamasanie3423092013-05-22 19:41:45 -07005851 }
5852 } else {
5853 // Otherwise check if the callingUid has a package that has opted in
5854 for (String packageName : packages) {
5855 PackageInfo pi = mPackageManager.getPackageInfo(packageName, 0);
5856 if (pi != null && pi.restrictedAccountType != null) {
5857 requiredAccountType = pi.restrictedAccountType;
Amith Yamasani27db4682013-03-30 17:07:47 -07005858 break;
5859 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005860 }
5861 }
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005862 } catch (NameNotFoundException e) {
5863 Log.d(TAG, "Package not found " + e.getMessage());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005864 }
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005865 Map<Account, Integer> filtered = new LinkedHashMap<>();
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005866 for (Map.Entry<Account, Integer> entry : unfiltered.entrySet()) {
5867 Account account = entry.getKey();
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005868 if (account.type.equals(requiredAccountType)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005869 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005870 } else {
5871 boolean found = false;
5872 for (Account shared : sharedAccounts) {
5873 if (shared.equals(account)) {
5874 found = true;
5875 break;
5876 }
5877 }
5878 if (!found) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005879 filtered.put(account, entry.getValue());
Amith Yamasani0ac1fc92013-03-27 18:56:08 -07005880 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005881 }
5882 }
Amith Yamasanidf2e92a2013-03-01 17:04:38 -08005883 return filtered;
5884 } else {
5885 return unfiltered;
5886 }
5887 }
5888
Amith Yamasani27db4682013-03-30 17:07:47 -07005889 /*
5890 * packageName can be null. If not null, it should be used to filter out restricted accounts
5891 * that the package is not allowed to access.
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005892 *
5893 * <p>The method shouldn't be called with UserAccounts#cacheLock held, otherwise it will cause a
5894 * deadlock
Amith Yamasani27db4682013-03-30 17:07:47 -07005895 */
Dmitry Dementyevc34a48d2017-03-02 13:53:31 -08005896 @NonNull
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005897 protected Account[] getAccountsFromCache(UserAccounts userAccounts, String accountType,
Dmitry Dementyev5159f432017-03-09 12:59:56 -08005898 int callingUid, @Nullable String callingPackage, boolean includeManagedNotVisible) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005899 Preconditions.checkState(!Thread.holdsLock(userAccounts.cacheLock),
5900 "Method should not be called with cacheLock");
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005901 if (accountType != null) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005902 Account[] accounts;
5903 synchronized (userAccounts.cacheLock) {
5904 accounts = userAccounts.accountCache.get(accountType);
5905 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005906 if (accounts == null) {
5907 return EMPTY_ACCOUNT_ARRAY;
Fred Quintana56285a62010-12-02 14:20:51 -08005908 } else {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005909 return filterAccounts(userAccounts, Arrays.copyOf(accounts, accounts.length),
5910 callingUid, callingPackage, includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005911 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005912 } else {
5913 int totalLength = 0;
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005914 Account[] accountsArray;
5915 synchronized (userAccounts.cacheLock) {
5916 for (Account[] accounts : userAccounts.accountCache.values()) {
5917 totalLength += accounts.length;
5918 }
5919 if (totalLength == 0) {
5920 return EMPTY_ACCOUNT_ARRAY;
5921 }
5922 accountsArray = new Account[totalLength];
5923 totalLength = 0;
5924 for (Account[] accountsOfType : userAccounts.accountCache.values()) {
5925 System.arraycopy(accountsOfType, 0, accountsArray, totalLength,
5926 accountsOfType.length);
5927 totalLength += accountsOfType.length;
5928 }
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005929 }
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005930 return filterAccounts(userAccounts, accountsArray, callingUid, callingPackage,
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08005931 includeManagedNotVisible);
Fred Quintana56285a62010-12-02 14:20:51 -08005932 }
5933 }
5934
Fyodor Kupolov3d734992017-03-29 17:28:52 -07005935 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005936 protected void writeUserDataIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005937 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005938 Map<String, String> userDataForAccount = accounts.userDataCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005939 if (userDataForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005940 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005941 accounts.userDataCache.put(account, userDataForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005942 }
5943 if (value == null) {
5944 userDataForAccount.remove(key);
5945 } else {
5946 userDataForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005947 }
5948 }
5949
Carlos Valdivia91979be2015-05-22 14:11:35 -07005950 protected String readCachedTokenInternal(
5951 UserAccounts accounts,
5952 Account account,
5953 String tokenType,
5954 String callingPackage,
5955 byte[] pkgSigDigest) {
Dmitry Dementyev18f0ca92017-06-12 17:56:47 -07005956 synchronized (accounts.cacheLock) {
5957 return accounts.accountTokenCaches.get(
5958 account, tokenType, callingPackage, pkgSigDigest);
Carlos Valdivia91979be2015-05-22 14:11:35 -07005959 }
5960 }
5961
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005962 /** protected by the {@code dbLock}, {@code cacheLock} */
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005963 protected void writeAuthTokenIntoCacheLocked(UserAccounts accounts,
Amith Yamasani04e0d262012-02-14 11:50:53 -08005964 Account account, String key, String value) {
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07005965 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005966 if (authTokensForAccount == null) {
Fyodor Kupolov00de49e2016-09-23 13:10:27 -07005967 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
Amith Yamasani04e0d262012-02-14 11:50:53 -08005968 accounts.authTokenCache.put(account, authTokensForAccount);
Fred Quintanaf9f240e2011-02-24 18:27:50 -08005969 }
5970 if (value == null) {
5971 authTokensForAccount.remove(key);
5972 } else {
5973 authTokensForAccount.put(key, value);
Fred Quintana56285a62010-12-02 14:20:51 -08005974 }
5975 }
5976
Amith Yamasani04e0d262012-02-14 11:50:53 -08005977 protected String readAuthTokenInternal(UserAccounts accounts, Account account,
5978 String authTokenType) {
Fyodor Kupolov9ac40f12017-03-28 19:11:17 -07005979 // Fast path - check if account is already cached
5980 synchronized (accounts.cacheLock) {
5981 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5982 if (authTokensForAccount != null) {
5983 return authTokensForAccount.get(authTokenType);
5984 }
5985 }
5986 // If not cached yet - do slow path and sync with db if necessary
Fyodor Kupolov8cd927d2017-03-27 17:02:11 -07005987 synchronized (accounts.dbLock) {
5988 synchronized (accounts.cacheLock) {
5989 Map<String, String> authTokensForAccount = accounts.authTokenCache.get(account);
5990 if (authTokensForAccount == null) {
5991 // need to populate the cache for this account
5992 authTokensForAccount = accounts.accountsDb.findAuthTokensByAccount(account);
5993 accounts.authTokenCache.put(account, authTokensForAccount);
5994 }
5995 return authTokensForAccount.get(authTokenType);
Fred Quintana56285a62010-12-02 14:20:51 -08005996 }
Fred Quintana56285a62010-12-02 14:20:51 -08005997 }
5998 }
5999
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006000 private String readUserDataInternal(UserAccounts accounts, Account account, String key) {
6001 Map<String, String> userDataForAccount;
6002 // Fast path - check if data is already cached
6003 synchronized (accounts.cacheLock) {
6004 userDataForAccount = accounts.userDataCache.get(account);
6005 }
6006 // If not cached yet - do slow path and sync with db if necessary
Simranjit Kohli858511c2016-03-10 18:36:11 +00006007 if (userDataForAccount == null) {
Fyodor Kupolov3d734992017-03-29 17:28:52 -07006008 synchronized (accounts.dbLock) {
6009 synchronized (accounts.cacheLock) {
6010 userDataForAccount = accounts.userDataCache.get(account);
6011 if (userDataForAccount == null) {
6012 // need to populate the cache for this account
6013 userDataForAccount = accounts.accountsDb.findUserExtrasForAccount(account);
6014 accounts.userDataCache.put(account, userDataForAccount);
6015 }
6016 }
6017 }
Fred Quintana56285a62010-12-02 14:20:51 -08006018 }
Simranjit Kohli858511c2016-03-10 18:36:11 +00006019 return userDataForAccount.get(key);
Fred Quintana56285a62010-12-02 14:20:51 -08006020 }
6021
Kenny Guy07ad8dc2014-09-01 20:56:12 +01006022 private Context getContextForUser(UserHandle user) {
6023 try {
6024 return mContext.createPackageContextAsUser(mContext.getPackageName(), 0, user);
6025 } catch (NameNotFoundException e) {
6026 // Default to mContext, not finding the package system is running as is unlikely.
6027 return mContext;
6028 }
6029 }
Sandra Kwan78812282015-11-04 11:19:47 -08006030
6031 private void sendResponse(IAccountManagerResponse response, Bundle result) {
6032 try {
6033 response.onResult(result);
6034 } catch (RemoteException e) {
6035 // if the caller is dead then there is no one to care about remote
6036 // exceptions
6037 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6038 Log.v(TAG, "failure while notifying response", e);
6039 }
6040 }
6041 }
6042
6043 private void sendErrorResponse(IAccountManagerResponse response, int errorCode,
6044 String errorMessage) {
6045 try {
6046 response.onError(errorCode, errorMessage);
6047 } catch (RemoteException e) {
6048 // if the caller is dead then there is no one to care about remote
6049 // exceptions
6050 if (Log.isLoggable(TAG, Log.VERBOSE)) {
6051 Log.v(TAG, "failure while notifying response", e);
6052 }
6053 }
6054 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006055
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006056 private final class AccountManagerInternalImpl extends AccountManagerInternal {
Svet Ganov5d09c992016-09-07 09:57:41 -07006057 private final Object mLock = new Object();
6058
6059 @GuardedBy("mLock")
6060 private AccountManagerBackupHelper mBackupHelper;
6061
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006062 @Override
6063 public void requestAccountAccess(@NonNull Account account, @NonNull String packageName,
6064 @IntRange(from = 0) int userId, @NonNull RemoteCallback callback) {
6065 if (account == null) {
6066 Slog.w(TAG, "account cannot be null");
6067 return;
6068 }
6069 if (packageName == null) {
6070 Slog.w(TAG, "packageName cannot be null");
6071 return;
6072 }
6073 if (userId < UserHandle.USER_SYSTEM) {
6074 Slog.w(TAG, "user id must be concrete");
6075 return;
6076 }
6077 if (callback == null) {
6078 Slog.w(TAG, "callback cannot be null");
6079 return;
6080 }
6081
Dmitry Dementyev7b3ea132017-05-10 12:45:02 -07006082 int visibility =
6083 resolveAccountVisibility(account, packageName, getUserAccounts(userId));
6084 if (visibility == AccountManager.VISIBILITY_NOT_VISIBLE) {
6085 Slog.w(TAG, "requestAccountAccess: account is hidden");
6086 return;
6087 }
6088
Svet Ganovf6d424f12016-09-20 20:18:53 -07006089 if (AccountManagerService.this.hasAccountAccess(account, packageName,
6090 new UserHandle(userId))) {
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006091 Bundle result = new Bundle();
6092 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
6093 callback.sendResult(result);
6094 return;
6095 }
6096
6097 final int uid;
6098 try {
6099 uid = mPackageManager.getPackageUidAsUser(packageName, userId);
6100 } catch (NameNotFoundException e) {
6101 Slog.e(TAG, "Unknown package " + packageName);
6102 return;
6103 }
6104
6105 Intent intent = newRequestAccountAccessIntent(account, packageName, uid, callback);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006106 final UserAccounts userAccounts;
6107 synchronized (mUsers) {
6108 userAccounts = mUsers.get(userId);
6109 }
Geoffrey Pitsch3560f842017-03-22 16:42:43 -04006110 SystemNotificationChannels.createAccountChannelForPackage(packageName, uid, mContext);
Svet Ganovf6d424f12016-09-20 20:18:53 -07006111 doNotification(userAccounts, account, null, intent, packageName, userId);
6112 }
6113
6114 @Override
6115 public void addOnAppPermissionChangeListener(OnAppPermissionChangeListener listener) {
6116 // Listeners are a final CopyOnWriteArrayList, hence no lock needed.
6117 mAppPermissionChangeListeners.add(listener);
6118 }
6119
6120 @Override
6121 public boolean hasAccountAccess(@NonNull Account account, @IntRange(from = 0) int uid) {
6122 return AccountManagerService.this.hasAccountAccess(account, null, uid);
Svetoslav Ganov5cb29732016-07-11 19:32:30 -07006123 }
Svet Ganov5d09c992016-09-07 09:57:41 -07006124
6125 @Override
6126 public byte[] backupAccountAccessPermissions(int userId) {
6127 synchronized (mLock) {
6128 if (mBackupHelper == null) {
6129 mBackupHelper = new AccountManagerBackupHelper(
6130 AccountManagerService.this, this);
6131 }
6132 return mBackupHelper.backupAccountAccessPermissions(userId);
6133 }
6134 }
6135
6136 @Override
6137 public void restoreAccountAccessPermissions(byte[] data, int userId) {
6138 synchronized (mLock) {
6139 if (mBackupHelper == null) {
6140 mBackupHelper = new AccountManagerBackupHelper(
6141 AccountManagerService.this, this);
6142 }
6143 mBackupHelper.restoreAccountAccessPermissions(data, userId);
6144 }
6145 }
Fyodor Kupolov1e8a94b2016-08-09 16:08:59 -07006146 }
Fyodor Kupolovda993802016-09-21 14:47:10 -07006147
6148 @VisibleForTesting
6149 static class Injector {
6150 private final Context mContext;
6151
6152 public Injector(Context context) {
6153 mContext = context;
6154 }
6155
6156 Looper getMessageHandlerLooper() {
6157 ServiceThread serviceThread = new ServiceThread(TAG,
6158 android.os.Process.THREAD_PRIORITY_FOREGROUND, true /* allowIo */);
6159 serviceThread.start();
6160 return serviceThread.getLooper();
6161 }
6162
6163 Context getContext() {
6164 return mContext;
6165 }
6166
6167 void addLocalService(AccountManagerInternal service) {
6168 LocalServices.addService(AccountManagerInternal.class, service);
6169 }
6170
6171 String getDeDatabaseName(int userId) {
6172 File databaseFile = new File(Environment.getDataSystemDeDirectory(userId),
6173 AccountsDb.DE_DATABASE_NAME);
6174 return databaseFile.getPath();
6175 }
6176
6177 String getCeDatabaseName(int userId) {
6178 File databaseFile = new File(Environment.getDataSystemCeDirectory(userId),
6179 AccountsDb.CE_DATABASE_NAME);
6180 return databaseFile.getPath();
6181 }
6182
6183 String getPreNDatabaseName(int userId) {
6184 File systemDir = Environment.getDataSystemDirectory();
6185 File databaseFile = new File(Environment.getUserSystemDirectory(userId),
6186 PRE_N_DATABASE_NAME);
6187 if (userId == 0) {
6188 // Migrate old file, if it exists, to the new location.
6189 // Make sure the new file doesn't already exist. A dummy file could have been
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006190 // accidentally created in the old location,
6191 // causing the new one to become corrupted as well.
Fyodor Kupolovda993802016-09-21 14:47:10 -07006192 File oldFile = new File(systemDir, PRE_N_DATABASE_NAME);
6193 if (oldFile.exists() && !databaseFile.exists()) {
6194 // Check for use directory; create if it doesn't exist, else renameTo will fail
6195 File userDir = Environment.getUserSystemDirectory(userId);
6196 if (!userDir.exists()) {
6197 if (!userDir.mkdirs()) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006198 throw new IllegalStateException(
6199 "User dir cannot be created: " + userDir);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006200 }
6201 }
6202 if (!oldFile.renameTo(databaseFile)) {
Dmitry Dementyev01985ff2017-01-19 16:03:39 -08006203 throw new IllegalStateException(
6204 "User dir cannot be migrated: " + databaseFile);
Fyodor Kupolovda993802016-09-21 14:47:10 -07006205 }
6206 }
6207 }
6208 return databaseFile.getPath();
6209 }
6210
6211 IAccountAuthenticatorCache getAccountAuthenticatorCache() {
6212 return new AccountAuthenticatorCache(mContext);
6213 }
6214
6215 INotificationManager getNotificationManager() {
6216 return NotificationManager.getService();
6217 }
6218 }
Chris Wren717a8812017-03-31 15:34:39 -04006219
Andrew Scullc7770d62017-05-22 17:49:58 +01006220 private static class NotificationId {
Chris Wren717a8812017-03-31 15:34:39 -04006221 final String mTag;
6222 private final int mId;
6223
6224 NotificationId(String tag, int type) {
6225 mTag = tag;
6226 mId = type;
6227 }
6228 }
Fred Quintana60307342009-03-24 22:48:12 -07006229}